ai-driven-e2e 0.4.0__py3-none-any.whl
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.
- ai_driven_e2e-0.4.0.dist-info/METADATA +427 -0
- ai_driven_e2e-0.4.0.dist-info/RECORD +49 -0
- ai_driven_e2e-0.4.0.dist-info/WHEEL +4 -0
- ai_driven_e2e-0.4.0.dist-info/entry_points.txt +2 -0
- ai_driven_e2e-0.4.0.dist-info/licenses/LICENSE +21 -0
- app/__init__.py +1 -0
- app/cli.py +381 -0
- app/config.py +105 -0
- app/graph.py +86 -0
- app/llm.py +246 -0
- app/logging.py +22 -0
- app/nodes/__init__.py +1 -0
- app/nodes/diagnoser.py +28 -0
- app/nodes/patch_generator.py +43 -0
- app/nodes/reviewer.py +34 -0
- app/nodes/selector_verifier.py +75 -0
- app/nodes/shadow_verifier.py +106 -0
- app/nodes/test_runner.py +36 -0
- app/preprocess/__init__.py +1 -0
- app/preprocess/aria_snapshot.py +70 -0
- app/preprocess/diff_ast_analyzer.py +201 -0
- app/preprocess/error_log_parser.py +52 -0
- app/preprocess/failure_scanner.py +32 -0
- app/prompts/__init__.py +1 -0
- app/prompts/diagnoser.py +11 -0
- app/prompts/patch_generator.py +14 -0
- app/prompts/reviewer.py +18 -0
- app/runner.py +31 -0
- app/sandbox.py +130 -0
- app/schemas.py +99 -0
- app/shadow/__init__.py +69 -0
- app/shadow/config.py +47 -0
- app/shadow/context.py +30 -0
- app/shadow/in_memory_snapshot_store.py +36 -0
- app/shadow/injector.py +131 -0
- app/shadow/interfaces.py +158 -0
- app/shadow/matcher.py +94 -0
- app/shadow/normalizer.py +119 -0
- app/shadow/runtime.py +233 -0
- app/shadow/schemas.py +62 -0
- app/shadow/scoring.py +114 -0
- app/shadow/snapshot_store.py +106 -0
- app/shadow/trace_parser.py +266 -0
- app/shadow/workspace.py +104 -0
- app/state.py +23 -0
- app/utils/__init__.py +1 -0
- app/utils/files.py +24 -0
- app/verify/__init__.py +1 -0
- app/verify/selector_check.py +92 -0
app/shadow/config.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CleanupPolicy(str, Enum):
|
|
7
|
+
"""When the Shadow Runtime should remove its workspace artifacts."""
|
|
8
|
+
|
|
9
|
+
ALWAYS = "always"
|
|
10
|
+
ON_SUCCESS = "on_success"
|
|
11
|
+
NEVER = "never"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ShadowConfig(BaseModel):
|
|
15
|
+
"""Shared, lightweight configuration for the Shadow Runtime.
|
|
16
|
+
|
|
17
|
+
Immutable so a config can be created once and passed around without risk of
|
|
18
|
+
downstream mutation. Directory fields are relative subdirectory names resolved
|
|
19
|
+
under :attr:`workspace_dir`, matching the current workspace layout.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
model_config = ConfigDict(frozen=True)
|
|
23
|
+
|
|
24
|
+
workspace_dir: str = Field(
|
|
25
|
+
default=".shadow_workspace",
|
|
26
|
+
description="root directory holding all shadow runtime artifacts",
|
|
27
|
+
)
|
|
28
|
+
cache_dir: str = Field(
|
|
29
|
+
default="cache",
|
|
30
|
+
description="cache subdirectory, relative to workspace_dir",
|
|
31
|
+
)
|
|
32
|
+
snapshots_dir: str = Field(
|
|
33
|
+
default="snapshots",
|
|
34
|
+
description="snapshot subdirectory, relative to workspace_dir",
|
|
35
|
+
)
|
|
36
|
+
tmp_dir: str = Field(
|
|
37
|
+
default="tmp",
|
|
38
|
+
description="temporary subdirectory, relative to workspace_dir",
|
|
39
|
+
)
|
|
40
|
+
offline: bool = Field(
|
|
41
|
+
default=False,
|
|
42
|
+
description="serve exclusively from snapshots without live network access",
|
|
43
|
+
)
|
|
44
|
+
cleanup_policy: CleanupPolicy = Field(
|
|
45
|
+
default=CleanupPolicy.ON_SUCCESS,
|
|
46
|
+
description="when to remove workspace artifacts after a shadow run",
|
|
47
|
+
)
|
app/shadow/context.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Shadow Runtime execution context.
|
|
2
|
+
Creating a context has no side effects; the runtime is responsible for
|
|
3
|
+
activating and deactivating it.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from app.shadow.interfaces import IMockInjector, IShadowWorkspace, ISnapshotStore
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class ShadowContext:
|
|
13
|
+
"""Shared, per-session state for the Shadow Runtime.
|
|
14
|
+
|
|
15
|
+
The collaborators are optional so a minimal runtime can be created and its
|
|
16
|
+
lifecycle exercised without wiring any real components yet.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
workspace: IShadowWorkspace | None = None
|
|
20
|
+
snapshot_store: ISnapshotStore | None = None
|
|
21
|
+
injector: IMockInjector | None = None
|
|
22
|
+
is_active: bool = False
|
|
23
|
+
|
|
24
|
+
def activate(self) -> None:
|
|
25
|
+
"""Mark the context as live for the current shadow session."""
|
|
26
|
+
self.is_active = True
|
|
27
|
+
|
|
28
|
+
def deactivate(self) -> None:
|
|
29
|
+
"""Mark the context as no longer live once the session ends."""
|
|
30
|
+
self.is_active = False
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""In-memory implementation of ISnapshotStore for tests."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from app.shadow.interfaces import ISnapshotStore
|
|
6
|
+
from app.shadow.schemas import ShadowSnapshot
|
|
7
|
+
from app.shadow.snapshot_store import (
|
|
8
|
+
SnapshotNotFoundError,
|
|
9
|
+
SnapshotStoreError,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class InMemorySnapshotStore(ISnapshotStore):
|
|
14
|
+
"""Dictionary-backed snapshot store used as a test double."""
|
|
15
|
+
|
|
16
|
+
def __init__(self):
|
|
17
|
+
self._snapshots: dict[str, ShadowSnapshot] = {}
|
|
18
|
+
|
|
19
|
+
def save_snapshot(self, snapshot_id: str, data: Any) -> None:
|
|
20
|
+
if isinstance(data, ShadowSnapshot):
|
|
21
|
+
snapshot = data
|
|
22
|
+
elif isinstance(data, dict):
|
|
23
|
+
try:
|
|
24
|
+
snapshot = ShadowSnapshot(**data)
|
|
25
|
+
except Exception as e:
|
|
26
|
+
raise SnapshotStoreError(f"Invalid snapshot dict structure: {e}")
|
|
27
|
+
else:
|
|
28
|
+
raise SnapshotStoreError("Unsupported data type; expected ShadowSnapshot or dict")
|
|
29
|
+
|
|
30
|
+
self._snapshots[snapshot_id] = snapshot
|
|
31
|
+
|
|
32
|
+
def get_snapshot(self, snapshot_id: str) -> ShadowSnapshot:
|
|
33
|
+
if snapshot_id not in self._snapshots:
|
|
34
|
+
raise SnapshotNotFoundError(f"Snapshot '{snapshot_id}' does not exist.")
|
|
35
|
+
|
|
36
|
+
return self._snapshots[snapshot_id]
|
app/shadow/injector.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Mock injector to intercept outgoing Playwright network requests and replay matching snapshots."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import inspect
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import structlog
|
|
9
|
+
|
|
10
|
+
from app.shadow.interfaces import IMockInjector
|
|
11
|
+
from app.shadow.matcher import NoMatchError, SnapshotMatcher
|
|
12
|
+
from app.shadow.schemas import CapturedRequest, NetworkSnapshot
|
|
13
|
+
|
|
14
|
+
logger = structlog.get_logger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MockInjector(IMockInjector):
|
|
18
|
+
"""Playwright-specific mock injector.
|
|
19
|
+
|
|
20
|
+
Intercepts outgoing network requests and fulfills them using a matching snapshot response.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, page_or_context: Any = None):
|
|
24
|
+
self.page_or_context = page_or_context
|
|
25
|
+
self.unmatched_requests: list[CapturedRequest] = []
|
|
26
|
+
self.matched_requests: list[tuple[CapturedRequest, float]] = []
|
|
27
|
+
self.matcher: SnapshotMatcher | None = None
|
|
28
|
+
|
|
29
|
+
def inject_mock(self, target: Any, mock_data: Any) -> Any:
|
|
30
|
+
"""Injects network mocks for the target pattern or page/context.
|
|
31
|
+
|
|
32
|
+
- If target is a string (e.g. a glob or regex pattern), registers request
|
|
33
|
+
interception for that pattern on the attached Playwright page/context.
|
|
34
|
+
- If target is a Playwright Page/BrowserContext object, attaches it as
|
|
35
|
+
the active target page/context and intercepts all requests ("**/*").
|
|
36
|
+
|
|
37
|
+
- mock_data can be a SnapshotMatcher or a list of NetworkSnapshot objects.
|
|
38
|
+
"""
|
|
39
|
+
# 1. Resolve mock_data into a SnapshotMatcher
|
|
40
|
+
if isinstance(mock_data, SnapshotMatcher):
|
|
41
|
+
self.matcher = mock_data
|
|
42
|
+
elif isinstance(mock_data, list):
|
|
43
|
+
# Parse list elements to NetworkSnapshot if needed, or assume correct type
|
|
44
|
+
snapshots = []
|
|
45
|
+
for item in mock_data:
|
|
46
|
+
if isinstance(item, dict):
|
|
47
|
+
snapshots.append(NetworkSnapshot(**item))
|
|
48
|
+
else:
|
|
49
|
+
snapshots.append(item)
|
|
50
|
+
self.matcher = SnapshotMatcher(snapshots)
|
|
51
|
+
else:
|
|
52
|
+
self.matcher = SnapshotMatcher([mock_data])
|
|
53
|
+
|
|
54
|
+
# 2. Resolve target and pattern
|
|
55
|
+
pattern = "**/*"
|
|
56
|
+
if isinstance(target, str):
|
|
57
|
+
pattern = target
|
|
58
|
+
else:
|
|
59
|
+
self.page_or_context = target
|
|
60
|
+
|
|
61
|
+
if not self.page_or_context:
|
|
62
|
+
raise ValueError("No Playwright page or context attached to MockInjector")
|
|
63
|
+
|
|
64
|
+
# 3. Define the routing handlers
|
|
65
|
+
def handle_request_sync(route: Any, request: Any) -> None:
|
|
66
|
+
captured_req = CapturedRequest(
|
|
67
|
+
method=request.method,
|
|
68
|
+
url=request.url,
|
|
69
|
+
headers=request.headers,
|
|
70
|
+
body=request.post_data,
|
|
71
|
+
)
|
|
72
|
+
try:
|
|
73
|
+
assert self.matcher is not None
|
|
74
|
+
response, score = self.matcher.match_with_score(captured_req)
|
|
75
|
+
self.matched_requests.append((captured_req, score))
|
|
76
|
+
body = response.body
|
|
77
|
+
if response.is_base64 and body:
|
|
78
|
+
body_bytes = base64.b64decode(body)
|
|
79
|
+
else:
|
|
80
|
+
body_bytes = body.encode("utf-8") if body is not None else None
|
|
81
|
+
|
|
82
|
+
route.fulfill(
|
|
83
|
+
status=response.status,
|
|
84
|
+
headers=response.headers,
|
|
85
|
+
body=body_bytes,
|
|
86
|
+
)
|
|
87
|
+
except NoMatchError:
|
|
88
|
+
self.unmatched_requests.append(captured_req)
|
|
89
|
+
logger.warning("network_mock_no_match", url=request.url, method=request.method)
|
|
90
|
+
route.abort("failed")
|
|
91
|
+
|
|
92
|
+
async def handle_request_async(route: Any, request: Any) -> None:
|
|
93
|
+
captured_req = CapturedRequest(
|
|
94
|
+
method=request.method,
|
|
95
|
+
url=request.url,
|
|
96
|
+
headers=request.headers,
|
|
97
|
+
body=request.post_data,
|
|
98
|
+
)
|
|
99
|
+
try:
|
|
100
|
+
assert self.matcher is not None
|
|
101
|
+
response, score = self.matcher.match_with_score(captured_req)
|
|
102
|
+
self.matched_requests.append((captured_req, score))
|
|
103
|
+
body = response.body
|
|
104
|
+
if response.is_base64 and body:
|
|
105
|
+
body_bytes = base64.b64decode(body)
|
|
106
|
+
else:
|
|
107
|
+
body_bytes = body.encode("utf-8") if body is not None else None
|
|
108
|
+
|
|
109
|
+
await route.fulfill(
|
|
110
|
+
status=response.status,
|
|
111
|
+
headers=response.headers,
|
|
112
|
+
body=body_bytes,
|
|
113
|
+
)
|
|
114
|
+
except NoMatchError:
|
|
115
|
+
self.unmatched_requests.append(captured_req)
|
|
116
|
+
logger.warning("network_mock_no_match", url=request.url, method=request.method)
|
|
117
|
+
await route.abort("failed")
|
|
118
|
+
|
|
119
|
+
# 4. Bind the route to the Playwright target (supports both sync and async APIs)
|
|
120
|
+
if inspect.iscoroutinefunction(self.page_or_context.route):
|
|
121
|
+
try:
|
|
122
|
+
loop = asyncio.get_running_loop()
|
|
123
|
+
return loop.create_task(self.page_or_context.route(pattern, handle_request_async))
|
|
124
|
+
except RuntimeError:
|
|
125
|
+
raise RuntimeError(
|
|
126
|
+
"Cannot register async route on Playwright page/context without a running event loop. "
|
|
127
|
+
"Ensure this is called from within an active async event loop."
|
|
128
|
+
)
|
|
129
|
+
else:
|
|
130
|
+
self.page_or_context.route(pattern, handle_request_sync)
|
|
131
|
+
return None
|
app/shadow/interfaces.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class IShadowWorkspace(ABC):
|
|
7
|
+
"""Interface for managing the Shadow runtime workspace.
|
|
8
|
+
|
|
9
|
+
Implementations are responsible for creating, resolving, and cleaning up
|
|
10
|
+
temporary directories used during Shadow execution.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def setup_dirs(self) -> None:
|
|
15
|
+
"""Create and initialize the required workspace directories.
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
None
|
|
19
|
+
|
|
20
|
+
Contract:
|
|
21
|
+
Implementations should ensure all required directories exist before
|
|
22
|
+
runtime execution begins.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
@abstractmethod
|
|
26
|
+
def resolve_path(self, relative_path: str | Path) -> Path:
|
|
27
|
+
"""Resolve a relative path within the Shadow workspace.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
relative_path: Relative file or directory path.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
Path: Absolute path inside the workspace.
|
|
34
|
+
|
|
35
|
+
Contract:
|
|
36
|
+
Returned paths must always remain inside the workspace root.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def cleanup(self, is_success: bool = False) -> None:
|
|
41
|
+
"""Clean up the workspace after execution.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
is_success: True if execution completed successfully.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
None
|
|
48
|
+
|
|
49
|
+
Contract:
|
|
50
|
+
Implementations should safely remove temporary resources while
|
|
51
|
+
preserving any required output artifacts.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ITraceParser(ABC):
|
|
56
|
+
"""Interface for parsing execution trace files.
|
|
57
|
+
|
|
58
|
+
Implementations convert raw trace files into structured data that can be
|
|
59
|
+
consumed by Shadow runtime features.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
@abstractmethod
|
|
63
|
+
def parse(self, trace_path: Path) -> Any:
|
|
64
|
+
"""Parse an execution trace.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
trace_path: Path to the trace file.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
Parsed trace representation.
|
|
71
|
+
|
|
72
|
+
Contract:
|
|
73
|
+
Raise an appropriate exception if the trace cannot be parsed.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ISnapshotStore(ABC):
|
|
78
|
+
"""Interface for storing and retrieving runtime snapshots."""
|
|
79
|
+
|
|
80
|
+
@abstractmethod
|
|
81
|
+
def save_snapshot(self, snapshot_id: str, data: Any) -> None:
|
|
82
|
+
"""Store a runtime snapshot.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
snapshot_id: Unique snapshot identifier.
|
|
86
|
+
data: Snapshot contents.
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
None
|
|
90
|
+
|
|
91
|
+
Contract:
|
|
92
|
+
Existing snapshots with the same identifier may be replaced.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
@abstractmethod
|
|
96
|
+
def get_snapshot(self, snapshot_id: str) -> Any:
|
|
97
|
+
"""Retrieve a stored snapshot.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
snapshot_id: Snapshot identifier.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
Stored snapshot data.
|
|
104
|
+
|
|
105
|
+
Contract:
|
|
106
|
+
Raise an appropriate error if the snapshot does not exist.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class IMockInjector(ABC):
|
|
111
|
+
"""Interface for injecting mocked responses into runtime execution."""
|
|
112
|
+
|
|
113
|
+
@abstractmethod
|
|
114
|
+
def inject_mock(self, target: str, mock_data: Any) -> Any:
|
|
115
|
+
"""Register a mock response.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
target: Target endpoint or resource.
|
|
119
|
+
mock_data: Mock response data.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
None
|
|
123
|
+
|
|
124
|
+
Contract:
|
|
125
|
+
Future runtime requests to the target should receive the provided mock.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class IShadowRuntime(ABC):
|
|
130
|
+
"""Blueprint for the Shadow Runtime orchestrator.
|
|
131
|
+
|
|
132
|
+
Owns the basic runtime lifecycle and the shared execution context that future
|
|
133
|
+
Shadow Testing features (trace parsing, snapshot loading, network
|
|
134
|
+
interception, DOM injection) will build upon. Only the lifecycle surface is
|
|
135
|
+
defined at this foundational stage.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
@abstractmethod
|
|
139
|
+
def initialize(self) -> None:
|
|
140
|
+
"""Initialize the Shadow runtime.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
None
|
|
144
|
+
|
|
145
|
+
Contract:
|
|
146
|
+
Prepare all runtime resources before execution begins.
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
@abstractmethod
|
|
150
|
+
def shutdown(self) -> None:
|
|
151
|
+
"""Shut down the Shadow runtime.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
None
|
|
155
|
+
|
|
156
|
+
Contract:
|
|
157
|
+
Release allocated resources and perform cleanup.
|
|
158
|
+
"""
|
app/shadow/matcher.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Matching engine to resolve incoming requests against captured network snapshots."""
|
|
2
|
+
|
|
3
|
+
import urllib.parse
|
|
4
|
+
|
|
5
|
+
from app.shadow.scoring import MatchScorer
|
|
6
|
+
from app.shadow.schemas import CapturedRequest, CapturedResponse, NetworkSnapshot
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class NoMatchError(Exception):
|
|
10
|
+
"""Raised when the matcher cannot find a matching snapshot for a request."""
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self, request: CapturedRequest, message: str = "No matching network snapshot found"
|
|
14
|
+
):
|
|
15
|
+
self.request = request
|
|
16
|
+
super().__init__(f"{message}: {request.method} {request.url}")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SnapshotMatcher:
|
|
20
|
+
"""Matches outgoing intercepted requests against stored NetworkSnapshots using similarity scoring."""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
snapshots: list[NetworkSnapshot],
|
|
25
|
+
scorer: MatchScorer | None = None,
|
|
26
|
+
):
|
|
27
|
+
self.snapshots = snapshots
|
|
28
|
+
self.scorer = scorer or MatchScorer()
|
|
29
|
+
|
|
30
|
+
def match(self, request: CapturedRequest) -> CapturedResponse:
|
|
31
|
+
"""Resolves the given captured request to the best-matching captured response.
|
|
32
|
+
|
|
33
|
+
Scans all snapshots, scores them using the MatchScorer, and returns the response
|
|
34
|
+
of the highest scoring candidate. Resolves ties deterministically.
|
|
35
|
+
"""
|
|
36
|
+
candidates = []
|
|
37
|
+
|
|
38
|
+
for idx, snapshot in enumerate(self.snapshots):
|
|
39
|
+
score = self.scorer.calculate_score(request, snapshot.request)
|
|
40
|
+
if score >= 0:
|
|
41
|
+
candidates.append((score, idx, snapshot))
|
|
42
|
+
|
|
43
|
+
if not candidates:
|
|
44
|
+
raise NoMatchError(request)
|
|
45
|
+
|
|
46
|
+
# Deterministic conflict resolution/tie-breaking:
|
|
47
|
+
# Sort candidates by:
|
|
48
|
+
# 1. Score descending (highest score first)
|
|
49
|
+
# 2. Exact URL match (True comes before False)
|
|
50
|
+
# 3. Exact URL path match (True comes before False)
|
|
51
|
+
# 4. Original snapshot index ascending (stable, deterministic ordering)
|
|
52
|
+
def sort_key(item):
|
|
53
|
+
score, idx, snapshot = item
|
|
54
|
+
exact_url = request.url == snapshot.request.url
|
|
55
|
+
|
|
56
|
+
p1 = urllib.parse.urlparse(request.url).path
|
|
57
|
+
p2 = urllib.parse.urlparse(snapshot.request.url).path
|
|
58
|
+
exact_path = p1 == p2
|
|
59
|
+
|
|
60
|
+
# Sort is ascending by default. To put highest scores first, we negate score.
|
|
61
|
+
# To put exact matches (True) first, we negate the boolean value (-1 for True, 0 for False).
|
|
62
|
+
return (-score, -int(exact_url), -int(exact_path), idx)
|
|
63
|
+
|
|
64
|
+
candidates.sort(key=sort_key)
|
|
65
|
+
best_candidate = candidates[0]
|
|
66
|
+
|
|
67
|
+
return best_candidate[2].response
|
|
68
|
+
|
|
69
|
+
def match_with_score(self, request: CapturedRequest) -> tuple[CapturedResponse, float]:
|
|
70
|
+
"""Resolves the given captured request and returns the response plus its similarity score."""
|
|
71
|
+
candidates = []
|
|
72
|
+
|
|
73
|
+
for idx, snapshot in enumerate(self.snapshots):
|
|
74
|
+
score = self.scorer.calculate_score(request, snapshot.request)
|
|
75
|
+
if score >= 0:
|
|
76
|
+
candidates.append((score, idx, snapshot))
|
|
77
|
+
|
|
78
|
+
if not candidates:
|
|
79
|
+
raise NoMatchError(request)
|
|
80
|
+
|
|
81
|
+
def sort_key(item):
|
|
82
|
+
score, idx, snapshot = item
|
|
83
|
+
exact_url = request.url == snapshot.request.url
|
|
84
|
+
|
|
85
|
+
p1 = urllib.parse.urlparse(request.url).path
|
|
86
|
+
p2 = urllib.parse.urlparse(snapshot.request.url).path
|
|
87
|
+
exact_path = p1 == p2
|
|
88
|
+
|
|
89
|
+
return (-score, -int(exact_url), -int(exact_path), idx)
|
|
90
|
+
|
|
91
|
+
candidates.sort(key=sort_key)
|
|
92
|
+
best_candidate = candidates[0]
|
|
93
|
+
|
|
94
|
+
return best_candidate[2].response, best_candidate[0]
|
app/shadow/normalizer.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Normalizer to scrub dynamic and volatile parameters from network requests."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import urllib.parse
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
# Regex patterns for dynamic fields
|
|
9
|
+
UUID_RE = re.compile(
|
|
10
|
+
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"
|
|
11
|
+
)
|
|
12
|
+
ISO_TIMESTAMP_RE = re.compile(
|
|
13
|
+
r"\b\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b"
|
|
14
|
+
)
|
|
15
|
+
EPOCH_TIMESTAMP_RE = re.compile(r"\b\d{10,13}\b")
|
|
16
|
+
|
|
17
|
+
# Keys that are typically dynamic and should be normalized/stripped
|
|
18
|
+
DYNAMIC_PARAM_KEYS = {
|
|
19
|
+
"timestamp",
|
|
20
|
+
"time",
|
|
21
|
+
"nonce",
|
|
22
|
+
"sig",
|
|
23
|
+
"signature",
|
|
24
|
+
"token",
|
|
25
|
+
"session_id",
|
|
26
|
+
"_",
|
|
27
|
+
"ts",
|
|
28
|
+
}
|
|
29
|
+
DYNAMIC_HEADER_KEYS = {
|
|
30
|
+
"authorization",
|
|
31
|
+
"cookie",
|
|
32
|
+
"x-csrf-token",
|
|
33
|
+
"date",
|
|
34
|
+
"user-agent",
|
|
35
|
+
"sec-ch-ua",
|
|
36
|
+
"sec-ch-ua-mobile",
|
|
37
|
+
"sec-ch-ua-platform",
|
|
38
|
+
"referer",
|
|
39
|
+
"host",
|
|
40
|
+
"content-length",
|
|
41
|
+
"connection",
|
|
42
|
+
"accept-encoding",
|
|
43
|
+
"accept-language",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class RequestNormalizer:
|
|
48
|
+
"""Normalizes request parameters, paths, headers, and bodies to allow fuzzy matching."""
|
|
49
|
+
|
|
50
|
+
def normalize_value(self, val: str) -> str:
|
|
51
|
+
"""Replace UUIDs, timestamps, and nonces with placeholder tokens in strings."""
|
|
52
|
+
if not isinstance(val, str):
|
|
53
|
+
return str(val)
|
|
54
|
+
val = UUID_RE.sub("<UUID>", val)
|
|
55
|
+
val = ISO_TIMESTAMP_RE.sub("<TIMESTAMP>", val)
|
|
56
|
+
val = EPOCH_TIMESTAMP_RE.sub("<TIMESTAMP>", val)
|
|
57
|
+
return val
|
|
58
|
+
|
|
59
|
+
def normalize_url(self, url: str) -> tuple[str, dict[str, list[str]]]:
|
|
60
|
+
"""Normalize URL path and query parameters. Returns (normalized_path, normalized_query)."""
|
|
61
|
+
parsed = urllib.parse.urlparse(url)
|
|
62
|
+
|
|
63
|
+
# Normalize path segments
|
|
64
|
+
path_segments = parsed.path.split("/")
|
|
65
|
+
normalized_segments = [self.normalize_value(seg) for seg in path_segments]
|
|
66
|
+
normalized_path = "/".join(normalized_segments)
|
|
67
|
+
|
|
68
|
+
# Normalize query params
|
|
69
|
+
query_params = urllib.parse.parse_qs(parsed.query)
|
|
70
|
+
normalized_query = {}
|
|
71
|
+
for k, vals in query_params.items():
|
|
72
|
+
k_lower = k.lower()
|
|
73
|
+
if k_lower in DYNAMIC_PARAM_KEYS:
|
|
74
|
+
# Key is completely dynamic, skip it to prevent mismatching on dynamic nonces
|
|
75
|
+
continue
|
|
76
|
+
normalized_query[k] = [self.normalize_value(v) for v in vals]
|
|
77
|
+
|
|
78
|
+
return normalized_path, normalized_query
|
|
79
|
+
|
|
80
|
+
def normalize_headers(self, headers: dict[str, str]) -> dict[str, str]:
|
|
81
|
+
"""Normalize header values and filter out unstable headers."""
|
|
82
|
+
normalized = {}
|
|
83
|
+
for k, v in headers.items():
|
|
84
|
+
k_lower = k.lower()
|
|
85
|
+
if k_lower in DYNAMIC_HEADER_KEYS:
|
|
86
|
+
continue
|
|
87
|
+
normalized[k_lower] = self.normalize_value(v)
|
|
88
|
+
return normalized
|
|
89
|
+
|
|
90
|
+
def normalize_body(self, body: str | None) -> Any:
|
|
91
|
+
"""Normalize request body (recursively if JSON, text replacement if string)."""
|
|
92
|
+
if not body:
|
|
93
|
+
return ""
|
|
94
|
+
|
|
95
|
+
# Try to parse as JSON
|
|
96
|
+
try:
|
|
97
|
+
parsed_json = json.loads(body)
|
|
98
|
+
return self._normalize_json_node(parsed_json)
|
|
99
|
+
except json.JSONDecodeError:
|
|
100
|
+
# Fallback to plain text regex scrubbing
|
|
101
|
+
return self.normalize_value(body)
|
|
102
|
+
|
|
103
|
+
def _normalize_json_node(self, node: Any) -> Any:
|
|
104
|
+
"""Recursively normalizes keys/values in a parsed JSON structure."""
|
|
105
|
+
if isinstance(node, dict):
|
|
106
|
+
new_dict = {}
|
|
107
|
+
for k, v in node.items():
|
|
108
|
+
k_lower = k.lower()
|
|
109
|
+
if k_lower in DYNAMIC_PARAM_KEYS:
|
|
110
|
+
new_dict[k] = "<DYNAMIC>"
|
|
111
|
+
else:
|
|
112
|
+
new_dict[k] = self._normalize_json_node(v)
|
|
113
|
+
return new_dict
|
|
114
|
+
elif isinstance(node, list):
|
|
115
|
+
return [self._normalize_json_node(item) for item in node]
|
|
116
|
+
elif isinstance(node, str):
|
|
117
|
+
return self.normalize_value(node)
|
|
118
|
+
else:
|
|
119
|
+
return node
|