diff --git a/cracklab/server/migrations/002_crack_search_contexts.sql b/cracklab/server/migrations/002_crack_search_contexts.sql new file mode 100644 index 0000000..20049e6 --- /dev/null +++ b/cracklab/server/migrations/002_crack_search_contexts.sql @@ -0,0 +1,30 @@ +CREATE TABLE IF NOT EXISTS crack_search_contexts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + token_hash TEXT NOT NULL UNIQUE, + criteria_json TEXT NOT NULL, + matched_access_point_count INTEGER NOT NULL, + handshake_count INTEGER NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + CHECK (matched_access_point_count >= 0), + CHECK (handshake_count >= 0), + CHECK (expires_at > created_at) +); + +CREATE TABLE IF NOT EXISTS crack_search_context_handshakes ( + token_hash TEXT NOT NULL, + handshake_id INTEGER NOT NULL, + PRIMARY KEY (token_hash, handshake_id), + FOREIGN KEY (token_hash) + REFERENCES crack_search_contexts(token_hash) + ON DELETE CASCADE, + FOREIGN KEY (handshake_id) + REFERENCES handshakes(id) + ON DELETE CASCADE +); + +CREATE INDEX IF NOT EXISTS idx_crack_search_contexts_expires +ON crack_search_contexts(expires_at); + +CREATE INDEX IF NOT EXISTS idx_crack_search_context_handshakes_handshake +ON crack_search_context_handshakes(handshake_id); diff --git a/cracklab/server/repositories/search_contexts.py b/cracklab/server/repositories/search_contexts.py new file mode 100644 index 0000000..38ecf5c --- /dev/null +++ b/cracklab/server/repositories/search_contexts.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import sqlite3 +from typing import Any + + +class SearchContextsRepository: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + + def create_context( + self, + token_hash: str, + criteria_json: str, + matched_access_point_count: int, + handshake_count: int, + created_at: str, + expires_at: str, + ) -> None: + self._conn.execute( + """ + INSERT INTO crack_search_contexts ( + token_hash, + criteria_json, + matched_access_point_count, + handshake_count, + created_at, + expires_at + ) + VALUES (?, ?, ?, ?, ?, ?) + """, + ( + token_hash, + criteria_json, + matched_access_point_count, + handshake_count, + created_at, + expires_at, + ), + ) + + def add_handshakes( + self, + token_hash: str, + handshake_ids: list[int], + ) -> None: + self._conn.executemany( + """ + INSERT INTO crack_search_context_handshakes ( + token_hash, + handshake_id + ) + VALUES (?, ?) + """, + [ + (token_hash, handshake_id) + for handshake_id in handshake_ids + ], + ) + + def get_context( + self, + token_hash: str, + ) -> sqlite3.Row | None: + return self._conn.execute( + """ + SELECT + id, + token_hash, + criteria_json, + matched_access_point_count, + handshake_count, + created_at, + expires_at + FROM crack_search_contexts + WHERE token_hash = ? + """, + (token_hash,), + ).fetchone() + + def list_handshake_ids( + self, + token_hash: str, + ) -> list[int]: + rows = self._conn.execute( + """ + SELECT handshake_id + FROM crack_search_context_handshakes + WHERE token_hash = ? + ORDER BY handshake_id + """, + (token_hash,), + ).fetchall() + + return [ + int(row["handshake_id"]) + for row in rows + ] + + def delete_expired( + self, + now: str, + ) -> int: + cursor = self._conn.execute( + """ + DELETE FROM crack_search_contexts + WHERE expires_at <= ? + """, + (now,), + ) + + return cursor.rowcount diff --git a/cracklab/server/services/__init__.py b/cracklab/server/services/__init__.py index b97ba3b..338cb30 100644 --- a/cracklab/server/services/__init__.py +++ b/cracklab/server/services/__init__.py @@ -1,6 +1,7 @@ from .job_issuance import JobIssuanceService, IssuedJob from .job_result import JobResultError, JobResultService from .methods import MethodService, MethodServiceError +from .search_context import SearchContextError, SearchContextService __all__ = [ "IssuedJob", @@ -9,4 +10,6 @@ __all__ = [ "JobResultService", "MethodService", "MethodServiceError", + "SearchContextError", + "SearchContextService", ] diff --git a/cracklab/server/services/search_context.py b/cracklab/server/services/search_context.py new file mode 100644 index 0000000..c997417 --- /dev/null +++ b/cracklab/server/services/search_context.py @@ -0,0 +1,212 @@ +from __future__ import annotations + +import hashlib +import json +import secrets +import sqlite3 + +from datetime import datetime, timedelta, timezone +from typing import Any + +from cracklab.server.repositories.search_contexts import ( + SearchContextsRepository, +) + + +SEARCH_CONTEXT_TTL = timedelta(hours=2) + + +class SearchContextError(ValueError): + pass + + +class SearchContextService: + def __init__(self, conn: sqlite3.Connection) -> None: + self._conn = conn + self._repository = SearchContextsRepository(conn) + + @staticmethod + def _utc_now() -> datetime: + return datetime.now(timezone.utc) + + @staticmethod + def _format_datetime(value: datetime) -> str: + return value.isoformat( + timespec="seconds", + ).replace("+00:00", "Z") + + @staticmethod + def _token_hash(token: str) -> str: + return hashlib.sha256( + token.encode("utf-8"), + ).hexdigest() + + @staticmethod + def _normalize_handshake_ids( + handshake_ids: list[int] | tuple[int, ...], + ) -> list[int]: + if not isinstance(handshake_ids, (list, tuple)): + raise SearchContextError( + "Invalid handshake ID collection." + ) + + normalized: set[int] = set() + + for handshake_id in handshake_ids: + if ( + isinstance(handshake_id, bool) + or not isinstance(handshake_id, int) + or handshake_id <= 0 + ): + raise SearchContextError( + "Invalid handshake ID." + ) + + normalized.add(handshake_id) + + return sorted(normalized) + + def create_context( + self, + criteria: dict[str, Any], + handshake_ids: list[int] | tuple[int, ...], + matched_access_point_count: int, + ) -> dict[str, Any]: + if not isinstance(criteria, dict) or not criteria: + raise SearchContextError( + "Search criteria are required." + ) + + if ( + isinstance(matched_access_point_count, bool) + or not isinstance(matched_access_point_count, int) + or matched_access_point_count < 0 + ): + raise SearchContextError( + "Invalid matched access point count." + ) + + normalized_ids = self._normalize_handshake_ids( + handshake_ids, + ) + + try: + criteria_json = json.dumps( + criteria, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ) + except (TypeError, ValueError) as exc: + raise SearchContextError( + "Search criteria cannot be serialized." + ) from exc + + token = secrets.token_urlsafe(32) + token_hash = self._token_hash(token) + + now = self._utc_now() + created_at = self._format_datetime(now) + expires_at = self._format_datetime( + now + SEARCH_CONTEXT_TTL, + ) + + self._conn.execute("BEGIN IMMEDIATE") + + try: + self._repository.create_context( + token_hash=token_hash, + criteria_json=criteria_json, + matched_access_point_count=( + matched_access_point_count + ), + handshake_count=len(normalized_ids), + created_at=created_at, + expires_at=expires_at, + ) + + self._repository.add_handshakes( + token_hash, + normalized_ids, + ) + + self._conn.commit() + + except Exception: + self._conn.rollback() + raise + + return { + "token": token, + "created_at": created_at, + "expires_at": expires_at, + "matched_access_point_count": ( + matched_access_point_count + ), + "handshake_count": len(normalized_ids), + } + + def get_context( + self, + token: str, + ) -> dict[str, Any] | None: + if not isinstance(token, str) or not token: + return None + + token_hash = self._token_hash(token) + + row = self._repository.get_context( + token_hash, + ) + + if row is None: + return None + + now = self._format_datetime( + self._utc_now(), + ) + + return { + "id": int(row["id"]), + "token_hash": row["token_hash"], + "criteria": json.loads(row["criteria_json"]), + "matched_access_point_count": int( + row["matched_access_point_count"] + ), + "handshake_count": int(row["handshake_count"]), + "created_at": row["created_at"], + "expires_at": row["expires_at"], + "expired": row["expires_at"] <= now, + } + + def list_handshake_ids( + self, + token: str, + ) -> list[int]: + if not isinstance(token, str) or not token: + raise SearchContextError( + "Invalid search context token." + ) + + return self._repository.list_handshake_ids( + self._token_hash(token), + ) + + def delete_expired(self) -> int: + now = self._format_datetime( + self._utc_now(), + ) + + self._conn.execute("BEGIN IMMEDIATE") + + try: + deleted = self._repository.delete_expired( + now, + ) + self._conn.commit() + + except Exception: + self._conn.rollback() + raise + + return deleted