cobraphp 0.1.0.dev5__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
@@ -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
  ]
@@ -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,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)
@@ -0,0 +1,143 @@
1
+ """Interprocedural argument and return edges of the existing call graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import cast
6
+
7
+ from php_parser_py import AST, Node
8
+
9
+ from ._call_graph import CallGraph
10
+ from ._taint_graph import DataFlowGraph, ensure_node as _ensure_node
11
+ from ._taint_rules import CALLABLE_TYPES
12
+
13
+ def build_interproc_edges(
14
+ ast: AST,
15
+ call_graph: CallGraph,
16
+ dataflow_graph: DataFlowGraph,
17
+ ) -> None:
18
+ """Build argument->parameter and return->callsite edges via CallGraph."""
19
+ for cg_node_id in call_graph.storage.get_nodes():
20
+ node_type = call_graph.storage.get_node_prop(cg_node_id, "node_type")
21
+ if node_type != "call_site":
22
+ continue
23
+
24
+ site_node = call_graph.get_site_node(cg_node_id)
25
+ callees = call_graph.get_callees(cg_node_id)
26
+
27
+ if not callees:
28
+ _build_overapprox_edges(ast, site_node.argument_ids, cg_node_id, dataflow_graph)
29
+ continue
30
+
31
+ for callee in callees:
32
+ _build_arg_to_param_edges(
33
+ ast,
34
+ site_node.argument_ids,
35
+ callee.parameter_ids,
36
+ dataflow_graph,
37
+ )
38
+ _build_return_to_callsite_edges(
39
+ ast,
40
+ callee.node_id,
41
+ cg_node_id,
42
+ dataflow_graph,
43
+ )
44
+
45
+
46
+ def _build_arg_to_param_edges(
47
+ ast: AST,
48
+ argument_ids: list[str],
49
+ parameter_ids: list[str],
50
+ dataflow_graph: DataFlowGraph,
51
+ ) -> None:
52
+ """Create edges from call site arguments to callee parameters by position."""
53
+ min_len = min(len(argument_ids), len(parameter_ids))
54
+ for i in range(min_len):
55
+ arg_expr_id = _get_arg_expression_id(ast, argument_ids[i])
56
+ if not arg_expr_id:
57
+ continue
58
+ param_var_id = _get_param_variable_id(ast, parameter_ids[i])
59
+ if not param_var_id:
60
+ continue
61
+ _ensure_node(dataflow_graph, arg_expr_id)
62
+ _ensure_node(dataflow_graph, param_var_id)
63
+ dataflow_graph.add_structural_edge(arg_expr_id, param_var_id)
64
+
65
+
66
+ def _build_overapprox_edges(
67
+ ast: AST,
68
+ argument_ids: list[str],
69
+ callsite_id: str,
70
+ dataflow_graph: DataFlowGraph,
71
+ ) -> None:
72
+ """Over-approximate taint through an unresolved call.
73
+
74
+ For a call site with no resolved callee (library, builtin, or dynamic
75
+ dispatch), connect each argument expression to the call-site node so a
76
+ tainted argument taints the call's result. Semgrep OSS provides no
77
+ interprocedural taint to fall back on.
78
+ """
79
+ for arg_node_id in argument_ids:
80
+ arg_expr_id = _get_arg_expression_id(ast, arg_node_id)
81
+ if not arg_expr_id:
82
+ continue
83
+ _ensure_node(dataflow_graph, arg_expr_id)
84
+ _ensure_node(dataflow_graph, callsite_id)
85
+ dataflow_graph.add_structural_edge(arg_expr_id, callsite_id)
86
+
87
+
88
+ def _build_return_to_callsite_edges(
89
+ ast: AST,
90
+ callee_func_id: str,
91
+ callsite_id: str,
92
+ dataflow_graph: DataFlowGraph,
93
+ ) -> None:
94
+ """Create edges from callee return expressions to call site node."""
95
+ func_node = ast.node(callee_func_id)
96
+ if func_node is None:
97
+ return
98
+
99
+ for return_stmt in _own_return_statements(ast, func_node):
100
+ return_children = list(ast.succ(return_stmt))
101
+ if not return_children:
102
+ continue
103
+ return_expr = return_children[0]
104
+ _ensure_node(dataflow_graph, return_expr.id)
105
+ _ensure_node(dataflow_graph, callsite_id)
106
+ dataflow_graph.add_structural_edge(return_expr.id, callsite_id)
107
+
108
+
109
+ def _own_return_statements(ast: AST, func_node: Node) -> list[Node]:
110
+ # Stmt_Return nodes at any depth in a callable's body, excluding those of
111
+ # callables nested inside it.
112
+ found: list[Node] = []
113
+ pending = list(ast.succ(func_node))
114
+ while pending:
115
+ node = pending.pop()
116
+ if node.node_type in CALLABLE_TYPES:
117
+ continue
118
+ if node.node_type == "Stmt_Return":
119
+ found.append(node)
120
+ pending.extend(ast.succ(node))
121
+ return found
122
+
123
+
124
+ def _get_arg_expression_id(ast: AST, arg_node_id: str) -> str | None:
125
+ """Get the expression node ID inside an Arg wrapper node."""
126
+ arg_node = ast.node(arg_node_id)
127
+ if arg_node is None:
128
+ return None
129
+ children = list(ast.succ(arg_node))
130
+ if not children:
131
+ return None
132
+ return cast(str, children[0].id)
133
+
134
+
135
+ def _get_param_variable_id(ast: AST, param_node_id: str) -> str | None:
136
+ """Get the Expr_Variable node ID inside a Param wrapper node."""
137
+ param_node = ast.node(param_node_id)
138
+ if param_node is None:
139
+ return None
140
+ for child in ast.succ(param_node):
141
+ if child.node_type == "Expr_Variable":
142
+ return cast(str, child.id)
143
+ return None
@@ -0,0 +1,85 @@
1
+ """Per-scope expression edges supplementing reaching-definition def-use chains."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from php_parser_py import AST, Node
6
+
7
+ from ._callee_index import CLASS_LIKE_KINDS
8
+ from ._declarations import CALLABLE_DECL_TYPES
9
+ from ._defuse_assignments import (
10
+ ASSIGN_TYPES, PLAIN_ASSIGN_TYPES, REFERENCE_ASSIGN_TYPES, assignment_parts, field_children, written_targets,
11
+ )
12
+ from ._taint_graph import DataFlowGraph, ensure_node
13
+
14
+ # Wrappers hold expression values but are not themselves expressions.
15
+ _VALUE_WRAPPERS = frozenset({"Arg", "ArrayItem", "ClosureUse"})
16
+
17
+
18
+ def scope_nodes(ast: AST, scope: Node) -> tuple[Node, ...]:
19
+ found: list[Node] = []
20
+ pending = [scope]
21
+ while pending:
22
+ node = pending.pop()
23
+ found.append(node)
24
+ if node.node_type in CLASS_LIKE_KINDS:
25
+ continue
26
+ children = list(ast.succ(node))
27
+ if node.id != scope.id and node.node_type in CALLABLE_DECL_TYPES:
28
+ children = [child for child in children if child.node_type == "ClosureUse"]
29
+ pending.extend(reversed(children))
30
+ return tuple(found)
31
+
32
+
33
+ def extend_value_edges(ast: AST, nodes: tuple[Node, ...], graph: DataFlowGraph) -> None:
34
+ owned = {node.id for node in nodes}
35
+ for node in nodes:
36
+ if node.node_type.startswith("Expr_"):
37
+ ensure_node(graph, node.id)
38
+ if node.node_type in ASSIGN_TYPES:
39
+ _assignment_edges(ast, node, graph)
40
+ continue
41
+ if node.node_type == "Stmt_Foreach":
42
+ _foreach_edges(ast, node, graph)
43
+ continue
44
+ if not node.node_type.startswith(("Expr_", "Scalar_")) and node.node_type not in _VALUE_WRAPPERS:
45
+ continue
46
+ for child in (child for child in ast.succ(node) if child.id in owned):
47
+ _connect(graph, child.id, node.id)
48
+
49
+
50
+ def _assignment_edges(ast: AST, node: Node, graph: DataFlowGraph) -> None:
51
+ parts = assignment_parts(ast, node)
52
+ if parts is None:
53
+ return
54
+ target, value = parts
55
+ _connect(graph, value.id, node.id)
56
+ if node.node_type not in PLAIN_ASSIGN_TYPES:
57
+ _connect(graph, target.id, node.id)
58
+ for written in written_targets(ast, target):
59
+ _connect(graph, value.id, written.id)
60
+ _array_write_edges(ast, written, graph)
61
+ if node.node_type in REFERENCE_ASSIGN_TYPES:
62
+ _connect(graph, written.id, value.id)
63
+
64
+
65
+ def _foreach_edges(ast: AST, node: Node, graph: DataFlowGraph) -> None:
66
+ values = field_children(ast, node, "expr")
67
+ if not values:
68
+ return
69
+ for target in (*field_children(ast, node, "keyVar"), *field_children(ast, node, "valueVar")):
70
+ for written in written_targets(ast, target):
71
+ _connect(graph, values[0].id, written.id)
72
+ _array_write_edges(ast, written, graph)
73
+
74
+
75
+ def _array_write_edges(ast: AST, target: Node, graph: DataFlowGraph) -> None:
76
+ if target.node_type != "Expr_ArrayDimFetch":
77
+ return
78
+ for base in field_children(ast, target, "var"):
79
+ _connect(graph, target.id, base.id)
80
+
81
+
82
+ def _connect(graph: DataFlowGraph, source: str, sink: str) -> None:
83
+ ensure_node(graph, source)
84
+ ensure_node(graph, sink)
85
+ graph.add_structural_edge(source, sink)
@@ -0,0 +1,138 @@
1
+ """Immutable function declarations and executable file scopes of a project AST."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal, TypeAlias, cast
7
+
8
+ from php_parser_py import AST, Node, NodeNotInFileError
9
+
10
+ from ._ast_types import _php_ast_types
11
+ from ._callee_index import CLASS_LIKE_KINDS, METHOD_DECL_TYPE, _child_name, enclosing_class
12
+ from ._declarations import ARROW_FUNCTION_TYPE, CALLABLE_DECL_TYPES, CALLABLE_KINDS, callable_name
13
+ from ._errors import StaticAnalysisError
14
+ from ._records import _relative_file
15
+
16
+ _ClassKind: TypeAlias = Literal["class", "interface", "trait", "enum"]
17
+ _FunctionKind: TypeAlias = Literal["function", "method", "closure", "arrow_function", "file"]
18
+
19
+ # PHP-Parser method modifier bits.
20
+ _PROTECTED = 2
21
+ _PRIVATE = 4
22
+ _STATIC = 8
23
+ _ABSTRACT = 16
24
+
25
+ _TOP_LEVEL_WRAPPERS = frozenset(cast(list[str], _php_ast_types()["top_level_wrappers"]["values"]))
26
+ _TOP_LEVEL_DECLARATIONS = frozenset(cast(list[str], _php_ast_types()["top_level_declarations"]["values"]))
27
+
28
+
29
+ @dataclass(frozen=True, slots=True, kw_only=True)
30
+ class Function:
31
+ """A callable declaration or executable file scope with inclusive source lines.
32
+
33
+ Names and node ids join the call graph's function entities. File paths are
34
+ project-relative POSIX paths. Class fields describe the nearest lexical owner.
35
+ `has_body` excludes empty and comment-only bodies; arrows have an implicit return.
36
+ """
37
+
38
+ node_id: str
39
+ name: str
40
+ class_name: str | None
41
+ class_kind: _ClassKind | None
42
+ kind: _FunctionKind
43
+ file: str
44
+ start_line: int
45
+ end_line: int
46
+ has_body: bool
47
+ visibility: Literal["public", "protected", "private"] | None
48
+ is_static: bool
49
+ is_abstract: bool
50
+ parameters: tuple[str, ...]
51
+ absolute_file: str | None
52
+
53
+
54
+ def list_functions(project_ast: AST) -> tuple[Function, ...]:
55
+ """Return declarations and executable file scopes of a php-parser-py AST.
56
+
57
+ Builds no call graph and runs no Semgrep. Results sort by file, start line
58
+ and node id. Raises `StaticAnalysisError` for malformed AST metadata.
59
+ """
60
+ if not isinstance(project_ast, AST):
61
+ raise StaticAnalysisError("list_functions requires a php-parser-py AST")
62
+ try:
63
+ records = [_function(project_ast, node) for node in project_ast.nodes()
64
+ if node.node_type in CALLABLE_DECL_TYPES]
65
+ records.extend(_function(project_ast, node) for node in project_ast.file_nodes()
66
+ if _has_top_level_code(project_ast, node))
67
+ return tuple(sorted(records, key=lambda record: (record.file, record.start_line, record.node_id)))
68
+ except (KeyError, TypeError, ValueError, NodeNotInFileError) as exc:
69
+ raise StaticAnalysisError(f"Failed to list functions: {exc}") from exc
70
+
71
+
72
+ def _function(ast: AST, node: Node) -> Function:
73
+ start, end = node.start_line, node.end_line
74
+ if start < 1 or end < start:
75
+ raise StaticAnalysisError(f"Node {node.id} has invalid line range {start}:{end}")
76
+ owner = enclosing_class(ast, node)
77
+ is_file = node.node_type == "File"
78
+ return Function(
79
+ node_id=node.id, name=_relative_file(node) if is_file else callable_name(ast, node),
80
+ class_name=None if owner is None else _child_name(ast, owner, frozenset({"Identifier"})),
81
+ class_kind=None if owner is None else cast(_ClassKind, CLASS_LIKE_KINDS[owner.node_type]),
82
+ kind="file" if is_file else cast(_FunctionKind, CALLABLE_KINDS[node.node_type]),
83
+ file=_relative_file(node), start_line=start, end_line=end,
84
+ has_body=is_file or _has_body(ast, node),
85
+ visibility=_visibility(node), is_static=bool(node.get("static", False) or int(node.get("flags", 0)) & _STATIC),
86
+ is_abstract=_is_abstract(node, owner), parameters=_parameter_names(ast, node),
87
+ absolute_file=node.absolute_path,
88
+ )
89
+
90
+
91
+ def _has_body(ast: AST, node: Node) -> bool:
92
+ field = "expr" if node.node_type == ARROW_FUNCTION_TYPE else "stmts"
93
+ return any(child.node_type != "Stmt_Nop" for child in ast.succ(node, lambda edge: edge.get("field") == field))
94
+
95
+
96
+ def _has_top_level_code(ast: AST, file: Node) -> bool:
97
+ pending = list(ast.succ(file, lambda edge: edge.get("field") == "stmts"))
98
+ while pending:
99
+ node = pending.pop()
100
+ if node.node_type in _TOP_LEVEL_WRAPPERS:
101
+ pending.extend(ast.succ(node, lambda edge: edge.get("field") == "stmts"))
102
+ continue
103
+ if node.node_type in CALLABLE_DECL_TYPES or node.node_type in CLASS_LIKE_KINDS:
104
+ continue
105
+ if node.node_type not in _TOP_LEVEL_DECLARATIONS:
106
+ return True
107
+ return False
108
+
109
+
110
+
111
+ def _visibility(node: Node) -> Literal["public", "protected", "private"] | None:
112
+ if node.node_type != METHOD_DECL_TYPE:
113
+ return None
114
+ flags = int(node.get("flags", 0))
115
+ if flags & _PRIVATE:
116
+ return "private"
117
+ return "protected" if flags & _PROTECTED else "public"
118
+
119
+
120
+ def _is_abstract(node: Node, owner: Node | None) -> bool:
121
+ if node.node_type != METHOD_DECL_TYPE:
122
+ return False
123
+ return bool(int(node.get("flags", 0)) & _ABSTRACT) or (
124
+ owner is not None and CLASS_LIKE_KINDS[owner.node_type] == "interface"
125
+ )
126
+
127
+
128
+ def _parameter_names(ast: AST, node: Node) -> tuple[str, ...]:
129
+ parameters = ast.succ(node, lambda edge: edge.get("field") == "params")
130
+ return tuple(_parameter_name(ast, parameter) for parameter in parameters)
131
+
132
+
133
+ def _parameter_name(ast: AST, parameter: Node) -> str:
134
+ variable = next(iter(ast.succ(parameter, lambda edge: edge.get("field") == "var")), None)
135
+ name = None if variable is None else variable.get("name")
136
+ if not isinstance(name, str) or not name:
137
+ raise StaticAnalysisError(f"Parameter {parameter.id} has no variable name")
138
+ return name
@@ -0,0 +1,43 @@
1
+ """Parse project directories through the analysis interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Callable
7
+ from pathlib import Path
8
+
9
+ from php_parser_py import AST, PHPVersion, RunnerError
10
+ from php_parser_py import parse_project as _parse_project
11
+
12
+ from ._errors import StaticAnalysisError
13
+
14
+
15
+ def parse_project(
16
+ project_path: str | Path,
17
+ *,
18
+ target_php: str,
19
+ file_filter: Callable[[Path], bool] | None = None,
20
+ ) -> AST:
21
+ """Parse a directory for an ASCII major.minor PHP version string.
22
+
23
+ `file_filter` receives absolute paths; None uses the parser's PHP suffixes.
24
+ Unreadable or invalid PHP files are warned about and retained in
25
+ `AST.skipped_files`; the remaining files are parsed.
26
+
27
+ Raises `StaticAnalysisError` for invalid arguments, directory errors or
28
+ parser runtime failures. Other exceptions from `file_filter` propagate.
29
+ """
30
+ version = _target_version(target_php)
31
+ if not isinstance(project_path, (str, Path)) or (file_filter is not None and not callable(file_filter)):
32
+ raise StaticAnalysisError("Invalid project path or file filter")
33
+ try:
34
+ return _parse_project(str(project_path), target_php=version, file_filter=file_filter)
35
+ except (OSError, ValueError, TypeError, RuntimeError, RunnerError) as exc:
36
+ raise StaticAnalysisError(f"Failed to parse project: {exc}") from exc
37
+
38
+
39
+ def _target_version(version: str) -> PHPVersion:
40
+ if not isinstance(version, str) or re.fullmatch(r"[0-9]+\.[0-9]+", version) is None:
41
+ raise StaticAnalysisError("PHP version must be a major.minor string, such as '7.4'")
42
+ major, minor = version.split(".")
43
+ return PHPVersion(int(major), int(minor))
@@ -16,7 +16,7 @@ from php_parser_py import AST, Node
16
16
  from ..graphs import GraphEdge, GraphExport, GraphNode
