backend-guard 1.0.0__tar.gz

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.
Files changed (68) hide show
  1. backend_guard-1.0.0/LICENSE +21 -0
  2. backend_guard-1.0.0/PKG-INFO +533 -0
  3. backend_guard-1.0.0/README.md +502 -0
  4. backend_guard-1.0.0/auditor/__init__.py +10 -0
  5. backend_guard-1.0.0/auditor/analyzers/__init__.py +27 -0
  6. backend_guard-1.0.0/auditor/analyzers/frameworks/express/__init__.py +145 -0
  7. backend_guard-1.0.0/auditor/analyzers/frameworks/fastapi/__init__.py +160 -0
  8. backend_guard-1.0.0/auditor/analyzers/frameworks/nestjs/__init__.py +127 -0
  9. backend_guard-1.0.0/auditor/analyzers/languages/javascript/imports.py +45 -0
  10. backend_guard-1.0.0/auditor/analyzers/languages/javascript/parser.py +113 -0
  11. backend_guard-1.0.0/auditor/analyzers/languages/javascript/rules.py +161 -0
  12. backend_guard-1.0.0/auditor/analyzers/languages/python/async_checks.py +82 -0
  13. backend_guard-1.0.0/auditor/analyzers/languages/python/imports.py +55 -0
  14. backend_guard-1.0.0/auditor/analyzers/languages/python/parser.py +45 -0
  15. backend_guard-1.0.0/auditor/analyzers/languages/python/rules.py +197 -0
  16. backend_guard-1.0.0/auditor/analyzers/languages/python/typing.py +78 -0
  17. backend_guard-1.0.0/auditor/analyzers/languages/typescript/imports.py +7 -0
  18. backend_guard-1.0.0/auditor/analyzers/languages/typescript/parser.py +8 -0
  19. backend_guard-1.0.0/auditor/analyzers/languages/typescript/rules.py +75 -0
  20. backend_guard-1.0.0/auditor/analyzers/universal/api_design.py +154 -0
  21. backend_guard-1.0.0/auditor/analyzers/universal/architecture.py +106 -0
  22. backend_guard-1.0.0/auditor/analyzers/universal/complexity.py +190 -0
  23. backend_guard-1.0.0/auditor/analyzers/universal/configuration.py +95 -0
  24. backend_guard-1.0.0/auditor/analyzers/universal/database_design.py +179 -0
  25. backend_guard-1.0.0/auditor/analyzers/universal/dependency.py +94 -0
  26. backend_guard-1.0.0/auditor/analyzers/universal/duplication.py +104 -0
  27. backend_guard-1.0.0/auditor/analyzers/universal/error_handling.py +194 -0
  28. backend_guard-1.0.0/auditor/analyzers/universal/logging.py +156 -0
  29. backend_guard-1.0.0/auditor/analyzers/universal/production_readiness.py +93 -0
  30. backend_guard-1.0.0/auditor/analyzers/universal/security.py +405 -0
  31. backend_guard-1.0.0/auditor/analyzers/universal/solid.py +124 -0
  32. backend_guard-1.0.0/auditor/analyzers/universal/testing.py +136 -0
  33. backend_guard-1.0.0/auditor/baselines.py +55 -0
  34. backend_guard-1.0.0/auditor/cli.py +342 -0
  35. backend_guard-1.0.0/auditor/config.py +186 -0
  36. backend_guard-1.0.0/auditor/core/__init__.py +19 -0
  37. backend_guard-1.0.0/auditor/core/analyzer.py +40 -0
  38. backend_guard-1.0.0/auditor/core/context.py +89 -0
  39. backend_guard-1.0.0/auditor/core/dependency_graph.py +188 -0
  40. backend_guard-1.0.0/auditor/core/findings.py +76 -0
  41. backend_guard-1.0.0/auditor/core/rule.py +134 -0
  42. backend_guard-1.0.0/auditor/core/severity.py +111 -0
  43. backend_guard-1.0.0/auditor/discovery.py +433 -0
  44. backend_guard-1.0.0/auditor/engine.py +146 -0
  45. backend_guard-1.0.0/auditor/integrations/bandit.py +58 -0
  46. backend_guard-1.0.0/auditor/integrations/eslint.py +56 -0
  47. backend_guard-1.0.0/auditor/integrations/external_tools.py +43 -0
  48. backend_guard-1.0.0/auditor/integrations/mypy.py +54 -0
  49. backend_guard-1.0.0/auditor/integrations/pytest.py +43 -0
  50. backend_guard-1.0.0/auditor/integrations/ruff.py +62 -0
  51. backend_guard-1.0.0/auditor/integrations_external/github_actions.py +22 -0
  52. backend_guard-1.0.0/auditor/integrations_external/mcp_server.py +121 -0
  53. backend_guard-1.0.0/auditor/models.py +222 -0
  54. backend_guard-1.0.0/auditor/project.py +37 -0
  55. backend_guard-1.0.0/auditor/registry.py +101 -0
  56. backend_guard-1.0.0/auditor/reporting/json_report.py +15 -0
  57. backend_guard-1.0.0/auditor/reporting/markdown_report.py +123 -0
  58. backend_guard-1.0.0/auditor/reporting/sarif_report.py +87 -0
  59. backend_guard-1.0.0/auditor/reporting/terminal.py +133 -0
  60. backend_guard-1.0.0/auditor/suppressions.py +112 -0
  61. backend_guard-1.0.0/backend_guard.egg-info/PKG-INFO +533 -0
  62. backend_guard-1.0.0/backend_guard.egg-info/SOURCES.txt +66 -0
  63. backend_guard-1.0.0/backend_guard.egg-info/dependency_links.txt +1 -0
  64. backend_guard-1.0.0/backend_guard.egg-info/entry_points.txt +3 -0
  65. backend_guard-1.0.0/backend_guard.egg-info/requires.txt +8 -0
  66. backend_guard-1.0.0/backend_guard.egg-info/top_level.txt +1 -0
  67. backend_guard-1.0.0/pyproject.toml +81 -0
  68. backend_guard-1.0.0/setup.cfg +4 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Backend Guard Maintainers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,533 @@
