File size: 7,920 Bytes
aef804e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | """
Fuzzing test configuration with Atheris setup.
This module provides pytest fixtures for coverage-guided fuzzing using
Atheris to discover crashes, security vulnerabilities, and edge cases.
Fixtures:
- atheris_fuzz_target: Base fixture for Atheris fuzz targets
- fuzz_input_data: Provider for random fuzz input
- fuzz_timeout: Timeout fixture (default 300s for fuzzing)
- Import existing fixtures from e2e_ui for auth and database isolation
"""
import os
import sys
import tempfile
from typing import Generator, Callable, Any
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
# Add backend to path for imports
backend_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if backend_dir not in sys.path:
sys.path.insert(0, backend_dir)
# ============================================================================
# IMPORT EXISTING FIXTURES FROM E2E_UI (NO DUPLICATION)
# ============================================================================
# Reuse existing auth and database fixtures to avoid duplication
from tests.e2e_ui.fixtures.auth_fixtures import authenticated_user, test_user
from tests.e2e_ui.fixtures.database_fixtures import db_session
# Re-export for direct use in fuzzing tests
__all__ = [
'authenticated_user',
'test_user',
'db_session',
'atheris_fuzz_target',
'fuzz_input_data',
'fuzz_timeout',
]
# ============================================================================
# ATHERIS SETUP AND TELEMETRY
# ============================================================================
# Try to import Atheris (optional - graceful degradation if not installed)
try:
import atheris
ATHERIS_AVAILABLE = True
except ImportError:
ATHERIS_AVAILABLE = False
print("Warning: Atheris not installed. Fuzzing tests will be skipped.")
print("Install with: pip install atheris")
@pytest.fixture(scope="session")
def atheris_available() -> bool:
"""
Check if Atheris is available for fuzzing.
Returns:
bool: True if Atheris is installed, False otherwise
"""
return ATHERIS_AVAILABLE
@pytest.fixture(scope="session")
def fuzz_timeout() -> int:
"""
Default timeout for fuzzing tests in seconds.
Fuzzing runs can take a long time to discover interesting inputs.
Default: 300 seconds (5 minutes)
Returns:
int: Timeout in seconds
"""
return int(os.getenv("FUZZ_TIMEOUT", "300"))
@pytest.fixture(scope="function")
def fuzz_input_data() -> Callable[[], bytes]:
"""
Provider for random fuzz input data.
This fixture generates random byte sequences for fuzzing.
Atheris will mutate this input to discover crashes.
Returns:
Callable: Function that generates random bytes
"""
def _generate_random_bytes(max_length: int = 1024) -> bytes:
"""Generate random bytes for fuzzing.
Args:
max_length: Maximum length of random bytes (default: 1024)
Returns:
bytes: Random byte sequence
"""
import os
length = os.urandom(1)[0] % max_length # Random length up to max_length
return os.urandom(length)
return _generate_random_bytes
@pytest.fixture(scope="function")
def atheris_fuzz_target():
"""
Base fixture for Atheris fuzz targets.
This fixture provides a context manager for running Atheris fuzzing.
If Atheris is not installed, the test will be skipped.
Usage:
def test_parse_json_fuzz(atheris_fuzz_target):
with atheris_fuzz_target() as (data, fdp):
# Mutate input with fdp
json_str = fdp.ConsumeRandomLengthString()
# Test code that should not crash
parse_json(json_str)
Yields:
tuple: (data bytes, FileDictProto object) if Atheris available
Raises:
pytest.skip.Exception: If Atheris is not installed
"""
if not ATHERIS_AVAILABLE:
pytest.skip("Atheris not installed - fuzzing test skipped")
import atheris
class FuzzTargetContext:
"""Context manager for Atheris fuzz target."""
def __enter__(self):
# Initialize Atheris with libFuzzer
atheris.Setup(sys.argv, [])
# Create FileDictProto for structured input generation
from atheris import fp
return b"", fp
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
# Fuzzing found a crash
return False
return True
return FuzzTargetContext()
@pytest.fixture(scope="function")
def fuzz_crash_dir() -> str:
"""
Create temporary directory for crash artifacts.
When Atheris discovers a crash, it saves the crashing input
to a directory for later analysis.
Returns:
str: Path to crash artifacts directory
"""
crash_dir = tempfile.mkdtemp(prefix="fuzz_crashes_")
return crash_dir
@pytest.fixture(scope="function", autouse=True)
def cleanup_fuzz_artifacts(request):
"""
Clean up fuzzing artifacts after each test.
This autouse fixture ensures that temporary files created during
fuzzing are cleaned up after the test completes.
Args:
request: Pytest request object
"""
yield
# Clean up crash artifacts if test created them
if hasattr(request, "funcargs"):
crash_dir = request.funcargs.get("fuzz_crash_dir")
if crash_dir and os.path.exists(crash_dir):
import shutil
try:
shutil.rmtree(crash_dir)
except Exception:
pass # Best effort cleanup
# ============================================================================
# PYTEST HOOKS FOR FUZZING TESTS
# ============================================================================
def pytest_configure(config):
"""
Pytest configuration hook for fuzzing tests.
Register custom markers for fuzzing test categorization.
Args:
config: Pytest config object
"""
config.addinivalue_line(
"markers",
"fuzzing: Mark test as fuzzing test (requires Atheris)"
)
config.addinivalue_line(
"markers",
"crash: Mark test as expected to discover crash"
)
config.addinivalue_line(
"markers",
"hang: Mark test as expected to discover hang (timeout)"
)
@pytest.fixture(autouse=True)
def skip_fuzzing_without_atheris(request):
"""
Automatically skip fuzzing tests if Atheris is not installed.
This autouse fixture checks for the 'fuzzing' marker and skips
the test if Atheris is not available.
Args:
request: Pytest request object
"""
if request.node.get_closest_marker('fuzzing') and not ATHERIS_AVAILABLE:
pytest.skip("Atheris not installed - fuzzing test skipped")
# ============================================================================
# FUZZING CAMPAIGN FIXTURES
# ============================================================================
@pytest.fixture(scope="session")
def fuzz_campaign_duration() -> int:
"""
Duration for fuzzing campaign in seconds.
Longer campaigns discover more bugs but take more time.
Default: 60 seconds for quick fuzzing runs
Returns:
int: Campaign duration in seconds
"""
return int(os.getenv("FUZZ_CAMPAIGN_DURATION", "60"))
@pytest.fixture(scope="function")
def fuzz_stats():
"""
Track fuzzing statistics during test run.
This fixture provides a dictionary to store fuzzing metrics
like executions, crashes, coverage.
Returns:
dict: Statistics dictionary
"""
stats = {
"executions": 0,
"crashes": 0,
"hangs": 0,
"coverage": 0.0,
"start_time": None,
"end_time": None,
}
return stats
|