# Vulnerability Remediation Report **Date Remediated:** 2026-02-05 --- ## Reports Analyzed | Report | Date | Total Issues | Breakdown | |--------|------|--------------|-----------| | NeuroSploit Security Report_0_1.html | 2026-01-28 | 58 | 41 High, 14 Medium, 3 Low | --- ## Combined Summary | Category | Count | Status | |----------|-------|--------| | **Fixed** | 18 | Resolved with code changes | | **False Positives** | 55 | Scanner misidentified or not applicable | | **Skipped (By Design)** | 12 | Intentional behavior, no fix needed | | **Out of Scope** | 13 | Test files, utilities, or external dependencies | | **Already Remediated** | 32 | Second/third scan flagged issues already fixed | --- ## Fixed Vulnerabilities | # | Severity | CWE | Issue | File | Lines | How Fixed | |---|----------|-----|-------|------|-------|-----------| | 1 | High | CWE-22 | Path Traversal in Video File Path | `src/mapperclasses/input_classes.py` | 23-25 | Added `validate_videoFile` validator that checks for `..` sequences, absolute paths starting with `/`, and validates file extension against `ALLOWED_VIDEO_EXTENSIONS` whitelist | | 2 | High | CWE-284 | Absolute Path in Video File Path | `src/mapperclasses/input_classes.py` | 23-25 | Same validator rejects paths starting with `/` or containing path traversal patterns | | 3 | High | CWE-79 | Dangerous Patterns in Instruction Field | `src/mapperclasses/input_classes.py` | 34-36 | Added `validate_instruction` validator with pre-compiled regex patterns (`DANGEROUS_INPUT_COMPILED`) that block XSS, template injection, eval(), javascript:, etc. | | 4 | High | CWE-326 | Insecure API Key Handling | `src/config/constants.py` | 21-22 | Temp API key is now truncated when logged: `logging.warning("Generated temporary API key for development: %s...", temp_key[:8])` | | 5 | High | CWE-379 | Insecure API Key Verification | `src/utils/security.py` | 45-52 | API keys now compared using SHA-256 hashes with `secrets.compare_digest()` for constant-time comparison: `_API_KEY_HASHES = tuple(hashlib.sha256(key.encode()).hexdigest() for key in API_KEYS)` | | 6 | High | CWE-326 | Improper Rate Limiting Implementation | `src/utils/security.py` | 54-63 | Rate limiting implemented with sliding window algorithm, returns 429 with `Retry-After` header, health endpoints exempted | | 7 | High | CWE-377 | Improper Directory Creation | `src/utils/file_utils.py` | 20 | Already uses `os.makedirs(TEMP_FOLDER, exist_ok=True)`. Added TEMP_FOLDER validation with `os.path.realpath()` and unsafe prefix checks in constants.py | | 8 | High | CWE-377 | Insecure Default Configuration | `src/config/constants.py` | 4-7 | Added production mode detection (`IS_PRODUCTION`) that enforces auth enabled, HTTPS required, and warns if security features disabled | | 9 | High | CWE-327 | Invalid Model ID Format Validation | `src/routers/router.py` | 40 | Model ID validated via regex pattern `^[A-Za-z0-9_-]+$` in router, path traversal attempts return 404 | | 10 | High | CWE-20 | Improper Error Handling | `src/core/model_service.py` | 88 | OSError exceptions now return sanitized message: `raise ValueError("Error accessing model directory")` instead of leaking filesystem paths | | 11 | Medium | CWE-20 | Invalid File Extension in Video File Path | `src/mapperclasses/input_classes.py` | 23-25 | File extension validated against `ALLOWED_VIDEO_EXTENSIONS` whitelist (mp4, avi, mov, mkv, webm, flv, wmv) | | 12 | Medium | CWE-20 | Invalid Characters in Video File Path | `src/mapperclasses/input_classes.py` | 23-25 | Path length validated against `MAX_VIDEO_PATH_LENGTH`, dangerous patterns blocked | | 13 | Medium | CWE-377 | Insecure Temporary File Creation | `src/utils/file_utils.py` | 23 | UUID-based temp filename generation, extension validated from allowed list only | | 14 | Medium | CWE-200 | Improper Error Handling (router) | `src/routers/router.py` | N/A | Global exception handler in main.py returns generic error with error_id, no sensitive data exposed | | 15 | Low | CWE-200 | Lack of Timing Attack Protection | `src/utils/security.py` | N/A | Implemented constant-time comparison using `secrets.compare_digest()` on hashed keys | | 16 | Low | CWE-404 | Incomplete Cleanup of Temporary File | `src/utils/file_utils.py` | 108 | `cleanup_temp_file` now uses `os.path.realpath()` to resolve symlinks and validates path is within TEMP_FOLDER before deletion | | 17 | Medium | CWE-690 | Insecure Dependency Management | `src/utils/security.py` | N/A | f-string logging converted to lazy `%s` format for all 9 security-sensitive log calls to prevent log injection | | 18 | High | CWE-379 | Insecure TEMP_FOLDER Path | `src/config/constants.py` | N/A | Added path validation with `os.path.realpath()` and expanded unsafe prefix list (`/etc`, `/sys`, `/proc`, `/dev`, `/root`, `/boot`, `/sbin`) | --- ## False Positives | # | Severity | CWE | Issue | File | Why False Positive | |---|----------|-----|-------|------|-------------------| | 1 | High | CWE-79 | XSS in main.py headers | `src/main.py:45-52` | FastAPI's CORSMiddleware handles header sanitization. No user input injected into response headers. | | 2 | High | CWE-259 | Hard-coded Credentials in main.py | `src/main.py` | No credentials in main.py. Config loaded from environment variables via constants.py. | | 3 | High | CWE-754 | Improper Handling of Exceptional Conditions | `src/main.py` | Global exception handler (`global_exception_handler`) catches all exceptions and returns safe error response. | | 4 | High | CWE-434 | Unrestricted File Uploads | `src/config/constants.py` | API accepts video URLs, not file uploads. URLs are validated with extension whitelist and optional SSRF protection. | | 5 | High | CWE-379 | Insecure Download of Model Files | `src/misc/downlode-weights.py` | Offline utility script, not part of API. Hugging Face SDK handles integrity verification. | | 6 | High | CWE-305 | Unauthenticated Download from Hugging Face | `src/misc/downlode-weights.py` | Offline utility, not exposed. Public models don't require auth. | | 7 | High | CWE-377 | Insecure HTTP Methods Allowed | `test_security.py` | Test file checking that dangerous methods ARE blocked. Scanner misread test assertion as vulnerability. | | 8 | High | CWE-1304 | Large Request Body Rejected Incorrectly | `test_security.py` | Test file verifying large bodies ARE rejected. Scanner misread test as vulnerability. | | 9 | High | CWE-384 | No API Key Authentication | `test_auth.py` | Test file testing authentication. Scanner misread test fixture as missing auth. | | 10 | High | CWE-200 | Insecure Constant Time Comparison | `test_auth.py` | Test file. Actual implementation in security.py uses `secrets.compare_digest()`. | | 11 | High | CWE-384 | Improper Authentication | `run_tests.py` | Test runner script, not production code. Uses env vars for test credentials (correct). | | 12 | High | CWE-20 | Insecure Environment Variable Usage | `run_tests.py` | Test script. Production code validates env vars with defaults and warnings. | | 13 | High | CWE-319 | Lack of HTTPS Usage | `run_tests.py` | Test script uses localhost HTTP. Production enforces HTTPS via `HTTPS_ONLY` setting. | | 14 | High | CWE-284 | Insecure Configuration Handling | `run_tests.py` | Test configuration file. Production uses validated constants.py. | | 15 | High | CWE-20 | Improper Input Validation (test_api.py) | `test_api.py` | Test file testing input validation. Scanner confused test payloads with vulnerabilities. | | 16 | High | CWE-502 | Insecure Deserialization | `test_api.py` | Test file using standard `response.json()`. No pickle or unsafe deserialization. | | 17 | High | CWE-306 | Missing Authentication for Critical Function | `test_api.py` | Test file. Production endpoints require auth via `verify_api_key` dependency. | | 18 | High | CWE-326 | Insecure Configuration of API Keys | `conftest.py` | Test fixture with intentionally invalid key for negative testing. Not production code. | | 19 | High | CWE-798 | Use of Hardcoded Authentication Credentials | `conftest.py` | Test fixture. Production keys loaded from `API_KEYS` environment variable. | | 20 | High | CWE-287 | Improper Authentication in API Requests | `conftest.py` | Test helper class. Actual auth implemented in security.py. | | 21 | High | CWE-327 | Insecure Use of Requests Library | `conftest.py` | Test file using requests for API testing. Production code doesn't use requests library. | | 22 | High | CWE-20 | Unvalidated Input for Video File Path | `test_input_validation.py` | Test file testing that invalid paths ARE rejected. Scanner misread test payloads. | | 23 | High | CWE-43 | Unrestricted File Upload in Video File Handling | `test_input_validation.py` | Test file. API validates video URLs, doesn't accept uploads. | | 24 | High | CWE-305 | Improper Authentication for Model ID Handling | `test_input_validation.py` | Test file. Production validates model IDs with regex. | | 25 | High | CWE-639 | Insecure Direct Object References (IDOR) | `test_input_validation.py` | Test file. Model IDs are non-sensitive internal identifiers. | --- ## Skipped (By Design) | # | Severity | CWE | Issue | File | Reason Skipped | |---|----------|-----|-------|------|----------------| | 1 | High | CWE-311 | Insecure API Key Handling | `test_input_validation.py` | Test file behavior, not production code | | 2 | High | CWE-379 | Improper Rate Limiting Enforcement | `test_rate_limit.py` | Test file verifying rate limits work correctly | | 3 | Medium | CWE-287 | Insecure Health Endpoint Access | `test_auth.py` | **By Design**: Health endpoints (`/`, `/health`) are intentionally unauthenticated for load balancer health checks and monitoring. They expose no sensitive data (only status, version, GPU availability). | | 4 | Medium | CWE-327 | Weak API Key Validation | `test_auth.py` | Test file. Production uses SHA-256 hashed key comparison. | | 5 | Low | CWE-200 | Exposure of Sensitive Information via Retry-After | `test_rate_limit.py` | **By Design**: Retry-After header is RFC 6585 compliant. Provides UX benefit; minimal security risk. | | 6 | Medium | CWE-377 | Insecure Design (Pydantic) | `output_classes.py` | Pydantic v2 has built-in protection. Response classes are output-only, not user-controllable. | | 7 | Medium | CWE-1236 | Insufficient Logging and Monitoring | `test_api.py` | **By Design**: Comprehensive logging exists via `LoggerOperations`. Test file has minimal logging by design. | | 8 | Medium | CWE-20 | Lack of Error Handling in Rate Limit Exceeded | `test_rate_limit.py` | Rate limit returns proper 429 with Retry-After. This tests that behavior. | --- ## Out of Scope | # | Severity | CWE | Issue | File | Reason | |---|----------|-----|-------|------|--------| | 1 | High | CWE-362 | Improper Model Version Validation | `src/core/model_service.py:42` | Model version is validated as digit-only string. No actual security risk identified. | | 2 | High | CWE-259 | Use of Hardcoded Credentials | `src/core/model_service.py` | Model IDs and paths are configuration, not credentials. Loaded from env vars. | | 3 | High | CWE-312 | Missing Cryptographic Storage of Sensitive Data | `src/routers/router.py` | API keys are in-memory only, compared via hashes. No persistent storage of keys. | | 4 | High | CWE-327 | Insecure File Download Method | `src/utils/file_utils.py:29` | Uses eizen_utils library for downloads which enforces HTTPS. Out of scope for this repo. | | 5 | Medium | CWE-401 | Potential Memory Leak in Model Loading | `src/misc/downlode-weights.py:32` | Offline utility. Python GC handles cleanup. GPU memory explicitly freed in cleanup_models(). | | 6 | Medium | CWE-690 | Insecure Dependency Handling | `src/routers/router.py` | Dependency versions managed via requirements.txt. Regular updates recommended. | | 7 | Medium | CWE-347 | Use of Insecure Library Version | `src/core/model_service.py` | Library versions pinned in requirements.txt. Regular dependency audits recommended. | | 8 | Medium | CWE-312 | Insecure Data Storage on GPU | `src/core/model_service.py` | Model weights on GPU are public HuggingFace models. No sensitive user data stored on GPU. | --- ## Remediation Details by File ### `src/config/constants.py` | Change | Description | |--------|-------------| | Line 59 | Temp API key truncated in log: `logging.warning("Generated temporary API key for development: %s...", temp_key[:8])` | | Lines 107-112 | TEMP_FOLDER validation: `os.path.realpath()` + check against `/etc`, `/sys`, `/proc`, `/dev`, `/root`, `/boot`, `/sbin` | | Lines 135-137 | Production SSRF warning: `if IS_PRODUCTION and not MEDIA_URL_VALIDATION_ENABLED: logging.warning(...)` | | Lines 148-149 | Pre-compiled regex patterns: `DANGEROUS_INPUT_COMPILED = [re.compile(p, re.IGNORECASE) for p in DANGEROUS_INPUT_PATTERNS]` | ### `src/utils/security.py` | Change | Description | |--------|-------------| | Line 14 | Removed unused `import hmac` | | Lines 38-39 | Hash-based key storage: `_API_KEY_HASHES = tuple(hashlib.sha256(key.encode()).hexdigest() for key in API_KEYS)` | | Lines 102, 109, 115, 123, 131, 154, 168, 182, 195 | Converted 9 f-string log calls to lazy `%s` format for security | | Line 127 | API key comparison via hashes: `api_key_hash = hashlib.sha256(api_key.encode()).hexdigest()` then `secrets.compare_digest()` | ### `src/utils/file_utils.py` | Change | Description | |--------|-------------| | Lines 48-50 | Hash algorithm whitelist: `_ALLOWED_HASH_ALGORITHMS = frozenset({'sha256', 'sha384', 'sha512'})` | | Lines 57-59 | Cloud path normalization: `os.path.normpath()` before `..` check | | Lines 108-115 | `cleanup_temp_file` uses `os.path.realpath()` to resolve symlinks and validate within TEMP_FOLDER | ### `src/mapperclasses/input_classes.py` | Change | Description | |--------|-------------| | Import | Changed from `DANGEROUS_INPUT_PATTERNS` to `DANGEROUS_INPUT_COMPILED` | | `validate_instruction` | Uses pre-compiled regex patterns for efficient dangerous input detection | ### `src/core/model_service.py` | Change | Description | |--------|-------------| | Line 88 | Sanitized OSError: `raise ValueError("Error accessing model directory")` instead of exposing path | --- ## Verification Commands ```bash # Verify all Python files compile without errors python3 -m py_compile src/config/constants.py python3 -m py_compile src/utils/security.py python3 -m py_compile src/utils/file_utils.py python3 -m py_compile src/mapperclasses/input_classes.py python3 -m py_compile src/core/model_service.py python3 -m py_compile src/routers/router.py python3 -m py_compile src/main.py # Verify imports work at runtime python3 -c "from src.config.constants import *; print('constants.py OK')" python3 -c "from src.utils.security import *; print('security.py OK')" python3 -c "from src.utils.file_utils import *; print('file_utils.py OK')" ``` --- ## Recommendations 1. **Re-run NeuroSploit scan** to verify reduced finding count 2. **Run automated tests** to ensure functionality preserved 3. **Review test files** - Scanner flagged many test files; consider adding `# nosec` comments or excluding test directories from security scans 4. **Dependency audit** - Run `pip-audit` or `safety check` for vulnerable dependencies 5. **Enable MEDIA_URL_VALIDATION** in production to prevent SSRF attacks 6. **Enable HTTPS_ONLY** in production environments --- # Second Report Analysis (latest_report_vulnerability.html) **Report Date:** 2026-02-02 **Total Issues:** 61 (4 Critical, 45 High, 11 Medium, 1 Low) --- ## New Critical Findings (4) | # | CWE | Issue | File | Classification | Explanation | |---|-----|-------|------|----------------|-------------| | 1 | CWE-89 | SQL Injection in Video Processing | `src/mapperclasses/input_classes.py:45-52` | **False Positive** | No SQL database used. This is a video ML inference API using PyTorch, not a database application. The `video_file` field is a URL/path validated against whitelists. | | 2 | CWE-384 | Auth Can Be Disabled via Env Vars | `src/config/constants.py` | **By Design** | `API_AUTH` toggle is intentional for development. Production mode (`IS_PRODUCTION=true`) logs warnings when auth is disabled. | | 3 | CWE-798 | Hardcoded Credentials | `src/misc/testing/run_tests.py` | **False Positive** | Test script uses env vars for test credentials (correct pattern). Not production code. | | 4 | CWE-521 | Insecure Storage of Auth Credentials | `src/misc/testing/test_rate_limit.py` | **False Positive** | Test file. Scanner misidentified test assertions as vulnerabilities. | --- ## New High Findings - Already Remediated (19) These issues were flagged but were already fixed by our previous remediation work: | # | CWE | Issue | File | Lines | Why Already Fixed | |---|-----|-------|------|-------|-------------------| | 1 | CWE-307 | Improper Auth Attempt Restriction | `src/main.py` | N/A | Auth failure lockout implemented in `security.py` with `AUTH_FAILURE_LIMIT` and `AUTH_FAILURE_WINDOW` | | 2 | CWE-798 | Hardcoded Credentials | `src/main.py` | N/A | All credentials loaded from `API_KEYS` env var in constants.py | | 3 | CWE-755 | Improper Exception Handling | `src/main.py` | N/A | Global exception handler (`global_exception_handler`) returns safe error response with error_id | | 4 | CWE-284 | Insecure Configuration | `src/main.py` | N/A | Production mode warnings and validation in constants.py | | 5 | CWE-22 | Path Traversal in Video Path | `src/mapperclasses/input_classes.py` | 45-52 | `validate_videoFile` blocks `..` sequences and absolute paths | | 6 | CWE-78 | Command Injection in Instruction | `src/mapperclasses/input_classes.py` | 61-80 | `validate_instruction` with `DANGEROUS_INPUT_COMPILED` regex patterns | | 7 | CWE-79 | XSS in Instruction Field | `src/mapperclasses/input_classes.py` | 61-80 | Same `validate_instruction` blocks `