1
+ Metadata-Version: 2.4
2
+ Name: backend-guard
3
+ Version: 1.0.0
4
+ Summary: Universal Backend Codebase Auditor (Backend Guard) - Static architecture, security, and quality analysis.
5
+ Author-email: Backend Guard Core Maintainers <maintainers@backendguard.org>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/creativeprem789/Backend_Guard
8
+ Project-URL: Repository, https://github.com/creativeprem789/Backend_Guard.git
9
+ Project-URL: Documentation, https://github.com/creativeprem789/Backend_Guard#readme
10
+ Project-URL: Bug Tracker, https://github.com/creativeprem789/Backend_Guard/issues
11
+ Keywords: backend,static-analysis,architecture,linter,security,fastapi,express,nestjs,django
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Software Development :: Quality Assurance
21
+ Classifier: Topic :: Security
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: tomli>=1.1.0; python_version < "3.11"
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
28
+ Requires-Dist: ruff>=0.4.0; extra == "dev"
29
+ Requires-Dist: mypy>=1.10.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # 🛡️ Backend Guard
33
+
34
+ <div align="center">
35
+
36
+ **Universal Backend Codebase Auditor & Architecture Linter**
37
+
38
+ *Inspect backend architecture, catch silent production defects, enforce separation of concerns, and secure APIs across multiple languages and frameworks.*
39
+
40
+ [![Backend Guard CI](https://github.com/creativeprem789/Backend_Guard/actions/workflows/tests.yml/badge.svg)](https://github.com/creativeprem789/Backend_Guard/actions)
41
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
42
+ [![Python: 3.9+](https://img.shields.io/badge/Python-3.9%2B-3776AB.svg?logo=python&logoColor=white)](https://python.org)
43
+ [![Node.js: 18+](https://img.shields.io/badge/Node.js-18%2B-339933.svg?logo=nodedotjs&logoColor=white)](https://nodejs.org)
44
+ [![Code Style: Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
45
+ [![Type Checked: mypy](https://img.shields.io/badge/types-mypy-blue.svg)](http://mypy-lang.org/)
46
+
47
+ [Features](#-features) •
48
+ [Why Backend Guard?](#-why-backend-guard) •
49
+ [Installation](#-installation) •
50
+ [Quick Start](#-quick-start) •
51
+ [Auditing Your Backend](#-auditing-your-backend) •
52
+ [Rule Reference](#-rule-catalog) •
53
+ [AI & MCP Server](#-ai-coding-assistant-integration-mcp) •
54
+ [Configuration](#-configuration) •
55
+ [Documentation](#-documentation)
56
+
57
+ </div>
58
+
59
+ ---
60
+
61
+ ## 💡 What is Backend Guard?
62
+
63
+ **Backend Guard** is an extensible, open-source static analysis engine designed **exclusively for backend systems**.
64
+
65
+ While traditional linters check formatting and general style, Backend Guard evaluates **backend architecture, system reliability, data flow, concurrency safety, and production readiness**.
66
+
67
+ It answers questions linters ignore:
68
+ - ❌ Are HTTP route handlers directly executing database queries instead of delegating to a service/repository?
69
+ - ❌ Is a synchronous blocking call like `time.sleep()` or `fs.readFileSync` freezing the async event loop under high load?
70
+ - ❌ Are database queries executing inside a loop iteration creating severe **N+1 query** performance bottlenecks?
71
+ - ❌ Is an unhandled promise rejection in an Express route silently hanging client connections indefinitely?
72
+ - ❌ Are database transactions committing without explicit rollback handlers in exception paths?
73
+ - ❌ Is your backend missing health probes (`/health`), request timeouts, or pagination on collection endpoints?
74
+
75
+ ---
76
+
77
+ ## 🥊 Why Backend Guard?
78
+
79
+ | Feature | Standard Linters (Ruff, ESLint) | Security Scanners (Bandit, Snyk) | 🛡️ **Backend Guard** |
80
+ |---|:---:|:---:|:---:|
81
+ | Syntax & Formatting | ✅ | ❌ | ✅ |
82
+ | Known Vulnerability Scanning | ❌ | ✅ | ✅ |
83
+ | **Layer Boundary & Coupling (Presentation ➔ Infra)** | ❌ | ❌ | ✅ |
84
+ | **Async Event Loop Blocking Detections** | ❌ | ❌ | ✅ |
85
+ | **Database Transaction & N+1 Query Risks** | ❌ | ❌ | ✅ |
86
+ | **Framework Lifecycle Hygiene (FastAPI, Express, NestJS)** | ❌ | ❌ | ✅ |
87
+ | **API Pagination & HTTP Status Semantics** | ❌ | ❌ | ✅ |
88
+ | **Production Readiness (Health Probes, Graceful Shutdown)** | ❌ | ❌ | ✅ |
89
+ | **AI Coding Assistant Protocol (MCP Server Native)** | ❌ | ❌ | ✅ |
90
+ | **Strictly Read-Only Guarantee** | Varies | ✅ | ✅ |
91
+
92
+ ---
93
+
94
+ ## 🏗️ Architecture
95
+
96
+ Backend Guard employs a **language-independent core engine** coupled with specialized AST and framework analyzers:
97
+
98
+ ```text
99
+ TARGET BACKEND CODEBASE
100
+ │
101
+ ▼
102
+ PROJECT DISCOVERY
103
+ (File tree, .gitignore, exclusions)
104
+ │
105
+ ▼
106
+ TECHNOLOGY DETECTION
107
+ (Python, JS, TS, FastAPI, Express, NestJS)
108
+ │
109
+ ▼
110
+ UNIVERSAL CORE ENGINE
111
+ ┌───────────────────────┼───────────────────────┐
112
+ ▼ ▼ ▼
113
+ UNIVERSAL ANALYZERS LANGUAGE ANALYZERS FRAMEWORK ANALYZERS
114
+ • Architecture • Python (AST, async) • FastAPI
115
+ • SOLID Principles • JavaScript (Node) • Express.js
116
+ • Security & Secrets • TypeScript (strict) • NestJS
117
+ • Database & N+1 • Django / Flask
118
+ • Error Handling
119
+ • Production Readiness
120
+ │ │ │
121
+ └───────────────────────┼───────────────────────┘
122
+ │
123
+ ▼
124
+ UNIFIED FINDINGS
125
+ (Fingerprinted, Suppressed, Baselines)
126
+ │
127
+ ┌───────────────────────┼───────────────────────┐
128
+ ▼ ▼ ▼
129
+ TERMINAL REPORT JSON / SARIF MARKDOWN
130
+ (ANSI cards & fixes) (GitHub CodeScan) (PR Documentation)
131
+ │
132
+ ▼
133
+ AI CODING ASSISTANTS & CI/CD PIPELINES
134
+ (Model Context Protocol - MCP)
135
+ ```
136
+
137
+ ---
138
+
139
+ ## 🚀 Supported Tech Stack
140
+
141
+ | Ecosystem | Status | Analyzed Frameworks | Key Checks |
142
+ |---|:---:|---|---|
143
+ | **Python** | ✅ Supported | **FastAPI**, **Django**, **Flask** | Blocking I/O in async def, mutable defaults, unsafe deserialization, DI validation, raw SQL in routes |
144
+ | **JavaScript** | ✅ Supported | **Express**, **NestJS** | Sync I/O on servers, unhandled promises, eval safety, missing 4-arg error middleware |
145
+ | **TypeScript** | ✅ Supported | **Express**, **NestJS** | Unsafe `any` type propagation, `@Injectable()` decoration, controller DB isolation |
146
+ | Java | 📋 Planned v1.1 | Spring Boot | Dependency injection lifecycle, JPA N+1 query patterns, transaction boundaries |
147
+ | Go | 📋 Planned v1.1 | Gin, Echo, Fiber | Goroutine leaks, unbuffered channel deadlocks, handler error propagation |
148
+ | PHP | 📋 Planned v1.2 | Laravel, Symfony | Eloquent eager-loading, container isolation, mass-assignment vulnerabilities |
149
+ | C# | 📋 Planned v1.2 | ASP.NET Core | Middleware ordering, Entity Framework DbContext concurrency |
150
+ | Rust | 📋 Planned v1.3 | Actix Web, Axum | Handler panic safety (`unwrap()`), async runtime blocking |
151
+
152
+ ---
153
+
154
+ ## 📦 Installation
155
+
156
+ ### Option 1: Install from PyPI (Recommended)
157
+ ```bash
158
+ pip install backend-guard
159
+ ```
160
+
161
+ ### Option 2: Install from GitHub (Development)
162
+ ```bash
163
+ git clone https://github.com/creativeprem789/Backend_Guard.git
164
+ cd Backend_Guard/backend-auditor
165
+ pip install -e .
166
+ ```
167
+
168
+ ### Option 2: Install via pip (once published on PyPI)
169
+ ```bash
170
+ pip install backend-auditor
171
+ ```
172
+
173
+ After installation, both `backend-guard` and `backend-auditor` CLI commands are available globally.
174
+
175
+ ```bash
176
+ backend-guard --version
177
+ # Output: backend-guard 1.0.0
178
+ ```
179
+
180
+ ---
181
+
182
+ ## ⚡ Quick Start
183
+
184
+ ```bash
185
+ # 1. Audit your current backend directory
186
+ backend-guard audit .
187
+
188
+ # 2. Detect the technologies and frameworks in a project
189
+ backend-guard detect /path/to/backend
190
+
191
+ # 3. View all 42 supported backend audit rules
192
+ backend-guard rules
193
+
194
+ # 4. Generate a GitHub Flavored Markdown report for a Pull Request
195
+ backend-guard audit . --format markdown --output AUDIT.md
196
+
197
+ # 5. Output SARIF format for GitHub Code Scanning
198
+ backend-guard audit . --format sarif --output results.sarif
199
+ ```
200
+
201
+ ---
202
+
203
+ ## 🔍 Auditing Your Backend
204
+
205
+ To audit any existing backend codebase, simply point `backend-guard` to your project folder:
206
+
207
+ ```bash
208
+ backend-guard audit /path/to/my-project
209
+ ```
210
+
211
+ ### Sample Terminal Output
212
+
213
+ ```text
214
+ ============================================================================
215
+ 🛡️ BACKEND GUARD AUDIT REPORT - my-backend-service
216
+ ============================================================================
217
+ Root: C:/Projects/my-backend-service
218
+ Languages: Python (high)
219
+ Frameworks: FastAPI (high)
220
+ Scanned: 34 files (5,420 lines of code) in 0.28s
221
+ ----------------------------------------------------------------------------
222
+
223
+ FINDINGS SUMMARY:
224
+ Critical: 1 | High: 3 | Medium: 2 | Low: 1 | Info: 0
225
+
226
+ ----------------------------------------------------------------------------
227
+ DETAILED FINDINGS
228
+ ----------------------------------------------------------------------------
229
+
230
+ 1. [CRITICAL] SEC-002: SQL injection risk from string formatting (high conf)
231
+ Location: app/routers/orders.py:42
232
+ Problem: Database query constructed using Python f-string interpolation.
233
+ Evidence: db.execute(f"SELECT * FROM orders WHERE id = '{order_id}'")
234
+ Impact: Attackers can bypass authorization or extract arbitrary database records.
235
+ Fix: Use parameterized queries with bind variables.
236
+ Example: cursor.execute("SELECT * FROM orders WHERE id = %s", (order_id,))
237
+
238
+ 2. [HIGH] PY-ASYNC-001: Synchronous blocking call in async function (high conf)
239
+ Location: app/services/notifier.py:18
240
+ Problem: Blocking call 'time.sleep()' invoked inside async function 'send_webhook'. Use asyncio.sleep() instead.
241
+ Evidence: time.sleep(2)
242
+ Impact: Completely freezes the single-threaded asyncio event loop, halting all concurrent requests.
243
+ Fix: Replace with await asyncio.sleep(2).
244
+
245
+ 3. [HIGH] DB-001: Potential N+1 query pattern detected in loop (medium conf)
246
+ Location: app/services/users.py:87
247
+ Problem: Database query 'db.get()' executed inside loop iteration.
248
+ Evidence: Loop query at line 87
249
+ Impact: Multiplies database round-trips; an endpoint returning 100 items executes 101 queries.
250
+ Fix: Batch query IDs using .filter(Model.id.in_(ids)) outside the loop or use eager loading.
251
+
252
+ ============================================================================
253
+ ```
254
+
255
+ ### Filtering Findings
256
+ ```bash
257
+ # Only fail CI on critical and high severity findings
258
+ backend-guard audit . --fail-on high
259
+
260
+ # Only audit security-related rules
261
+ backend-guard audit . --category security
262
+
263
+ # Exclude generated code and migrations
264
+ backend-guard audit . --exclude migrations,generated,venv
265
+ ```
266
+
267
+ ---
268
+
269
+ ## 🤖 AI Coding Assistant Integration (MCP)
270
+
271
+ Backend Guard includes a native **Model Context Protocol (MCP)** server over `stdio`. AI coding tools like **Cursor**, **Claude Desktop**, and **Antigravity** can inspect your backend, execute audits, and fetch fix suggestions dynamically.
272
+
273
+ ### Start the MCP Server
274
+ ```bash
275
+ backend-guard mcp
276
+ ```
277
+
278
+ ### Configure in Claude Desktop (`claude_desktop_config.json`) or Cursor
279
+ ```json
280
+ {
281
+ "mcpServers": {
282
+ "backend-guard": {
283
+ "command": "backend-guard",
284
+ "args": ["mcp"]
285
+ }
286
+ }
287
+ }
288
+ ```
289
+
290
+ ### Supported MCP Operations
291
+ - `detect_backend_stack`: Inspects target codebase and returns detected frameworks, manifests, and file counts.
292
+ - `audit_backend`: Runs the full audit engine and returns structured JSON findings.
293
+ - `get_finding_details`: Fetches full impact, evidence, and remediation guidance for a specific finding.
294
+ - `get_rule_information`: Returns rule documentation and architecture rationale.
295
+ - `generate_fix_suggestion`: Returns concrete refactoring code snippets.
296
+
297
+ ---
298
+
299
+ ## 🚫 False-Positive Controls & Suppressions
300
+
301
+ Backend Guard is engineered to be developer-friendly. You can suppress individual findings directly in code:
302
+
303
+ ### Python
304
+ ```python
305
+ # Inline suppression
306
+ DUMMY_KEY = "test_key_1234567890" # backend-auditor: ignore SEC-001 -- mock test key
307
+
308
+ # Block suppression
309
+ # backend-auditor: ignore-block ARCH-001
310
+ from app.infra import raw_db
311
+ raw_db.ping()
312
+ # backend-auditor: end-ignore-block
313
+
314
+ # File-level suppression
315
+ # backend-auditor: ignore-file
316
+ ```
317
+
318
+ ### JavaScript / TypeScript
319
+ ```javascript
320
+ // Inline suppression
321
+ const data = fs.readFileSync('conf.json'); // backend-guard: ignore JS-001 -- startup only
322
+
323
+ // Block suppression
324
+ /* backend-guard: ignore-block JS-003 */
325
+ const res = eval(expr);
326
+ /* backend-guard: end-ignore-block */
327
+ ```
328
+
329
+ ### Baseline Snapshots for Legacy Codebases
330
+ Adopt Backend Guard on large existing codebases without breaking your build:
331
+ ```bash
332
+ # 1. Snapshot all existing legacy findings
333
+ backend-guard baseline generate . -o baseline.json
334
+
335
+ # 2. Audit against baseline (only NEW defects fail the build)
336
+ backend-guard audit . --baseline baseline.json
337
+ ```
338
+
339
+ ---
340
+
341
+ ## ⚙️ Configuration (`backend-auditor.toml`)
342
+
343
+ Initialize a configuration file:
344
+ ```bash
345
+ backend-guard init .
346
+ ```
347
+
348
+ `backend-auditor.toml`:
349
+ ```toml
350
+ [general]
351
+ failure_threshold = "high" # Exit code 1 if findings >= threshold (critical, high, medium, low)
352
+ confidence_threshold = "low" # Minimum confidence level to report
353
+ # baseline = "baseline.json"
354
+
355
+ [rules]
356
+ # enable = ["ARCH-001", "SEC-001"] # Whitelist specific rules
357
+ disable = ["LOG-002"] # Ignore specific rules
358
+
359
+ [rules.severity]
360
+ # Override default severities
361
+ "API-001" = "low"
362
+
363
+ [exclusions]
364
+ dirs = [
365
+ "node_modules",
366
+ ".git",
367
+ "venv",
368
+ ".venv",
369
+ "migrations"
370
+ ]
371
+ files = []
372
+ respect_gitignore = true
373
+
374
+ [complexity]
375
+ max_cyclomatic_complexity = 15
376
+ max_function_lines = 60
377
+ max_file_lines = 600
378
+
379
+ [tools]
380
+ # External tools executed when running with --with-tools
381
+ ruff = true
382
+ eslint = true
383
+ mypy = true
384
+ bandit = true
385
+ pytest = true
386
+ ```
387
+
388
+ ---
389
+
390
+ ## 📋 Rule Catalog
391
+
392
+ <details>
393
+ <summary><b>Click to expand the 42 implemented backend rules</b></summary>
394
+
395
+ ### 1. Architecture (`architecture`)
396
+ - `ARCH-001` [HIGH]: Direct presentation to infrastructure coupling (route directly calling database).
397
+ - `ARCH-003` [HIGH]: Circular module dependency cycle detected.
398
+ - `DUP-001` [LOW]: Substantial code duplication across handlers/services.
399
+ - `FASTAPI-001` [HIGH]: Direct raw SQL execution inside route endpoint.
400
+ - `NEST-002` [HIGH]: Direct database access inside NestJS controller.
401
+
402
+ ### 2. SOLID Principles (`solid`)
403
+ - `SOLID-001` [MEDIUM]: Single Responsibility Principle: God class detected (> 15 methods, > 250 lines).
404
+ - `SOLID-002` [LOW]: Open/Closed Principle: Excessive type-checking cascades (`isinstance` ladders).
405
+
406
+ ### 3. Security (`security`)
407
+ - `SEC-001` [CRITICAL]: Hardcoded secret or API credential detected.
408
+ - `SEC-002` [CRITICAL]: SQL injection risk from string formatting/concatenation.
409
+ - `SEC-003` [HIGH]: Dangerous system command execution (`os.system`, `child_process.exec`).
410
+ - `SEC-004` [HIGH]: Insecure CORS wildcard origin with credentials enabled.
411
+ - `SEC-005` [HIGH]: Path traversal vulnerability risk in file operations.
412
+ - `PY-002` [CRITICAL]: Unsafe deserialization via `pickle` or `yaml.load` without SafeLoader.
413
+ - `JS-003` [CRITICAL]: Dangerous dynamic code evaluation (`eval()` or `new Function()`).
414
+
415
+ ### 4. Async & Concurrency (`async_concurrency`)
416
+ - `PY-ASYNC-001` [HIGH]: Synchronous blocking call inside `async def` function.
417
+ - `JS-001` [HIGH]: Synchronous blocking I/O call in Node.js server (`fs.readFileSync`).
418
+
419
+ ### 5. Database Engineering (`database`)
420
+ - `DB-001` [HIGH]: Potential N+1 query pattern detected in loop.
421
+ - `DB-002` [HIGH]: Database transaction commit without explicit rollback handler.
422
+
423
+ ### 6. Error Handling (`error_handling`)
424
+ - `ERR-001` [HIGH]: Silent exception swallowing (`except: pass` or empty catch).
425
+ - `ERR-002` [MEDIUM]: Overly broad exception catching without re-raise (`except:` or `BaseException`).
426
+ - `ERR-003` [HIGH]: Internal stack trace or raw error leaked to client.
427
+ - `JS-002` [HIGH]: Unhandled promise rejection risk (`.then()` without `.catch()`).
428
+ - `EXPRESS-001` [HIGH]: Missing global 4-argument error handling middleware in Express.
429
+ - `EXPRESS-003` [HIGH]: Async Express route handler without error handling.
430
+
431
+ ### 7. Complexity (`complexity`)
432
+ - `CMPLX-001` [MEDIUM]: Excessive cyclomatic complexity in function (> 15).
433
+ - `CMPLX-002` [LOW]: Function exceeds maximum line threshold (> 60 lines).
434
+ - `CMPLX-003` [MEDIUM]: Deeply nested control structures (Arrow antipattern > 4 levels).
435
+
436
+ ### 8. API Design (`api_design`)
437
+ - `API-001` [MEDIUM]: Missing pagination on collection endpoint.
438
+ - `API-002` [LOW]: HTTP 200 OK returned with error payload.
439
+ - `FASTAPI-002` [LOW]: Missing `response_model` on mutating route endpoint.
440
+
441
+ ### 9. Dependency Management (`dependency`)
442
+ - `DEP-002` [MEDIUM]: Unpinned dependency version in production manifest (`requirements.txt` / `package.json`).
443
+
444
+ ### 10. Logging (`production_readiness`)
445
+ - `LOG-001` [HIGH]: Sensitive credential or auth token logged.
446
+ - `LOG-002` [LOW]: Raw stdout printing (`print()` / `console.log()`) instead of structured logger.
447
+
448
+ ### 11. Production Readiness (`production_readiness`)
449
+ - `CONF-002` [HIGH]: Production debug mode hardcoded to True.
450
+ - `PROD-001` [LOW]: Missing health check or liveness endpoint (`/health`, `/healthz`).
451
+
452
+ ### 12. Testing (`testing`)
453
+ - `TEST-001` [HIGH]: Missing automated test suite in non-trivial project.
454
+ - `TEST-002` [MEDIUM]: Vacuous test case containing no assertions.
455
+
456
+ ### 13. Language & Framework Patterns (`patterns`, `typing`)
457
+ - `PY-001` [HIGH]: Dangerous mutable default argument (`def f(items=[])`).
458
+ - `PY-003` [LOW]: Wildcard import polluting namespace (`from module import *`).
459
+ - `PY-TYPE-001` [LOW]: Missing type annotations on public function.
460
+ - `TS-001` [LOW]: Excessive use of unsafe `any` type in TypeScript.
461
+ - `NEST-001` [HIGH]: Service class missing `@Injectable()` decorator.
462
+
463
+ </details>
464
+
465
+ ---
466
+
467
+ ## 🚦 Exit Codes
468
+
469
+ | Code | Meaning |
470
+ |:---:|---|
471
+ | `0` | Audit completed successfully; no blocking threshold exceeded. |
472
+ | `1` | Blocking findings detected (findings at or above configured `failure_threshold`). |
473
+ | `2` | Invalid usage or configuration error. |
474
+ | `3` | Audit incomplete because a required analysis stage failed. |
475
+
476
+ ---
477
+
478
+ ## 🔄 GitHub Actions CI Integration
479
+
480
+ Add `.github/workflows/audit.yml` to your repository:
481
+
482
+ ```yaml
483
+ name: Backend Architecture Audit
484
+
485
+ on: [push, pull_request]
486
+
487
+ jobs:
488
+ audit:
489
+ runs-on: ubuntu-latest
490
+ steps:
491
+ - uses: actions/checkout@v4
492
+
493
+ - name: Set up Python
494
+ uses: actions/setup-python@v5
495
+ with:
496
+ python-version: '3.11'
497
+
498
+ - name: Install Backend Guard
499
+ run: |
500
+ pip install git+https://github.com/creativeprem789/Backend_Guard.git#subdirectory=backend-auditor
501
+
502
+ - name: Run Backend Guard Audit
503
+ run: |
504
+ backend-guard audit . --fail-on high --format github
505
+ ```
506
+
507
+ ---
508
+
509
+ ## 📚 Documentation
510
+
511
+ For deeper details, consult the documentation in [`docs/`](docs/):
512
+ - [Architecture & Design Details](docs/architecture.md)
513
+ - [Rules Reference](docs/rules_reference.md)
514
+ - [Supported Languages & Frameworks](docs/supported_languages.md)
515
+ - [Configuration Reference](docs/configuration.md)
516
+ - [Integrations (MCP, CI/CD, External Tools)](docs/integrations.md)
517
+ - [False-Positive Management](docs/false_positives.md)
518
+ - [Contributing Guide](CONTRIBUTING.md)
519
+
520
+ ---
521
+
522
+ ## 🤝 Contributing
523
+
524
+ Contributions are welcomed! Check out [CONTRIBUTING.md](CONTRIBUTING.md) to learn how to:
525
+ 1. Add new language analyzers (Go, Java, Rust).
526
+ 2. Add framework-specific rules (Spring Boot, Laravel, Gin).
527
+ 3. Run the automated test suite (`pytest`) and linters (`ruff`, `mypy`).
528
+
529
+ ---
530
+
531
+ ## 📄 License
532
+
533
+ Backend Guard is open-source software licensed under the [MIT License](LICENSE).