Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

bindings-python-cobraphp

Python interface of CobraPHP, the Cobra static taint analyzer for PHP web applications. The package cobraphp returns plain Python data: dataclasses, enums, pathlib.Path and built-in containers.

Status

Placeholder. The Python binding is not fully implemented. Interfaces and results may change between versions.

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. The version is a pre-release. The name follows the pattern bindings-<language>-<analyzer>.

Install

From a checkout, with uv:

uv sync

uv sync installs the package, its dependencies at the versions of uv.lock and the check tools. The analysis starts the semgrep program of the scripts directory of the running Python environment, and the first one on PATH only when that directory lacks it, so the caller's PATH need not hold that directory.

The planned release wheel will bundle the CobraPHP jar. Which Java runtime it uses is undecided (open gaps). Python 3.11 or later.

Examples

Analyze a project and read the result:

from pathlib import Path
from cobraphp import AnalysisConfig, Finding, Unanalyzed, analyze_project

outputs = analyze_project(Path("/srv/project"), AnalysisConfig(context_depth=3))
for output in outputs:
    print(output)  # a Finding prints its dataclass; an Unanalyzed prints `file:line function(): reason`
complete = not any(isinstance(o, Unanalyzed) for o in outputs)
findings = [o for o in outputs if isinstance(o, Finding)]

Build once, analyze several times, and export the graphs:

from dataclasses import replace
from cobraphp import build_project

with build_project(Path("/srv/project")) as built:
    more = built.analyze(replace(built.config, extra_paths_per_sink=3))
    built.export_graphs(Path("graphs.jsonl"))

List declarations and their source lines without building a call graph or running Semgrep:

from cobraphp.analysis import list_functions, parse_project

ast = parse_project("/path/to/project", target_php="8.5")
for function in list_functions(ast):
    print(function.name, function.class_kind, function.visibility,
          function.is_static, function.is_abstract, function.parameters,
          function.has_body, function.absolute_file, function.start_line, function.end_line)

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. list_functions(project_ast: AST) -> tuple[Function, ...] returns immutable records; Function declarations specifies every field.

Build the call graph and the data flow of a project with cobraphp.analysis:

from pathlib import Path
from cobraphp.analysis import USER_INPUT, backward_slice, build_call_graph, build_data_flow, make_app_file_filter, parse_project

root = Path("/srv/project")
ast = parse_project(root, target_php="8.5", file_filter=make_app_file_filter(root))
graph = build_call_graph(ast)
calls = [e for e in graph.edges if e.type == "CCG_SITE_CALL"]
called_names = {n.id: n.props["called_name"] for n in graph.nodes if n.type == "CCG_CALL_SITE"}
flow = build_data_flow(ast, timeout_seconds=600)
for node_id in flow.tainted[USER_INPUT]:
    print(node_id, backward_slice(flow, node_id, max_depth=3))

Query a value dependency inside a function or file scope without Semgrep:

from cobraphp.analysis import is_dependent

function = next(f for f in list_functions(ast) if f.name == "total")
print(is_dependent(ast, function.node_id, sink="$total", source="$amount"))

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 specifies supported assignments, cost and limitations.

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:

from cobraphp.analysis import DatabaseWriteReach, find_database_writes

reach = DatabaseWriteReach(ast, flow, find_database_writes(ast))
for node_id in flow.tainted[USER_INPUT]:
    for write in reach.reached_database_writes(node_id):
        print(node_id, write.file, write.line, write.kind, write.table)

Apply the same file exclusions outside parse_project:

from cobraphp.analysis import app_file_filter, framework_excluded_dirs

framework_dirs = framework_excluded_dirs(root.resolve())
app_files = [p for p in root.resolve().rglob("*.php")
             if app_file_filter(p) and not any(p.is_relative_to(d) for d in framework_dirs)]

Handle a failure:

from cobraphp import ProjectNotFoundError

try:
    analyze_project(Path("/missing"))
except ProjectNotFoundError as error:
    print(error)

Design

docs/design.md states the types, functions, errors, lifecycle and open items. Companions: mapping to Kotlin, backend boundary, graph access, extension points, query languages and analysis interface, the last four proposed, and static analysis subpackage. The implementation plan is docs/todo.md. Terms are those of the glossary.

Checks

python -m compileall src
python -m pytest
python -m mypy

Run them inside the environment, for example as uv run python -m pytest. The tests marked integration run an external program; python -m pytest -m "not integration" skips them.

License

GPL-2.0-only, the licence of CobraPHP; see LICENSE.

Metadata

Release files for cobraphp 0.1.0.dev6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cobraphp 0.1.0.dev6
File Size Uploaded Provenance Actions
cobraphp-0.1.0.dev6.tar.gz 79.4 kB Without provenance Details for cobraphp-0.1.0.dev6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cobraphp 0.1.0.dev6
File Interpreter ABI Platform Actions
cobraphp-0.1.0.dev6-py3-none-any.whl Python 3 none any Details for cobraphp-0.1.0.dev6-py3-none-any.whl

Total release size: 170.2 kB

Release files / cobraphp-0.1.0.dev6.tar.gz

Download URL cobraphp-0.1.0.dev6.tar.gz
Size 79.4 kB
Tags Source
SHA-256 checksum
How to use checksums
799e6949eb1b398f856ceb2363aa7067b086c6570f9f283c081e6e7cb3ff8ff1
BLAKE2b-256 checksum
How to use checksums
c235a783cff19197471da5ee2f30207d66d97d4551bca302c38498523a33f232
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.18

Release files / cobraphp-0.1.0.dev6-py3-none-any.whl

Download URL cobraphp-0.1.0.dev6-py3-none-any.whl
Size 90.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4b31e9a4093c1a6fc276e0fe549ce6c2840077ba78bc18af9f10dd56e6d4a7f9
BLAKE2b-256 checksum
How to use checksums
d02059c50fdb0a82940da747f9ce6fc37a67fb5fbfc7187c3aacb60d365c16c9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.18

Security for cobraphp 0.1.0.dev6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page