Spaces:
Configuration error
Configuration error
Niranjan-Murugarasu024
feat: TradeSense AI Chairman Edition production release ready for Hugging Face Spaces
0125724 Download backend/tests/data/test_security.py from BlueMen/tradesenseAi: direct link, hf CLI and curl.
- Browser
- Download file 4.39 kB
-
https://huggingface.co/spaces/BlueMen/tradesenseAi/resolve/main/backend/tests/data/test_security.py
- Command line
-
hf download hf://spaces/BlueMen/tradesenseAi/backend/tests/data/test_security.py
-
curl -L -o test_security.py https://huggingface.co/spaces/BlueMen/tradesenseAi/resolve/main/backend/tests/data/test_security.py
4.39 kB
| """ | |
| TradeSense AI — API Key Security Tests | |
| CRITICAL: Verifies that no API keys are leaked in logs, hashes, or API responses. | |
| """ | |
| import os | |
| import logging | |
| import json | |
| import pytest | |
| from unittest.mock import patch, MagicMock | |
| from backend.config.settings import settings | |
| class TestAPIKeySecurityNeverExposed: | |
| """ | |
| Security-critical test: API keys must NEVER appear in: | |
| - Log output | |
| - SHA-256 lineage fingerprints | |
| - API endpoint responses | |
| - Exception messages | |
| - Error responses | |
| """ | |
| def test_settings_keys_not_logged(self, caplog): | |
| """Verify that loading settings does NOT emit any key values in logs.""" | |
| with caplog.at_level(logging.DEBUG, logger="tradesense"): | |
| # Trigger settings access | |
| _ = settings.market_data.polygon_api_key | |
| _ = settings.market_data.fmp_api_key | |
| _ = settings.market_data.twelve_data_api_key | |
| _ = settings.market_data.alpha_vantage_api_key | |
| # Check all log messages for suspicious content | |
| dangerous_patterns = ["apikey=", "api_key=", "POLYGON_API_KEY=", "FMP_API_KEY="] | |
| for record in caplog.records: | |
| for pattern in dangerous_patterns: | |
| assert pattern not in record.message.lower(), ( | |
| f"Potential API key leak in log: '{record.message[:100]}...'" | |
| ) | |
| def test_no_default_hardcoded_keys_in_settings(self): | |
| """Verify settings module uses env vars only; no hardcoded fallbacks with real keys.""" | |
| import re | |
| import pathlib | |
| settings_path = pathlib.Path(__file__).parent.parent.parent.parent / "backend" / "config" / "settings.py" | |
| source = settings_path.read_text(encoding="utf-8") | |
| # A real API key is typically 20+ alphanumeric chars in a default= value | |
| suspicious = re.findall(r'default\s*=\s*["\']([A-Za-z0-9]{20,})["\']', source) | |
| assert len(suspicious) == 0, ( | |
| f"Possible hardcoded API key found in settings.py: {suspicious}" | |
| ) | |
| def test_env_key_not_in_snapshot_hash(self): | |
| """SHA-256 hashes must be computed from market data only, not API key values.""" | |
| from backend.data.lineage import LineageEngine | |
| import pandas as pd | |
| import numpy as np | |
| from datetime import date | |
| df = pd.DataFrame({ | |
| "session": [date(2024, 1, 2), date(2024, 1, 3)], | |
| "Open": [100.0, 101.0], | |
| "High": [102.0, 103.0], | |
| "Low": [99.0, 100.0], | |
| "Close": [101.0, 102.0], | |
| "Volume": [1000000.0, 1100000.0], | |
| }) | |
| fake_key = "SUPERSECRETFAKEAPIKEY12345" | |
| with patch.dict(os.environ, {"POLYGON_API_KEY": fake_key}): | |
| hash1 = LineageEngine.compute_sha256(df) | |
| with patch.dict(os.environ, {"POLYGON_API_KEY": "DIFFERENTFAKEKEY54321"}): | |
| hash2 = LineageEngine.compute_sha256(df) | |
| # Hashes must be identical — data is the same regardless of API key | |
| assert hash1 == hash2, "SHA-256 hash must depend only on market data, NOT on API key values." | |
| # Also ensure fake key does not appear in the hash | |
| assert fake_key not in hash1 | |
| class TestSecurityEnvironmentVariables: | |
| def test_polygon_key_loaded_from_env(self): | |
| """If env var is set, settings should read it without raising errors.""" | |
| with patch.dict(os.environ, {"POLYGON_API_KEY": "test_polygon_key_12345"}): | |
| # Re-instantiate to pick up env change | |
| from backend.config.settings import MarketDataSettings | |
| s = MarketDataSettings() | |
| assert s.polygon_api_key == "test_polygon_key_12345" | |
| def test_no_api_key_still_runs_without_crash(self): | |
| """When no API key is set, settings should return None gracefully.""" | |
| env_backup = {} | |
| keys_to_clear = ["POLYGON_API_KEY", "FMP_API_KEY", "TWELVE_DATA_API_KEY", "ALPHA_VANTAGE_API_KEY"] | |
| for k in keys_to_clear: | |
| if k in os.environ: | |
| env_backup[k] = os.environ.pop(k) | |
| try: | |
| from backend.config.settings import MarketDataSettings | |
| s = MarketDataSettings() | |
| # Should not raise; None is acceptable | |
| assert s.polygon_api_key is None or isinstance(s.polygon_api_key, str) | |
| finally: | |
| os.environ.update(env_backup) | |