Code Audit Public APIs#
Public Interfaces module#
License GPLv3 or higher.
2025 - 2026 Created by Maikel Mardjan and all contributors - https://nocomplexity.com/
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Public API functions for Python Code Audit aka codeaudit on pypi.org
- codeaudit.api_interfaces.egress_check(input_path)[source]#
Scan Python code for potential data egress or privacy leaks.
This function performs a static analysis of Python source code to detect patterns that may indicate privacy or data-egress risks. The analysis is based on an Abstract Syntax Tree (AST) inspection of the provided source.
- The input can refer to:
A local directory containing a Python package
A single Python file
A PyPI package name (the package will be downloaded and scanned)
Depending on the input type, the function performs a file-level or package-level scan and returns structured metadata together with the detected findings.
- Parameters:
input_path (str) – Location of the Python code to analyze. This can be: - Path to a local Python package directory. - Path to a single .py file. - Name of a package published on PyPI.
- Returns:
Dictionary containing scan metadata and analysis results. The dictionary always includes basic metadata such as the tool name, version, and generation timestamp. Additional fields depend on the input type:
- Directory or PyPI package input
package_name: Name of the scanned package.package_release(PyPI only): Package version.Package-level privacy findings.
- Single file input
file_name: Name of the scanned file.file_privacy_check: Results of the file-level analysis.
- Invalid input
{"Error": "<message>"}
- Return type:
dict
- Raises:
None – All errors are handled internally and reported in the
returned dictionary instead of raising exceptions. –
Notes:
The scan uses static AST analysis and does not execute code.
PyPI packages are downloaded to a temporary directory before scanning.
Temporary directories are automatically removed after the scan.
Only syntactically valid Python files that can be parsed into an AST are analyzed.
Examples for API use:
Scan a local Python file:
>>> data_egress_scan("script.py")
Scan a local package directory:
>>> data_egress_scan("./my_package")
Scan a package from PyPI:
>>> data_egress_scan("requests")
- codeaudit.api_interfaces.filescan(input_path, nosec=False)[source]#
Scan a Python source file, a local directory, or a PyPI package from PyPI.org for security weaknesses and return the results as a JSON-serializable dictionary.
This API function works on:
Local directory: Recursively scans all supported Python files in the directory.
Single Python file: Scans the file if it exists and can be parsed into an AST.
PyPI package on PyPI.org: Downloads the source distribution from PyPI, scans it, and cleans up temporary files.
The returned output always includes Python Code Audit version information and a generation timestamp. For consistency, single-file scans are normalized to match the structure of directory/package scans.
Note: The filescan command does NOT include all directories. This is done on purpose! The following directories are skipped by default:
/docs
/docker
/dist
/tests
all directories that start with . (dot) or _ (underscore)
But you can easily change this if needed!
- Parameters:
input_path (str) – One of the following: - Path to a local directory containing Python code. - Path to a single
.pyfile. - Name of a package available on PyPI.- Returns:
A JSON-serializable dictionary containing scan results and metadata. The structure varies slightly depending on the scan type, but always includes: - Version information from
version(). -generated_ontimestamp (YYYY-MM-DD HH:MM). - Package or file-level security findings.- Return type:
dict
If the input cannot be interpreted as a valid directory, Python file, or PyPI package, a dictionary with an
"Error"key is returned.- Raises:
None explicitly. Any unexpected exceptions are allowed to propagate –
unless handled by downstream callers. –
Example
>>> result = filescan("example_package") >>> result["package_name"]
- codeaudit.api_interfaces.get_construct_counts(input_file)[source]#
Analyze a Python file or package(directory) and count occurrences of code constructs (aka weaknesses).
This function uses filescan API call to retrieve security-related information about the input file. This returns a dict. Then it counts how many times each code construct appears across all scanned files.
- Parameters:
input_file (str) – Path to the file or directory(package) to scan.
- Returns:
- A dictionary mapping each construct name (str) to the total
number of occurrences (int) across all scanned files.
- Return type:
dict
Notes
The filescan function is expected to return a dictionary with a ‘file_security_info’ key, containing per-file information.
Each file’s ‘sast_result’ should be a dictionary mapping construct names to lists of occurrences.
- codeaudit.api_interfaces.get_default_validations()[source]#
Retrieve the default implemented security validations.
This function collects the built-in Static Application Security Testing (SAST) validations applied to standard Python modules. It retrieves the validation definitions, converts them into a serializable format, and enriches the result with generation metadata.
The returned structure is intended to be consumed by reporting, API, or documentation layers.
- Returns:
A dictionary containing generation metadata and a list of security validations.
Example structure:
{ "<metadata_key>": "<metadata_value>", ..., "validations": [ { "<field>": "<value>", ... }, ... ] }
- Return type:
dict
Notes
Requires Python 3.9 or later due to use of the dictionary union operator (
|).The
validationslist is derived from a pandas DataFrame usingto_dict(orient="records").
- codeaudit.api_interfaces.get_module_vulnerability_info(module)[source]#
Retrieves vulnerability information for an external module using the OSV Database.
- Parameters:
module (str) – Name of the module to query.
- Returns:
Generation metadata combined with OSV vulnerability results.
- Return type:
dict
- codeaudit.api_interfaces.get_modules(filename)[source]#
Extract modules used in a Python source file.
Analyzes the specified Python file and returns the modules imported directly within the source code. This approach relies on the actual imports present in the file rather than dependency declarations such as
requirements.txtorpyproject.toml, which may be incomplete or outdated.- Parameters:
filename (str) – Path to the Python file to analyze.
- Returns:
- A dictionary containing discovered modules. Expected keys are:
core_modules(list[str]): Standard library modules.imported_modules(list[str]): Imported modules in the file and third-party modules.
- Return type:
dict
- codeaudit.api_interfaces.get_overview(input_path)[source]#
Retrieves the security relevant statistics of a Python package(directory) or of a single Python
Based on the input path, call the overview function and return the result in a dict
- Parameters:
input_path – Directory path of the package to use
- Returns:
Returns the overview statistics in DICT format
- Return type:
dict
- codeaudit.api_interfaces.get_psl_modules()[source]#
Retrieves a list of collection of Python modules that are part of a Python distribution aka standard installation
- Returns:
Overview of PSL modules in the Python version used.
- Return type:
dict
- codeaudit.api_interfaces.get_weakness_counts(input_file, nosec=False)[source]#
Analyze a Python file or package and count occurrences of code weaknesses.
- codeaudit.api_interfaces.package_imports(scanresult)[source]#
Return the external Python modules imported by a scanned package.
This function extracts the list of imported modules from a SAST scan and filters out modules that belong to the package itself. If a package name is available, the returned module names are further normalized by removing imports that resolve to the package’s own namespace.
- Parameters:
scanresult (dict) – Scan result containing package metadata. The dictionary is expected to contain a
module_overviewmapping with animported_moduleslist. Optionally, it may include apackage_namekey used for additional filtering.- Returns:
A list of external module names imported by the package. Returns
Noneifscanresultis not a dictionary or if the expectedmodule_overvieworimported_modulesentries are missing or have an invalid type.- Return type:
list[str] | None
Example
scanresult = filescan(“packagename”) E.g.:
>> scanresult = filescan(“codeaudit”) # Current version, without SAST details
>> modules_discovered = scanresult[“module_overview”]
>> imported_modules = modules_discovered[“imported_modules”]
>> imported_modules [‘altair’, ‘fire’, ‘pandas’, ‘panel’, ‘pyodide.http’]
- codeaudit.api_interfaces.platform_info()[source]#
Get Python platform information - Python version and Python runtime interpreter used. :param none:
- Returns:
Overview of implemented security SAST validation on Standard Python modules
- Return type:
dict
- codeaudit.api_interfaces.read_input_file(filename, safe_directory='data_folder')[source]#
Securely read a Python CodeAudit JSON file and return its contents as a dictionary.
- Parameters:
filename – Path to the JSON file (str or Path).
safe_directory – Base directory considered “safe” for reading files.
- Returns:
The contents of the JSON file.
- Return type:
dict
- Raises:
FileNotFoundError – If the file does not exist.
PermissionError – If the file is outside the allowed safe directory.
json.JSONDecodeError – If the file is not valid JSON.
- codeaudit.api_interfaces.save_to_json(sast_result, filename='codeaudit_output.json')[source]#
Save a SAST result (dict or serializable object) to a JSON file.
- Parameters:
sast_result (dict or list) – The data to be saved as JSON.
filename (str, optional) – The file path to save the JSON data. Defaults to “codeaudit_output.json”.
- Returns:
The absolute path of the saved file, or None if saving failed.
- Return type:
Path
License GPLv3 or higher.
2025 - 2026 Created by Maikel Mardjan - https://nocomplexity.com/
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Altair Plotting functions for Python Code Audit (aka codeaudit)
- codeaudit.altairplots.ast_nodes_overview(scanresult, width=800, height=400)[source]#
Create a bar chart of top files by AST node count.
Displays the top 30 files ranked by AST nodes, with disambiguated filenames, derived density metric, and tooltips showing file details.
- Parameters:
scanresult (dict) – Scan result containing “file_security_info”.
width (int, optional) – Chart width in pixels. Defaults to 800.
height (int, optional) – Chart height in pixels. Defaults to 400.
- Returns:
Bar chart visualization, or a warning message if no valid data is available.
- Return type:
altair.Chart | str
- codeaudit.altairplots.complexity_heatmap(scanresult)[source]#
Generate an interactive heatmap of file complexity and size.
This function visualizes file-level risk by combining code complexity and lines of code into a single interactive heatmap. Files are ranked and filtered to highlight the most potentially risky candidates based on a derived risk score.
The visualization includes:
A heatmap of file metrics (
"Complexity"and"Lines")A computed
"RiskScore"used for sorting and prioritizationInteractive sliders to control threshold levels for complexity and file size
An optional toggle to display only high-risk files
Tooltip details for deeper inspection
Data is pre-filtered to improve usability and performance:
Top 30 files by complexity
Top 30 files by lines of code
Combined and deduplicated set, sorted by risk score
- Parameters:
scanresult (dict) –
Scan output containing file-level metrics.
Expected structure:
{ "file_security_info": { "<file_id>": { "file_name": str, "Number_Of_Lines": int, "Complexity_Score": int | float, ... }, ... } }
- Returns:
An Altair layered chart (heatmap + text overlay) if input is valid.
A warning message string if
scanresultis invalid or empty.
- Return type:
altair.Chart | str
- Raises:
KeyError – If required keys (for example,
"file_security_info") are missing.ValueError – If input data cannot be converted into a valid DataFrame.
Notes
RiskScoreis computed as:(Complexity / 80) + (Lines / 2000)
This normalization balances the influence of both metrics.
Threshold defaults are set to 70% of the maximum observed values.
The chart is optimized for exploratory analysis rather than exhaustive dataset display.
Example
>>> chart = complexity_heatmap(scanresult) >>> if isinstance(chart, str): ... print(chart) >>> else: ... chart.show()
- codeaudit.altairplots.extract_altair_html(plot_html)[source]#
Clean Altair HTML into a minimal embeddable fragment containing only <div> and <script> elements.
- codeaudit.altairplots.issue_overview(df)[source]#
Create an Altair arc (donut) chart from a DataFrame with ‘call’ and ‘count’ columns, showing counts in the legend.
- codeaudit.altairplots.issue_plot(input_dict)[source]#
Create a radial (polar area) chart using Altair.
- Parameters:
input_dict (dict) – Dictionary where keys are ‘construct’ and values are ‘count’.
- Returns:
Altair chart object.
- Return type:
alt.Chart
- codeaudit.altairplots.lines_of_code_overview(scanresult, width=800, height=400)[source]#
Create a bar chart of top files by lines of code.
Displays the top 30 files ranked by lines of code, with disambiguated filenames and tooltips showing full path and complexity.
- Parameters:
scanresult (dict) – Scan result containing “file_security_info”.
width (int, optional) – Chart width in pixels. Defaults to 800.
height (int, optional) – Chart height in pixels. Defaults to 400.
- Returns:
Bar chart visualization, or a warning message if no valid data is available.
- Return type:
altair.Chart | str
- codeaudit.altairplots.module_count_barchart(scanresult)[source]#
Create a bar chart showing module counts by category.
This function generates an Altair bar chart comparing the number of Python standard library modules and third-party modules found in the provided scan result.
- Parameters:
scanresult (dict) – Scan result data containing a “module_overview” key with “core_modules” and “imported_modules” entries.
- Returns:
An Altair bar chart visualizing module counts. Returns a warning message string if the input is invalid.
- Return type:
altair.Chart | str
- codeaudit.altairplots.module_distribution_view(scanresult)[source]#
Create a donut chart showing module distribution.
- Parameters:
scanresult (dict) – Scan result containing “module_overview” with “core_modules” and “imported_modules”.
- Returns:
Donut chart of module distribution, or a warning message if input is invalid.
- Return type:
altair.Chart | str
- codeaudit.altairplots.multi_bar_chart(df)[source]#
Creates a multi bar chart for all relevant columns
- codeaudit.altairplots.sast_files_overview(scanresult)[source]#
Create a bar chart of security issues per file.
Aggregates SAST findings across files and visualizes the number of security issues per file. Filenames are disambiguated using the parent folder when duplicates exist.
- Parameters:
scanresult (dict) – Scan result containing “file_security_info” with per-file SAST findings and metadata.
- Returns:
Bar chart of files with security issues, or a fallback text chart if no valid data is available.
- Return type:
altair.Chart
- codeaudit.altairplots.weaknesses_overview(scanresult)[source]#
Generate a bar chart of the most common security weaknesses.
Aggregates SAST validation findings across all scanned files and displays the most frequent issues. Designed for quick identification of recurring security patterns.
- Parameters:
scanresult (dict) – Scan output containing “file_security_info” with per-file SAST findings. Each finding should include a “validation” field.
- Returns:
Bar chart of top weaknesses, or a text-based chart if input is invalid or no findings are present.
- Return type:
altair.Chart
Notes
Only the top 50 most frequent weaknesses are shown.
The top 5 are visually highlighted.
Returns a fallback chart instead of raising errors for invalid input.