17
17
  from . import _taint_graph
18
18
  from ._call_graph import CallGraph
19
- from ._callee_index import FUNCTION_CALL_TYPE, CalleeIndex, _enclosing_class_name
19
+ from ._callee_index import FUNCTION_CALL_TYPE, CalleeIndex, _enclosing_class_name, called_name
20
20
  from ._errors import StaticAnalysisError
21
21
  from ._taint_rules import TAINT_RULES
22
22
 
@@ -74,7 +74,8 @@ def call_graph_export(project_ast: AST, call_graph: CallGraph) -> GraphExport:
74
74
  entities.append(_entity(caller_id, _relative_file(file_node), file_node, None))
75
75
  sites.append(
76
76
  GraphNode(id=node_id, graph=CCG, type=CALL_SITE, state=None, path=None,
77
- props={"file": _relative_file(site), "line": site.start_line})
77
+ props={"file": _relative_file(site), "line": site.start_line,
78
+ "called_name": called_name(project_ast, site)})
78
79
  )
79
80
  edges.append(GraphEdge(source=caller_id, target=node_id, type=FUNC_CONTAIN, labels=(), props={}))
80
81
  for callee in call_graph.get_callees(node_id):
@@ -198,3 +198,8 @@ class DataFlowGraph(AbcGraphQuerier[DataFlowNode, DataFlowEdge]): # type: ignor
198
198
  if pred not in visited:
