Local offline backend security, error handling, and code quality auditing tool for Python applications
Project description
backend-audit
An offline-first, zero-network, local static analysis security, error handling, and code quality auditing tool specifically built for Python backend applications. It scans web frameworks (Flask, FastAPI, Django, Sanic, and plain HTTP servers) using abstract syntax trees to flag vulnerabilities, weak practices, and REST standard violations before your code goes to production.
🔒 100% Offline-First & Privacy-Locked
This project is built from the ground up for strict data privacy:
- No Cloud API Calls: All analysis is performed entirely on your local machine. No external requests are made, and no code is ever transmitted to the cloud.
- Pure AST/CST Engine: Standard Python
asthandles structured syntax trees, andlibcstperforms local comment parsing to verify muted findings.
🏗 System Architecture
The following diagram outlines the internal pipeline of backend-audit when executing a codebase scan:
graph TD
A[CLI Execution: scan path] --> B[File Discovery: pathlib + exclusions]
B --> C[Framework Detector: flask, fastapi, django, sanic]
C --> D[Source Code Reader: UTF-8 safe]
subgraph "Local Static Analysis Engine"
D --> E[CST Parser: libcst]
E --> F[Extract Ignore Line Ranges: # nosec, # backend-audit:ignore]
D --> G[AST Compiler: built-in ast]
G --> H[AST Node Traverser]
H --> I[Error Handling Rule]
H --> J[Security Scanner Rule]
H --> K[REST Validation Rule]
end
I --> L[Mute Filters: Apply Ignored Lines]
J --> L
K --> L
L --> M[Findings Synthesizer]
M --> N[Report Compiler: AuditReport]
subgraph "Output Formatting"
N --> O[JSON Output: stdout / --output file.json]
N --> P[Rich Console Panels: Severity cards + Highlighted code]
end
Analysis Pipelines
- File discovery: Recursively searches the target path for
.pyfiles. Automatically ignores virtual environments (venv,.venv), configurations, tests, migrations, and build files. - Framework auto-detection: Looks at imports and file structures to detect the framework (FastAPI, Flask, Django, etc.) and adjusts testing rules accordingly.
- CST scanning: Parses the concrete syntax tree via
libcstto record lines marked with# backend-audit:ignoreor# nosecfor rule muting. - AST scanning: Walks the syntax tree structure to locate vulnerabilities, bad practices, and invalid status codes.
- Mute filters: Excludes findings matching ignored lines before report generation.
- Report compile: Formats the final
AuditReportto be presented in standard terminal layout panels or exported as standard JSON.
🚀 Key Features & Rules
1. Automatic Error Handling Detection
- Gaps in Route Handlers: Flags endpoints that lack standard
try/exceptwraps (missing-try-except). - Swallowed Exception Hazards: Detects
exceptblocks that catch exceptions and only log them usingprint()or logging objects without raising or returning a proper response (error-only-logged). - Global Configuration Issues: Highlights projects missing global exception handlers and
404 - Not Foundroute registrations in main server files (missing-global-error-handler,missing-404-handler).
2. Backend Security Scanner
- Hardcoded Credentials: Uses standard naming patterns and dynamic Shannon Entropy analysis to detect credentials, API keys, passwords, and tokens embedded in string literals (
hardcoded-secret). - Route Protection Gap: Flags sensitive endpoints (e.g. paths starting with
/adminor/api/private) that lack authentication wrappers or DRF / FastAPI security dependency parameters (unprotected-route). - Command Injection: Locates dangerous calls to
os.system()orsubprocessusingshell=Truewith dynamically formatted parameters (command-injection). - SQL Injection: Checks database raw execute methods that build query parameters via f-strings or manual string formats instead of parameterized query arguments (
sql-injection). - Weak JWTs: Flags signing calls using key literal values,
algorithm="none", or payloads missingexp(expiration) parameters (weak-jwt-secret,weak-jwt-algorithm,weak-jwt-missing-exp). - Dangerous Calls: Detects dynamic python evaluations using
eval()orexec()(dangerous-pattern).
3. HTTP Status Code & REST Validation
- 200 OK Error Responses: Detects return statements inside error handlers or conditional fail blocks returning standard
200 - OKresponses (error-response-status-200). - Semantic Code Gaps: Asserts that validation failures return
400 - Bad Request, authentication failures return401 - Unauthorizedor403 - Forbidden, and lookup failures return404 - Not Found. - Standard Descriptions: Automatically appends standard descriptions (e.g.
"404 - Not Found") to all HTTP status code warnings.
📦 Installation
From Source (Local Development)
Clone this repository and install in editable mode:
git clone https://github.com/KhairnarLokesh/backendaudit-python-library.git
cd backendaudit-python-library
pip install -e .
Directly From GitHub (Production / CLI Utility)
You can install this command line scanner directly from the remote repository:
pip install git+https://github.com/KhairnarLokesh/backendaudit-python-library.git
💻 CLI Usage
Once installed, use the backend-audit command:
1. Basic Directory Scan (Auto-detects Framework)
backend-audit scan .
2. Scan Specific File or Subdirectory
backend-audit scan src/controllers/
3. Specify Framework Override
backend-audit scan . --framework fastapi
4. Output as JSON and Save to File
backend-audit scan . --format json --output report.json
🤫 Muting Warnings
To suppress a false positive or ignore an intentional coding practice, add an inline # backend-audit:ignore or # nosec comment to that line:
# This hardcoded signature key will be ignored during scans
TEST_SECRET_KEY = "dummy-testing-signature-token-987" # backend-audit:ignore
try:
process_data()
except Exception as e:
# This caught error print swallow will be ignored
print("Logged only:", e) # nosec
🧪 Running Tests
Ensure all tests pass before making modifications:
# Add PYTHONPATH to let pytest discover the source package
$env:PYTHONPATH="src"
python -m pytest tests/
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file backendaudit_python_library-1.0.0.tar.gz.
File metadata
- Download URL: backendaudit_python_library-1.0.0.tar.gz
- Upload date:
- Size: 23.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dbbb8a6e3a7976ac580578b5551c4beaf5bbe738b051831fcaa9bd43fe885178
|
|
| MD5 |
df4a7131a48cbaf636fcf590ab4af244
|
|
| BLAKE2b-256 |
3e5e7b5b38d85feb03879990d41be8a54df0e14bc12c64207f5fdd879755dd69
|
File details
Details for the file backendaudit_python_library-1.0.0-py3-none-any.whl.
File metadata
- Download URL: backendaudit_python_library-1.0.0-py3-none-any.whl
- Upload date:
- Size: 23.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5db57fce6648157ed8bad71ab9d03603a18a1f5ce18d381a7c5673a9d61b18ef
|
|
| MD5 |
a05160eec0b6ef39d7dba997ae2bc9e0
|
|
| BLAKE2b-256 |
5d0cfc2edb92d552d4462e9ddf420d27d68deabde0150e829eb6c5906e4a13e9
|