-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate_manager.py
More file actions
401 lines (333 loc) · 14.1 KB
/
Copy pathstate_manager.py
File metadata and controls
401 lines (333 loc) · 14.1 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#!/usr/bin/env python3
"""
Counterscarp Engine — Scan state persistence for resume capability.
Provides the ScanStateManager class for writing and reading scan state
files that enable the --resume flag to restart a scan from the last
completed analysis phase.
"""
import dataclasses
import json
import logging
import secrets
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional, Set, cast
from exceptions import CounterscarpError
logger = logging.getLogger("counterscarp.state_manager")
# ---------------------------------------------------------------------------
# Custom exceptions
# ---------------------------------------------------------------------------
class StateError(CounterscarpError):
"""Raised for state persistence or session management errors.
Example:
>>> raise StateError("State file not found", details={"path": "..."})
"""
def __init__(
self,
message: str,
details: Optional[Dict[str, Any]] = None,
) -> None:
super().__init__(message, details)
# ---------------------------------------------------------------------------
# JSON encoder
# ---------------------------------------------------------------------------
class _CounterscarpJSONEncoder(json.JSONEncoder):
"""Custom JSON encoder that handles dataclasses, datetime, and Path."""
def default(self, obj: Any) -> Any:
if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
return dataclasses.asdict(obj)
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, Path):
return str(obj)
if isinstance(obj, set):
return list(obj)
return super().default(obj)
# ---------------------------------------------------------------------------
# ScanStateManager
# ---------------------------------------------------------------------------
class ScanStateManager:
"""Manages per-session scan state files for resume capability.
State files are stored as JSON inside *counterscarp_dir* (default
``.scarpshield/``). Each session produces:
* ``scan_state_{session_id}.json`` — top-level session record
* ``phase_{phase_name}_{session_id}.json`` — per-phase result blobs
Args:
counterscarp_dir: Directory path where state files are stored.
If omitted, `.scarpshield` is used as the preferred
state directory.
Legacy `.counterscarp` state is still readable for resume.
"""
def __init__(self, counterscarp_dir: Optional[str] = None) -> None:
if counterscarp_dir is None:
self._dir = Path(".scarpshield")
self._legacy_dir = Path(".counterscarp")
else:
self._dir = Path(counterscarp_dir)
self._legacy_dir = None
self._dir.mkdir(parents=True, exist_ok=True)
self._session_id: Optional[str] = None
self._state_file: Optional[Path] = None
logger.debug("ScanStateManager initialised with dir=%s", self._dir)
@property
def storage_dir(self) -> Path:
"""Return the preferred directory used for new state writes."""
return self._dir
@property
def session_id(self) -> Optional[str]:
"""Return the active session ID, or None if no session is active."""
return self._session_id
# ------------------------------------------------------------------
# Session lifecycle
# ------------------------------------------------------------------
def start_session(self, target: str, cli_args: Dict[str, Any]) -> str:
"""Create a new scan session and return its session ID.
Args:
target: Path or identifier of the contract/directory being scanned.
cli_args: Dictionary of CLI flags/options passed to the scan.
Returns:
The generated session_id string.
"""
session_id = (
f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_"
f"{secrets.token_hex(4)}"
)
self._session_id = session_id
self._state_file = self._dir / f"scan_state_{session_id}.json"
state: Dict[str, Any] = {
"session_id": session_id,
"target": target,
"cli_args": cli_args,
"started_at": datetime.now(timezone.utc).isoformat(),
"phases_completed": [],
"status": "in_progress",
}
self._write_json(self._state_file, state)
logger.info("Session started: %s (target=%s)", session_id, target)
return session_id
def mark_session_complete(self) -> None:
"""Mark the active session as completed.
Raises:
StateError: If no session is currently active.
"""
state = self._load_active_state()
state["status"] = "completed"
state["completed_at"] = datetime.now(timezone.utc).isoformat()
self._write_json(self._state_file, state) # type: ignore[arg-type]
logger.info("Session completed: %s", self._session_id)
# ------------------------------------------------------------------
# Phase tracking
# ------------------------------------------------------------------
def mark_phase_complete(
self,
phase_name: str,
findings_count: int = 0,
duration_secs: float = 0.0,
) -> None:
"""Record a phase as completed in the active session state.
Args:
phase_name: Identifier for the analysis phase (e.g. ``"slither"``).
findings_count: Number of findings produced by this phase.
duration_secs: Wall-clock seconds the phase took.
Raises:
StateError: If no active session exists.
"""
state = self._load_active_state()
entry: Dict[str, Any] = {
"name": phase_name,
"completed_at": datetime.now(timezone.utc).isoformat(),
"findings_count": findings_count,
"duration_secs": round(duration_secs, 3),
}
state["phases_completed"].append(entry)
self._write_json(self._state_file, state) # type: ignore[arg-type]
logger.debug(
"Phase complete: %s | findings=%d | duration=%.2fs",
phase_name,
findings_count,
duration_secs,
)
def get_completed_phases(self) -> Set[str]:
"""Return the set of completed phase names for the active session.
Returns:
Set of phase name strings.
Raises:
StateError: If no active session exists.
"""
state = self._load_active_state()
return {entry["name"] for entry in state.get("phases_completed", [])}
def is_phase_pending(self, phase_name: str) -> bool:
"""Check whether a phase has NOT yet been completed.
Args:
phase_name: Phase identifier to check.
Returns:
``True`` if the phase has not been marked complete.
"""
return phase_name not in self.get_completed_phases()
# ------------------------------------------------------------------
# Phase result blobs
# ------------------------------------------------------------------
def save_phase_results(self, phase_name: str, data: Any) -> None:
"""Persist arbitrary phase result data to disk.
Args:
phase_name: Phase identifier used in the filename.
data: Serialisable object (dict, list, dataclass, etc.).
Raises:
StateError: If no active session exists.
"""
if self._session_id is None:
raise StateError(
"No active session — call start_session() first.",
details={"phase": phase_name},
)
result_file = self._dir / f"phase_{phase_name}_{self._session_id}.json"
self._write_json(result_file, data)
logger.debug("Phase results saved: %s", result_file.name)
def load_phase_results(self, phase_name: str) -> Any:
"""Load previously saved phase result data.
Args:
phase_name: Phase identifier to load.
Returns:
Deserialised data, or ``None`` if no results file exists.
Raises:
StateError: If no active session exists.
"""
if self._session_id is None:
raise StateError(
"No active session — call start_session() or "
"load_session() first.",
details={"phase": phase_name},
)
result_file = self._dir / f"phase_{phase_name}_{self._session_id}.json"
if not result_file.exists():
logger.debug("No phase results file found: %s", result_file.name)
return None
with result_file.open("r", encoding="utf-8") as fh:
return json.load(fh)
# ------------------------------------------------------------------
# Session loading
# ------------------------------------------------------------------
def load_session(self, session_id: str) -> Dict[str, Any]:
"""Load an existing session by ID and make it the active session.
Args:
session_id: The session ID to load.
Returns:
The full session state dictionary.
Raises:
FileNotFoundError: If no state file exists for this session_id.
StateError: If the state file cannot be parsed.
"""
state_file = self._resolve_session_file(session_id)
if state_file is None:
raise FileNotFoundError(
f"No state file found for session '{session_id}' "
f"in '{self._dir}' or legacy directory."
)
try:
with state_file.open("r", encoding="utf-8") as fh:
state: Dict[str, Any] = json.load(fh)
except json.JSONDecodeError as exc:
raise StateError(
f"State file for session '{session_id}' is corrupt.",
details={"path": str(state_file)},
) from exc
# Make this the active session so subsequent calls work
self._session_id = session_id
self._state_file = state_file
logger.info("Session loaded: %s", session_id)
return state
# ------------------------------------------------------------------
# Maintenance
# ------------------------------------------------------------------
def cleanup_old_sessions(self, max_age_days: int = 30) -> None:
"""Remove state and phase result files older than *max_age_days*.
Args:
max_age_days: Files older than this many days are deleted.
"""
cutoff = time.time() - max_age_days * 86400
patterns = ["scan_state_*.json", "phase_*_*.json"]
removed = 0
for pattern in patterns:
for path in self._dir.glob(pattern):
try:
if path.stat().st_mtime < cutoff:
path.unlink()
removed += 1
logger.debug("Removed old state file: %s", path.name)
except OSError as exc:
logger.warning(
"Could not remove %s: %s", path.name, exc
)
logger.info(
"Cleanup complete: removed %d file(s) older than %d day(s).",
removed,
max_age_days,
)
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _load_active_state(self) -> Dict[str, Any]:
"""Load the current active state file.
Returns:
Parsed state dictionary.
Raises:
StateError: If no session is active or the file cannot be read.
"""
if self._session_id is None or self._state_file is None:
raise StateError(
"No active session — call start_session() or "
"load_session() first."
)
if not self._state_file.exists():
raise StateError(
f"State file missing for session '{self._session_id}'.",
details={"path": str(self._state_file)},
)
try:
with self._state_file.open("r", encoding="utf-8") as fh:
return cast(Dict[str, Any], json.load(fh))
except json.JSONDecodeError as exc:
raise StateError(
f"State file is corrupt for session '{self._session_id}'.",
details={"path": str(self._state_file)},
) from exc
def _write_json(self, path: Path, data: Any) -> None:
"""Atomically write *data* as JSON to *path*.
Uses a temporary sibling file + rename for crash safety.
Args:
path: Destination file path.
data: JSON-serialisable object.
"""
tmp_path = path.with_suffix(".tmp")
try:
with tmp_path.open("w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2, cls=_CounterscarpJSONEncoder)
fh.write("\n")
tmp_path.replace(path)
except OSError as exc:
raise StateError(
f"Failed to write state file: {path}",
details={"path": str(path)},
) from exc
def _resolve_session_file(self, session_id: str) -> Optional[Path]:
"""Resolve a session state file path in preferred then legacy dirs."""
filename = f"scan_state_{session_id}.json"
preferred = self._dir / filename
if preferred.exists():
return preferred
if self._legacy_dir is not None:
legacy = self._legacy_dir / filename
if legacy.exists():
return legacy
return None
# ---------------------------------------------------------------------------
# Module self-test
# ---------------------------------------------------------------------------
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
sm = ScanStateManager()
sid = sm.start_session("/tmp/test", {"report": True})
sm.mark_phase_complete("slither", 5, 12.3)
print(sm.get_completed_phases())
print("OK")