199
199
  queue.append((pred, depth + 1))
200
200
  return result
201
+
202
+
203
+ def ensure_node(graph: DataFlowGraph, node_id: str) -> None:
204
+ if not graph.storage.contains_node(node_id):
205
+ graph.add_dataflow_node(node_id)
@@ -0,0 +1,109 @@
1
+ """Match named PHP values against one scope's existing def-use graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import deque
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from php_parser_py import AST, Node
11
+
12
+ from ._declarations import CALLABLE_DECL_TYPES
13
+ from ._defuse_builder import build_scope_edges
14
+ from ._errors import StaticAnalysisError
15
+ from ._taint_graph import DataFlowGraph
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class _ExpressionNames:
20
+ by_node: Mapping[str, str]
21
+ by_name: Mapping[str, tuple[str, ...]]
22
+
23
+
24
+ def is_dependent(project_ast: AST, function_id: str, *, sink: str, source: str) -> bool:
25
+ """Whether a sink expression depends transitively on a source in one function.
26
+
27
+ Names match exact source expression text after removing all whitespace.
28
+ The relation is intraprocedural and flow-insensitive; a present value
29
+ depends on itself. No call graph or Semgrep runs. Work is bounded by
30
+ the selected function's AST, edges and source text, independent of the
31
+ rest of the project; expression text and assignment chains can be quadratic.
32
+
33
+ Raises `StaticAnalysisError` for an unknown/non-function id, invalid
34
+ name arguments, malformed metadata or an unavailable source range.
35
+ """
36
+ if not isinstance(sink, str) or not isinstance(source, str):
37
+ raise StaticAnalysisError("Dependency names must be PHP expression strings")
38
+ try:
39
+ scope = _function_scope(project_ast, function_id)
40
+ graph = DataFlowGraph()
41
+ nodes = build_scope_edges(project_ast, scope, graph)
42
+ names = _expression_names(scope, nodes)
43
+ return _depends(graph, names, (_normalize(sink), _normalize(source)))
44
+ except (KeyError, OSError, TypeError, ValueError) as exc:
45
+ raise StaticAnalysisError(f"Failed to query value dependency: {exc}") from exc
46
+
47
+
48
+ def _function_scope(ast: AST, node_id: str) -> Node:
49
+ scope = ast.node(node_id)
50
+ if scope.node_type not in CALLABLE_DECL_TYPES and scope.node_type != "File":
51
+ raise StaticAnalysisError(f"Node {node_id} is not a function or file scope")
52
+ return scope
53
+
54
+
55
+ def _expression_names(scope: Node, nodes: tuple[Node, ...]) -> _ExpressionNames:
56
+ text = _source_range(scope)
57
+ start = scope.start_file_pos
58
+ by_node: dict[str, str] = {}
59
+ by_name: dict[str, list[str]] = {}
60
+ for node in nodes:
61
+ if not node.node_type.startswith("Expr_"):
62
+ continue
63
+ first, last = node.start_file_pos - start, node.end_file_pos - start + 1
64
+ if first < 0 or last > len(text) or last <= first:
65
+ raise StaticAnalysisError(f"Expression {node.id} has an invalid source range")
66
+ name = _normalize(text[first:last].decode("utf-8", "surrogateescape"))
67
+ by_node[node.id] = name
68
+ by_name.setdefault(name, []).append(node.id)
69
+ return _ExpressionNames(by_node, {name: tuple(ids) for name, ids in by_name.items()})
70
+
71
+
72
+ def _source_range(scope: Node) -> bytes:
73
+ path = scope.absolute_path
74
+ if path is None:
75
+ raise StaticAnalysisError(f"Node {scope.id} has no absolute file path")
76
+ start, end = scope.start_file_pos, scope.end_file_pos
77
+ if start < 0 or end < start:
78
+ raise StaticAnalysisError(f"Node {scope.id} has an invalid source range")
79
+ with Path(path).open("rb") as source_file:
80
+ source_file.seek(start)
81
+ text = source_file.read(end - start + 1)
82
+ if len(text) != end - start + 1:
83
+ raise StaticAnalysisError(f"Source range for {scope.id} is unavailable")
84
+ return text
85
+
86
+
87
+ def _depends(graph: DataFlowGraph, names: _ExpressionNames, query: tuple[str, str]) -> bool:
88
+ sink, source = query
89
+ targets = set(names.by_name.get(sink, ()))
90
+ queue = deque(names.by_name.get(source, ()))
91
+ visited: set[str] = set()
92
+ expanded: set[str] = set()
93
+ while queue:
94
+ current = queue.popleft()
95
+ if current in targets:
96
+ return True
97
+ if current in visited:
98
+ continue
99
+ visited.add(current)
100
+ name = names.by_node.get(current)
101
+ if name is not None and name not in expanded:
102
+ expanded.add(name)
103
+ queue.extend(names.by_name[name])
104
+ queue.extend(graph.storage.successors(current))
105
+ return False
106
+
107
+
108
+ def _normalize(name: str) -> str:
109
+ return "".join(name.split())
@@ -12,11 +12,6 @@ values = [
12
12
  "Expr_ConstFetch", "Expr_ClassConstFetch",
13
13
  ]
14
14
 
15
- [callable_types]
16
- values = [
17
- "Stmt_Function", "Stmt_ClassMethod", "Expr_Closure", "Expr_ArrowFunction",
18
- ]
19
-
20
15
  [assign_node_types]
21
16
  values = [
22
17
  "Expr_Assign",
@@ -27,3 +22,27 @@ values = [
27
22
  "Expr_AssignOp_ShiftLeft", "Expr_AssignOp_ShiftRight",
28
23
  "Expr_AssignOp_Pow", "Expr_AssignOp_Coalesce",
29
24
  ]
25
+
26
+ # Public record kinds for the callable and class-like declarations.
27
+ [callable_kinds]
28
+ Stmt_Function = "function"
29
+ Stmt_ClassMethod = "method"
30
+ Expr_Closure = "closure"
31
+ Expr_ArrowFunction = "arrow_function"
32
+
33
+ [class_like_kinds]
34
+ Stmt_Class = "class"
35
+ Stmt_Interface = "interface"
36
+ Stmt_Trait = "trait"
37
+ Stmt_Enum = "enum"
38
+
39
+ # Wrappers contain top-level statements; the other types execute no file body.
40
+ [top_level_wrappers]
41
+ values = ["Stmt_Namespace", "Stmt_Declare"]
42
+
43
+ [top_level_declarations]
44
+ values = ["Stmt_Use", "Stmt_GroupUse", "Stmt_Const", "Stmt_Nop"]
45
+
46
+ # Reference assignments in the complete per-scope expression-flow view.
47
+ [reference_assign_types]
48
+ values = ["Expr_AssignRef"]
@@ -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.dev6
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
@@ -8,32 +8,39 @@ cobraphp/graphs.py,sha256=5f4ZbC4mouxlkeGTEhivDbhyK2ZwdO87KPWCnCnaXLI,1793
8
8
  cobraphp/project.py,sha256=LL4RhwIB-eInyIqD30Us948bDFizDZzK31YhgZOOug0,1497
9
9
  cobraphp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
10
  cobraphp/results.py,sha256=fc5CUVPZ__SDdKyxQ1UyQJt3FSM6yfzOfaBCGL1Wtss,3055
11
- cobraphp/analysis/__init__.py,sha256=OnbdawwvGN1Qi-XQMo-msRp53U8JGV4pTXBaDLZ6L8g,2978
12
- cobraphp/analysis/_ast_types.py,sha256=4_7ga_CcAbRxLTKuXCn-Bhn7Elprnq13r561hxJTtSw,661
13
- cobraphp/analysis/_call_builder.py,sha256=3e7zo7xBkV4jSgET6dXQMEPsTRhTYExY7uGWoBSeSJg,6258
11
+ cobraphp/analysis/__init__.py,sha256=s-5zkF4CmBl-WwB97kUF7Jws8oW49zNpVJQwhLcBzIQ,3197
12
+ cobraphp/analysis/_ast_types.py,sha256=vi0gkMxFHLDK7Jd_Qgj1h5iVf9BTGR2x5OhOtIkkq5E,926
13
+ cobraphp/analysis/_call_builder.py,sha256=dfrapjF7K2ZQFTs814QIvK5XMb8ufKJxoUcgzjfz9PM,5361
14
14
  cobraphp/analysis/_call_graph.py,sha256=nlo_8VCvc5JzVTrH7MMicbT49Rgwd-EuAewLrJoALx8,8081
15
15
  cobraphp/analysis/_call_graph_nodes.py,sha256=MuXtGdNe4iNals-0yPeLhykdxEr1JEjk1h_YypLLIaA,6205
16
- cobraphp/analysis/_callee_index.py,sha256=fgVHrJ3v5ng1KKYkpOgSgDG4doEKBDleSX-pOW08cfQ,5323
16
+ cobraphp/analysis/_callee_index.py,sha256=ZiqjNLCkEwWsn9OdC02xxgE-Bczy60HfdO_vAgTBRYo,5862
17
17
  cobraphp/analysis/_database_write_reach.py,sha256=7QX01xuwbOR-Z4G5_y9T2NZY5ctk_s2RtpthCEIxDaI,9255
18
18
  cobraphp/analysis/_database_writes.py,sha256=-CbUA1ox3nmhbBJjY5VL0BYkCtabcfrrvp7AeRZ2uaY,75811
19
- cobraphp/analysis/_defuse_builder.py,sha256=lV6mrt2RmW5SVWma5yJDNzdtlFF-B8eGrJCYS35yAY4,14749
19
+ cobraphp/analysis/_declarations.py,sha256=P7PCmghLuQjnqBZo8Kd5Gt21k_wjfbaPgLUHbReCw4Y,1126
20
+ cobraphp/analysis/_defuse_assignments.py,sha256=f_LrdQeNExdSpGsadjKETd4GI97HC_64C3Qq4BAbO-c,1466
21
+ cobraphp/analysis/_defuse_builder.py,sha256=B3rf2QmR5YM6xw1150pi1d1TSYnTWbXB7cdZtyI4Ylc,10981
22
+ cobraphp/analysis/_defuse_interproc.py,sha256=kNBICZkbYxEwtLtPfkxEPsNe_aHN_rHQ8K-n4OANOSw,4749
23
+ cobraphp/analysis/_defuse_values.py,sha256=1T2D6T4XWz1mK1y_fkw5h5WUlI1c-rlOG7X0X6GwP54,3210
20
24
  cobraphp/analysis/_errors.py,sha256=cn71QQpesqbkitJdkg9bMIcvXlPixRxol7CjOMZM0i0,531
21
25
  cobraphp/analysis/_file_filter.py,sha256=8z9-2ZANnjRGqDbnP6UQcUf0Hpjf_4C72yTgC8cqcDw,6056
26
+ cobraphp/analysis/_functions.py,sha256=NoBHi4XBbjSeKZ-dQESznpWCPe-6smNvmy5NChOXkCk,5781
22
27
  cobraphp/analysis/_node_order.py,sha256=LkPGeKxE1b06rPOCSUqnKXYqEMHjPx45oXVjkjRQ2mA,1699
28
+ cobraphp/analysis/_parsing.py,sha256=gFLgQ2Oe5rwls0XVDBnAh4evech2VXzEt73LnGrMZnY,1712
23
29
  cobraphp/analysis/_project_root.py,sha256=cuS_sOGZBqDp5H6HWn_xLaxAyVlsfxwADgc0MheC-fY,1050
24
- cobraphp/analysis/_records.py,sha256=GcafhC4iaJS2U-idCe5l3VM-AawBAMSmikiKAHaOQMA,5937
30
+ cobraphp/analysis/_records.py,sha256=ZTC9RCL1DoOi7ctLvBk6P10QqXaOqdxoNX776UUuuRE,6026
25
31
  cobraphp/analysis/_semgrep_runner.py,sha256=HwLfxi3Ql86IRQhyNvvtoa-uOPkWF168GfGed7d8_SA,14588
26
32
  cobraphp/analysis/_source_kinds.py,sha256=0LH0kkSQ13c7Ys2kf4QhwuCpyKKC3rn6c9ZXadkr47Q,144
27
- cobraphp/analysis/_taint_graph.py,sha256=HXd_g-yuzItyWQ9pj_p1M91UHKpoLOBwlBPqmwbnUuQ,7661
33
+ cobraphp/analysis/_taint_graph.py,sha256=UZePCPW4dcfwckJ5R4UuIetIoNcJc4Io_H4qX0rZWro,7814
28
34
  cobraphp/analysis/_taint_propagator.py,sha256=xmP_3G9T5Sgeie7yeq6Fca9bUsRyOnnwYzf-gyD_-iQ,10741
29
35
  cobraphp/analysis/_taint_rules.py,sha256=b77hFwh6zURdqfx6jWZwTbS24hE03t7wtlYEckgaO5I,4822
36
+ cobraphp/analysis/_value_dependency.py,sha256=AlMPHJLaEyMfdUeaDe2w3b9M5MU37_Jz8eEvYVG6Mq0,4333
30
37
  cobraphp/analysis/database_writes.toml,sha256=zeQbntZ5T6LbkIag6--v5uplnfHxGuT-FyNqpvwCgWY,18797
31
38
  cobraphp/analysis/frameworks.toml,sha256=MUGFYwMC6P7h-cj2_WUMGytYHWA9ZCTuGg_7LTkmy1k,1885
32
- cobraphp/analysis/php_ast_types.toml,sha256=fvh3SfjGm1IyJvRkBAhnOLnxCdT5ejowxDBRuOIxOcg,1032
39
+ cobraphp/analysis/php_ast_types.toml,sha256=yMtPKzOHDY9nm6NCKtMzxziug1z29kC3rSfh2bk46DM,1598
33
40
  cobraphp/analysis/rules/database_taint.yaml,sha256=xCx64v2RjponPfEYZOQUqSqP_ltV8YB-t5NldjOstcI,3495
34
41
  cobraphp/analysis/rules/user_input_taint.yaml,sha256=47nknffSg_wIKGPg8Ya-r4POa4nWswopju2IEkcFvtc,6998
35
- cobraphp-0.1.0.dev5.dist-info/licenses/LICENSE,sha256=-cN1ob5KQfe3AwHdg8kcuJ5BVnR4hZt37vN1pS14JQU,18091
36
- cobraphp-0.1.0.dev5.dist-info/METADATA,sha256=RLJuNiaMO9hP1CI_6hBh4cucTjoqAHXkMHu36FX9rNo,5239
37
- cobraphp-0.1.0.dev5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
38
- cobraphp-0.1.0.dev5.dist-info/top_level.txt,sha256=55CayiaOZMnPngJQf8IqO50E-l0BQONI8DTpnn-gtJk,9
39
- cobraphp-0.1.0.dev5.dist-info/RECORD,,
42
+ cobraphp-0.1.0.dev6.dist-info/licenses/LICENSE,sha256=-cN1ob5KQfe3AwHdg8kcuJ5BVnR4hZt37vN1pS14JQU,18091
43
+ cobraphp-0.1.0.dev6.dist-info/METADATA,sha256=DRRJFfxoPzr-rGCNNeOseNWfHzspBSkopTzCqmy5MyM,6818
44
+ cobraphp-0.1.0.dev6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
45
+ cobraphp-0.1.0.dev6.dist-info/top_level.txt,sha256=55CayiaOZMnPngJQf8IqO50E-l0BQONI8DTpnn-gtJk,9
46
+ cobraphp-0.1.0.dev6.dist-info/RECORD,,