From 08ed9fc37715f4206fa26c222e3a5cc24b7a5ccf Mon Sep 17 00:00:00 2001 From: noiemany <51255434+compnew2006@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:19:09 +0200 Subject: [PATCH 1/5] fix(waf): bound request body inspection while streaming --- Structure_README.md | 11 +++++ api/app.py | 104 +++++++++++++++++++++++++---------------- api/waf.py | 40 ++++++++++++++++ core/config.py | 5 +- tests/test_security.py | 87 ++++++++++++++++++++++++++++++++-- 5 files changed, 202 insertions(+), 45 deletions(-) diff --git a/Structure_README.md b/Structure_README.md index 831b9f0..68bcad1 100644 --- a/Structure_README.md +++ b/Structure_README.md @@ -777,6 +777,17 @@ drops internet briefly) re-dials on its own. Both only run while ppp0 is actually **up** (a dead dial has nothing to renew into), and the last-renewed timestamp is persisted so a gateway restart never re-renews mid-schedule. +### Request body inspection by the WAF + +`waf.max_body_bytes` (default 1 MiB) limits the bytes buffered to inspect +`POST`, `PUT`, `PATCH`, and `DELETE` bodies. The WAF checks the actual byte +count while reading, even when the client omits `Content-Length`. Strict mode +returns HTTP 413 for an oversized body before the route runs. Log mode records +the event and forwards the entire stream, including the bytes read before +the limit was reached, without auto-banning the client. The local-subnet exemption and WAF off mode +bypass inspection. Routes that accept large inputs still need their own limits +when WAF blocking is disabled or exempted. + ### Tailscale remote access `quota/tailscale.py` (`TailscaleManager`) manages the official `tailscale` diff --git a/api/app.py b/api/app.py index 4c23549..c3b3720 100644 --- a/api/app.py +++ b/api/app.py @@ -37,6 +37,8 @@ PlainTextResponse, RedirectResponse, StreamingResponse) from fastapi.staticfiles import StaticFiles +from starlette.datastructures import MutableHeaders +from starlette.types import ASGIApp, Message, Receive, Scope, Send from contextlib import asynccontextmanager from api.schemas import (BundleUpdate, ConsumptionSpoofRequest, DeviceCreate, @@ -4349,18 +4351,35 @@ def _waf_mode() -> str: if holder else "lan" return _waf.resolve_mode(getattr(waf_cfg, "mode", "auto"), topology) - @app.middleware("http") - async def _security_middleware(request: Request, - call_next) -> Response: - """WAF inspection + CSRF custom-header guard + security headers. + def _security_middleware(app: ASGIApp) -> ASGIApp: + async def dispatch(scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await app(scope, receive, send) + return + + body = _waf.InspectionBody(receive) + request = Request(scope, receive=body.receive) + response = await _security_response(request, body) + if response is not None: + await response(scope, body.receive, send) + return + + async def send_with_security_headers(message: Message) -> None: + if message["type"] == "http.response.start": + _stamp_security_headers(request.url.path, MutableHeaders(scope=message)) + await send(message) - Order: WAF first (reject the request before any handler runs), then - CSRF (a session-bearing cross-site mutation must carry ``X-QM-CSRF``), - then the response is stamped with the security headers. A WAF crash + await app(scope, body.receive, send_with_security_headers) + return dispatch + + async def _security_response(request: Request, + body: _waf.InspectionBody) -> Response | None: + """Return an early response for captive guests, WAF, or CSRF checks. + + WAF runs before CSRF and can reject the request before the handler. A WAF crash fails CLOSED in strict mode (503) — the dashboard becomes unreachable rather than silently unprotected — and OPEN (pass + log) in log mode. """ - response: Response | None = None try: # Captive portal redirection for pending guests host = request.client.host if request.client else "" @@ -4385,7 +4404,7 @@ async def _security_middleware(request: Request, waf_mode = _waf_mode() if waf_mode != "off": - blocked = await _waf_inspect(request, waf_mode) + blocked = await _waf_inspect(request, body, waf_mode) if blocked is not None: return blocked # CSRF: a state-changing request carrying a valid session cookie @@ -4412,11 +4431,9 @@ async def _security_middleware(request: Request, return JSONResponse( {"detail": "security layer unavailable"}, status_code=503) - response = await call_next(request) - _stamp_security_headers(request.url.path, response) - return response + return None - async def _waf_inspect(request: Request, + async def _waf_inspect(request: Request, body: _waf.InspectionBody, waf_mode: str) -> Response | None: """Run the WAF checks; return a Response to short-circuit, else None.""" host = request.client.host if request.client else "" @@ -4432,10 +4449,15 @@ async def _waf_inspect(request: Request, return None # -- cheap whole-request caps (before touching the body) -------------- + max_body_bytes = getattr(cfg, "max_body_bytes", 1_048_576) cl = request.headers.get("content-length", "") - if cl.isdigit() and int(cl) > getattr(cfg, "max_body_bytes", 1_048_576): - return await _waf_block(request, host, now, waf_mode, - "oversized-body", "request-size", cl) + if cl.isascii() and cl.isdecimal(): + # Compare decimal strings so even a long header needs no bigint. + declared = cl.lstrip("0") or "0" + cap = str(max_body_bytes) + if (len(declared), declared) > (len(cap), cap): + return await _waf_block(request, host, now, waf_mode, + "oversized-body", "request-size", "", status_code=413) if len(request.headers) > getattr(cfg, "max_headers", 40): return await _waf_block(request, host, now, waf_mode, "too-many-headers", "request-size", "") @@ -4447,11 +4469,10 @@ async def _waf_inspect(request: Request, # -- signatures over path / query / body ------------------------------ body_text = "" if request.method in ("POST", "PUT", "PATCH", "DELETE"): - try: - raw = await request.body() - except Exception: # noqa: BLE001 - raw = b"" - body_text = raw.decode("utf-8", "replace") + body_text = await body.inspect(max_body_bytes) + if body_text is None: + return await _waf_block(request, host, now, waf_mode, + "oversized-body", "request-size", "", status_code=413) rule = _waf.classify( request.method, request.url.path, request.url.query, body_text, dict(request.headers)) @@ -4479,7 +4500,7 @@ async def _waf_inspect(request: Request, async def _waf_block(request: Request, host: str, now: float, waf_mode: str, category: str, rule_id: str, - extra: str) -> Response | None: + extra: str, *, status_code: int = 403) -> Response | None: """Log a WAF hit, feed the auto-ban, and (in strict mode) reject.""" where = f"{request.url.path}" + (f"?{extra}" if extra else "") message = (f"WAF {category} ({rule_id}) from {host} " @@ -4493,6 +4514,9 @@ async def _waf_block(request: Request, host: str, now: float, await database.add_event(message, "warn") except Exception: # noqa: BLE001 pass + if waf_mode != "strict": + return None # Log-only hits never feed the firewall auto-ban. + waf_state.register_block(host, now) auto_after = int(getattr(waf_cfg, "auto_ban_after", 8) or 0) if auto_after and firewall is not None and \ @@ -4504,19 +4528,17 @@ async def _waf_block(request: Request, host: str, now: float, await firewall.ban_ip(host, seconds, "waf") except Exception: # noqa: BLE001 log.exception("waf auto-ban failed") - if waf_mode == "strict": - return JSONResponse( - {"detail": f"blocked by WAF ({category})"}, - status_code=403) - return None # log-only (LAN): record + pass through - - def _stamp_security_headers(path: str, response: Response) -> None: - response.headers.setdefault("X-Content-Type-Options", "nosniff") - response.headers.setdefault("X-Frame-Options", "DENY") - response.headers.setdefault("Referrer-Policy", "no-referrer") + return JSONResponse( + {"detail": f"blocked by WAF ({category})"}, + status_code=status_code) + + def _stamp_security_headers(path: str, headers: MutableHeaders) -> None: + headers.setdefault("X-Content-Type-Options", "nosniff") + headers.setdefault("X-Frame-Options", "DENY") + headers.setdefault("Referrer-Policy", "no-referrer") # If the dashboard ever sits on a public address, search engines must # never index the admin UI (robots.txt + this header both say so). - response.headers.setdefault("X-Robots-Tag", "noindex, nofollow") + headers.setdefault("X-Robots-Tag", "noindex, nofollow") # Sensitive-data protection (anti-replay / anti-cache): every DATA # response (API + the HTML pages) is marked no-store so the browser # never writes the payloads — MACs, usage, history, events, log lines — @@ -4526,31 +4548,33 @@ def _stamp_security_headers(path: str, response: Response) -> None: # Without a header browsers cache them heuristically for days, so after an # update the dashboard kept running the OLD app.js against the NEW API. if path.startswith(("/assets/", "/js/", "/css/", "/fonts/")) or path == "/logo.svg": - response.headers.setdefault("Cache-Control", "no-cache") + headers.setdefault("Cache-Control", "no-cache") if path.startswith(("/api", "/report", "/milestone", "/share", "/guest-pending", "/guest/pending", "/spoof")) or path == "/": - response.headers.setdefault("Cache-Control", - "no-store, no-cache, must-revalidate, max-age=0") - response.headers.setdefault("Pragma", "no-cache") - response.headers.setdefault("Expires", "0") + headers.setdefault("Cache-Control", + "no-store, no-cache, must-revalidate, max-age=0") + headers.setdefault("Pragma", "no-cache") + headers.setdefault("Expires", "0") # Strict CSP for the dashboard + API. /report, /milestone, /share, the guest # portal and the calibration page carry inline scripts, so they get the # looser (still-useful) profile (a strict script-src blocked the guest # page's status polling and its "Check now" button). if path.startswith(("/report", "/milestone", "/share", "/guest/pending", "/spoof")): - response.headers.setdefault( + headers.setdefault( "Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; " "img-src 'self' data: blob:; connect-src 'self' ws: wss:; " "script-src 'self' 'unsafe-inline'; base-uri 'self'; " "frame-ancestors 'none'; form-action 'self'") else: - response.headers.setdefault( + headers.setdefault( "Content-Security-Policy", "default-src 'self'; script-src 'self'; " "style-src 'self' 'unsafe-inline'; img-src 'self' data:; " "connect-src 'self' ws: wss:; font-src 'self'; " "base-uri 'self'; frame-ancestors 'none'; form-action 'self'") + app.add_middleware(_security_middleware) + # The dashboard used to live under /ui/ while the classic one sat at "/". # Old bookmarks and any cached page still point there: send them to the same # file at the root (so /ui/ -> /, /ui/js/main.js -> /js/main.js). diff --git a/api/waf.py b/api/waf.py index dea0eca..5d6efca 100644 --- a/api/waf.py +++ b/api/waf.py @@ -28,6 +28,46 @@ import ipaddress import re +from starlette.types import Message, Receive + + +class InspectionBody: + """Buffer a bounded HTTP body for inspection, then replay the same bytes.""" + + def __init__(self, receive: Receive) -> None: + self._receive = receive + self._prefix: bytearray | None = None + self._more_body = True + self._pending: Message | None = None + + async def inspect(self, limit: int) -> str | None: + """Return decoded text, or None at the first chunk that exceeds the cap.""" + prefix = self._prefix = bytearray() + while self._more_body: + message = await self._receive() + if message["type"] == "http.disconnect": + self._pending = message + return "" + chunk = message.get("body", b"") + if len(chunk) > limit - len(prefix): + # Log mode still needs to pass this event on. Keep the original + # message without copying its bytes into the inspection buffer. + self._pending = message + return None + prefix.extend(chunk) + self._more_body = message.get("more_body", False) + return prefix.decode("utf-8", "replace") + + async def receive(self) -> Message: + if self._prefix is not None: + prefix, self._prefix = self._prefix, None + return {"type": "http.request", "body": bytes(prefix), "more_body": self._more_body} + if self._pending is not None: + message, self._pending = self._pending, None + return message + return await self._receive() + + #: HTTP verbs the dashboard actually uses; everything else is rejected #: outright (TRACE/CONNECT and unused verbs are attack surface, not features). ALLOWED_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", diff --git a/core/config.py b/core/config.py index e58d080..3854801 100644 --- a/core/config.py +++ b/core/config.py @@ -556,14 +556,15 @@ class WafConfig: enabled: bool = True #: "auto" | "strict" | "log" | "off" ("auto" = strict on WAN, log on LAN). mode: str = "auto" - #: Body size cap (bytes) — larger requests are 413'd before parsing. + #: WAF inspection cap in bytes. Strict mode returns 413 on overflow; + #: log mode records the overflow and passes the original stream through. max_body_bytes: int = 1_048_576 #: Max request header count and per-header bytes (431 on overflow). max_headers: int = 40 max_header_bytes: int = 8_192 #: "closed" (unreachable rather than unprotected) | "open" (pass through). fail_mode: str = "closed" - #: WAF hits from one source within ``ban_window_seconds`` that trigger an + #: Strict-mode WAF hits within ``ban_window_seconds`` that trigger an #: automatic firewall IP ban (``0`` disables the auto-ban). auto_ban_after: int = 8 ban_seconds: int = 1800 diff --git a/tests/test_security.py b/tests/test_security.py index 7b96634..c3e68ee 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -5,6 +5,7 @@ import asyncio import time +import httpx import pytest # import asyncio _cached_loop = None @@ -49,8 +50,8 @@ async def _init(): _get_loop().run_until_complete(_init()) - def _make(waf_config=None, web_config=None): - return create_app(database, service, holder, + def _make(waf_config=None, web_config=None, firewall=None): + return create_app(database, service, holder, firewall=firewall, waf_config=waf_config, web_config=web_config) yield _make, database, service, holder @@ -464,10 +465,90 @@ def test_waf_oversized_body_blocks(app_factory): c2.post("/api/login", json={"password": "admin"}) r = c2.post("/api/bundle", json={"total_gb": 1, "padding": "x" * 100}) - assert r.status_code == 403 + assert r.status_code == 413 assert "oversized-body" in str(r.json()) +async def _submit_streamed_login(app, chunks, handed_off): + async def body(): + for chunk in chunks: + handed_off.append(chunk) + yield chunk + + transport = httpx.ASGITransport(app=app, client=("192.0.2.10", 50000)) + async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client: + request = client.build_request( + "POST", "/api/login", content=body(), headers={"Content-Type": "application/json"}, + ) + assert "content-length" not in request.headers + return await client.send(request) + + +def test_waf_stops_reading_as_soon_as_body_limit_is_crossed(app_factory): + make, database, _, _ = app_factory + app = make(WafConfig(mode="strict", max_body_bytes=10, local_subnets=[])) + chunks = [b'{"pass', b'word":', b'"admin"}'] + handed_off = [] + + response = _get_loop().run_until_complete(_submit_streamed_login(app, chunks, handed_off)) + + assert response.status_code == 413 + assert "oversized-body" in response.json()["detail"] + assert handed_off == chunks[:2] + assert not _get_loop().run_until_complete(database.get_setting("session_token")) + + +@pytest.mark.parametrize("mode,exempt", [("log", False), ("off", False), ("strict", True)]) +def test_waf_preserves_body_and_forwarding_in_nonblocking_modes(app_factory, mode, exempt): + make, database, _, _ = app_factory + app = make(WafConfig( + mode=mode, max_body_bytes=10, + local_subnets=["192.0.2.0/24"] if exempt else [], + )) + chunks = [b'{"pass', b'word":', b'"admin"}'] + handed_off = [] + + response = _get_loop().run_until_complete(_submit_streamed_login(app, chunks, handed_off)) + + assert response.status_code == 200 + assert handed_off == chunks + events = _get_loop().run_until_complete(database.list_events()) + assert any("WAF oversized-body" in e["message"] for e in events) == (mode == "log") + + +@pytest.mark.parametrize("mode,status,expected_bans", [("strict", 413, 1), ("log", 200, 0)]) +def test_waf_body_limit_only_auto_bans_in_strict_mode(app_factory, mode, status, expected_bans): + make, _, _, _ = app_factory + banned = [] + + class FirewallRecorder: + async def ban_ip(self, host, seconds, reason): + banned.append(host) + + app = make( + WafConfig(mode=mode, max_body_bytes=10, local_subnets=[], auto_ban_after=1), + firewall=FirewallRecorder(), + ) + response = _get_loop().run_until_complete( + _submit_streamed_login(app, [b'{"pass', b'word":', b'"admin"}'], []), + ) + + assert response.status_code == status + assert len(banned) == expected_bans + + +def test_waf_accepts_stream_at_exact_limit_and_replays_it(app_factory): + make, _, _, _ = app_factory + app = make(WafConfig(mode="strict", max_body_bytes=20, local_subnets=[])) + chunks = [b'{"pass', b'word":', b'"admin"}'] + + response = _get_loop().run_until_complete(_submit_streamed_login(app, chunks, [])) + + assert response.status_code == 200 + assert response.headers["X-Content-Type-Options"] == "nosniff" + assert "no-store" in response.headers["Cache-Control"] + + def test_waf_endpoint_rate_limit_strict(app_factory): make, _, _, holder = app_factory holder.swap(EngineSnapshot(wan_status={"topology": "wan"})) From c78ab40850835f0799922472d7c3f36778da0556 Mon Sep 17 00:00:00 2001 From: noiemany <51255434+compnew2006@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:31:10 +0200 Subject: [PATCH 2/5] fix(waf): bound and expire rate limiter state --- Structure_README.md | 11 ++++++ api/app.py | 65 +++++++++++++++++--------------- api/waf.py | 84 +++++++++++++++++++++++++++++++----------- tests/test_security.py | 70 +++++++++++++++++++++++++++++++++++ 4 files changed, 179 insertions(+), 51 deletions(-) diff --git a/Structure_README.md b/Structure_README.md index 68bcad1..7ea772a 100644 --- a/Structure_README.md +++ b/Structure_README.md @@ -788,6 +788,17 @@ the limit was reached, without auto-banning the client. The local-subnet exempti bypass inspection. Routes that accept large inputs still need their own limits when WAF blocking is disabled or exempted. +In strict mode, the WAF keeps at most 4,096 active source/endpoint rate buckets +and 4,096 source histories for auto-ban. Rate buckets expire after each +endpoint's configured window. Auto-ban holds only the most recent +`waf.auto_ban_after` timestamps per source and drops hits outside +`waf.ban_window_seconds`. A five-second sweep removes expired state even +without incoming requests. When the rate table is full, an untracked source +on a rate-limited route receives 429 until a slot frees up. A full auto-ban +table keeps its active histories. New sources are still blocked for WAF +violations, but their hits do not accumulate toward a firewall ban until +space becomes available. + ### Tailscale remote access `quota/tailscale.py` (`TailscaleManager`) manages the official `tailscale` diff --git a/api/app.py b/api/app.py index c3b3720..71bd7c5 100644 --- a/api/app.py +++ b/api/app.py @@ -4258,6 +4258,11 @@ async def _push_loop() -> None: except Exception: # noqa: BLE001 active_ws.discard(ws) + async def _expire_waf_state() -> None: + while True: + await asyncio.sleep(_waf.RATE_STATE_SWEEP_SECONDS) + waf_state.expire(time.monotonic()) + @asynccontextmanager async def _lifespan(_app: FastAPI): # startup @@ -4306,6 +4311,7 @@ async def _disk_heal_loop(): disk_restore_task = asyncio.get_running_loop().create_task(_restore_disk_shares()) disk_heal_task = asyncio.get_running_loop().create_task(_disk_heal_loop()) + waf_expiry_task = asyncio.create_task(_expire_waf_state()) try: yield finally: @@ -4314,6 +4320,8 @@ async def _disk_heal_loop(): share_cleanup_task.cancel() disk_restore_task.cancel() disk_heal_task.cancel() + waf_expiry_task.cancel() + await asyncio.gather(waf_expiry_task, return_exceptions=True) try: await push_task except (asyncio.CancelledError, Exception): @@ -4342,7 +4350,10 @@ async def _disk_heal_loop(): # (blocking) on WAN, log-only on LAN; fail-closed on WAN if the layer # itself errors. - waf_state = _waf.WafRateState() + waf_state = _waf.WafRateState( + ban_threshold=int(getattr(waf_cfg, "auto_ban_after", 8) or 0), + ban_window_seconds=float(getattr(waf_cfg, "ban_window_seconds", 300) or 300), + ) def _waf_mode() -> str: if not getattr(waf_cfg, "enabled", True): @@ -4437,7 +4448,6 @@ async def _waf_inspect(request: Request, body: _waf.InspectionBody, waf_mode: str) -> Response | None: """Run the WAF checks; return a Response to short-circuit, else None.""" host = request.client.host if request.client else "" - now = time.monotonic() cfg = waf_cfg # -- local-management exemption ------------------------------------ @@ -4456,14 +4466,14 @@ async def _waf_inspect(request: Request, body: _waf.InspectionBody, declared = cl.lstrip("0") or "0" cap = str(max_body_bytes) if (len(declared), declared) > (len(cap), cap): - return await _waf_block(request, host, now, waf_mode, + return await _waf_block(request, host, waf_mode, "oversized-body", "request-size", "", status_code=413) if len(request.headers) > getattr(cfg, "max_headers", 40): - return await _waf_block(request, host, now, waf_mode, + return await _waf_block(request, host, waf_mode, "too-many-headers", "request-size", "") for key, value in request.headers.items(): if len(value) > getattr(cfg, "max_header_bytes", 8192): - return await _waf_block(request, host, now, waf_mode, + return await _waf_block(request, host, waf_mode, "oversized-header", "request-size", key) # -- signatures over path / query / body ------------------------------ @@ -4471,7 +4481,7 @@ async def _waf_inspect(request: Request, body: _waf.InspectionBody, if request.method in ("POST", "PUT", "PATCH", "DELETE"): body_text = await body.inspect(max_body_bytes) if body_text is None: - return await _waf_block(request, host, now, waf_mode, + return await _waf_block(request, host, waf_mode, "oversized-body", "request-size", "", status_code=413) rule = _waf.classify( request.method, request.url.path, request.url.query, @@ -4479,28 +4489,27 @@ async def _waf_inspect(request: Request, body: _waf.InspectionBody, if rule is not None and not _waf.is_exempt( getattr(cfg, "exceptions", []), rule[0], request.url.path, host): - return await _waf_block(request, host, now, waf_mode, + return await _waf_block(request, host, waf_mode, rule[1], rule[0], "") # -- scanner User-Agent ----------------------------------------------- if _waf.classify_ua(request.headers.get("user-agent", "")): - return await _waf_block(request, host, now, waf_mode, + return await _waf_block(request, host, waf_mode, "scanner-ua", "scanner", "") - # -- per-endpoint request-rate cap (strict only; logged otherwise) ---- + # -- per-endpoint request-rate cap (strict only) ----------------------- limits = getattr(cfg, "endpoint_limits", {}) or {} - if limits and waf_state.rate_limited(host, request.url.path, - limits, now): - if waf_mode == "strict": - return JSONResponse( - {"detail": "request rate limit exceeded"}, - status_code=429, - headers={"Retry-After": "30"}) + if waf_mode == "strict" and limits and waf_state.rate_limited( + host, request.url.path, limits, time.monotonic()): + return JSONResponse( + {"detail": "request rate limit exceeded"}, + status_code=429, + headers={"Retry-After": "30"}) return None - async def _waf_block(request: Request, host: str, now: float, - waf_mode: str, category: str, rule_id: str, - extra: str, *, status_code: int = 403) -> Response | None: + async def _waf_block(request: Request, host: str, waf_mode: str, + category: str, rule_id: str, extra: str, + *, status_code: int = 403) -> Response | None: """Log a WAF hit, feed the auto-ban, and (in strict mode) reject.""" where = f"{request.url.path}" + (f"?{extra}" if extra else "") message = (f"WAF {category} ({rule_id}) from {host} " @@ -4517,17 +4526,13 @@ async def _waf_block(request: Request, host: str, now: float, if waf_mode != "strict": return None # Log-only hits never feed the firewall auto-ban. - waf_state.register_block(host, now) - auto_after = int(getattr(waf_cfg, "auto_ban_after", 8) or 0) - if auto_after and firewall is not None and \ - hasattr(firewall, "ban_ip"): - window = float(getattr(waf_cfg, "ban_window_seconds", 300) or 300) - if waf_state.blocks_in_window(host, window, now) >= auto_after: - seconds = int(getattr(waf_cfg, "ban_seconds", 1800) or 1800) - try: - await firewall.ban_ip(host, seconds, "waf") - except Exception: # noqa: BLE001 - log.exception("waf auto-ban failed") + if (firewall is not None and hasattr(firewall, "ban_ip") + and waf_state.register_block(host, time.monotonic())): + seconds = int(getattr(waf_cfg, "ban_seconds", 1800) or 1800) + try: + await firewall.ban_ip(host, seconds, "waf") + except Exception: # noqa: BLE001 + log.exception("waf auto-ban failed") return JSONResponse( {"detail": f"blocked by WAF ({category})"}, status_code=status_code) diff --git a/api/waf.py b/api/waf.py index 5d6efca..1ed0435 100644 --- a/api/waf.py +++ b/api/waf.py @@ -27,6 +27,7 @@ import ipaddress import re +from collections import deque from starlette.types import Message, Receive @@ -210,35 +211,76 @@ def is_exempt(exceptions: list[dict], rule_id: str, path: str, return False +RATE_STATE_SWEEP_SECONDS = 5 + + class WafRateState: - """Per-source-IP request buckets + auto-ban hit counters (in-memory).""" + """Bounded endpoint buckets and rolling auto-ban history.""" - def __init__(self) -> None: - self._hits: dict[str, list[float]] = {} # ip -> WAF-block timestamps + def __init__(self, *, max_entries: int = 4096, ban_threshold: int = 8, + ban_window_seconds: float = 300) -> None: + self._max_entries = max_entries + self._ban_threshold = ban_threshold + self._ban_window = ban_window_seconds self._buckets: dict[tuple[str, str], tuple[int, float]] = {} - # (ip, path-prefix) -> (count, window_start) + self._hits: dict[str, deque[float]] = {} + self._next_sweep = 0.0 + + def expire(self, now: float) -> None: + """Remove expired entries even when their source never returns.""" + self._next_sweep = now + RATE_STATE_SWEEP_SECONDS + for key, (_, deadline) in list(self._buckets.items()): + if now > deadline: + del self._buckets[key] + for ip, stamps in list(self._hits.items()): + self._expire_hits(stamps, now) + if not stamps: + del self._hits[ip] + + def _expire_if_due(self, now: float) -> None: + if now >= self._next_sweep: + self.expire(now) def rate_limited(self, ip: str, path: str, limits: dict[str, list[int]], now: float) -> bool: - """True when ``ip`` exceeded the per-path cap for ``path``.""" + """Check the per-path cap without displacing an active bucket.""" prefix = next((p for p in limits if path.startswith(p)), None) - if not prefix: + if prefix is None: return False + self._expire_if_due(now) max_reqs, window = limits[prefix] + if max_reqs <= 0: + return True key = (ip, prefix) - count, start = self._buckets.get(key, (0, now)) - if now - start > window: - count, start = 0, now - count += 1 - self._buckets[key] = (count, start) - return count > max_reqs - - def register_block(self, ip: str, now: float) -> None: - """Record a WAF block for ``ip`` (feeds the auto-ban counter).""" - stamps = self._hits.setdefault(ip, []) - stamps.append(now) + bucket = self._buckets.get(key) + if bucket is not None and now <= bucket[1]: + count, deadline = bucket + if count >= max_reqs: + return True + self._buckets[key] = (count + 1, deadline) + else: + if bucket is None and len(self._buckets) >= self._max_entries: + return True + self._buckets[key] = (1, now + window) + return False + + def _expire_hits(self, stamps: deque[float], now: float) -> None: + cutoff = now - self._ban_window + while stamps and stamps[0] < cutoff: + stamps.popleft() - def blocks_in_window(self, ip: str, window: float, now: float) -> int: - stamps = [t for t in self._hits.get(ip, []) if now - t <= window] - self._hits[ip] = stamps - return len(stamps) \ No newline at end of file + def register_block(self, ip: str, now: float) -> bool: + """Record a block and report whether this IP has met the ban threshold.""" + if self._ban_threshold <= 0: + return False + self._expire_if_due(now) + stamps = self._hits.get(ip) + if stamps is None: + if len(self._hits) >= self._max_entries: + # The request is still blocked by the WAF. Keep the existing + # histories so a new source can't erase another source's hits. + return False + stamps = self._hits[ip] = deque(maxlen=self._ban_threshold) + self._expire_hits(stamps, now) + stamps.append(now) + return len(stamps) >= self._ban_threshold diff --git a/tests/test_security.py b/tests/test_security.py index c3e68ee..f31793f 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -411,6 +411,76 @@ def test_waf_rate_state_window(): assert state.rate_limited("5.6.7.8", "/api/login", limits, t) is False +def test_waf_discards_expired_state_for_clients_that_do_not_return(): + state = _waf.WafRateState() + limits = {"/api/login": [1, 60]} + state.rate_limited("192.0.2.1", "/api/login", limits, 100) + state.register_block("192.0.2.1", 100) + + assert not state.rate_limited("192.0.2.2", "/api/login", limits, 406) + + assert set(state._buckets) == {("192.0.2.2", "/api/login")} + assert not state._hits + + +def test_waf_holds_only_the_hits_needed_to_reach_ban_threshold(): + state = _waf.WafRateState() + + for timestamp in range(100, 120): + state.register_block("192.0.2.1", timestamp) + + assert len(state._hits["192.0.2.1"]) == 8 + + +def test_waf_full_rate_table_preserves_active_limits_and_recovers(): + state = _waf.WafRateState(max_entries=2) + limits = {"/api/login": [1, 60], "/api/report": [2, 30]} + assert not state.rate_limited("192.0.2.1", "/api/login", limits, 100) + assert not state.rate_limited("192.0.2.1", "/api/report", limits, 100) + + assert state.rate_limited("192.0.2.2", "/api/login", limits, 101) + assert state.rate_limited("192.0.2.1", "/api/login", limits, 101) + assert not state.rate_limited("192.0.2.2", "/unlimited", limits, 101) + assert len(state._buckets) == 2 + + # The shorter window frees a slot while the original login is still capped. + assert not state.rate_limited("192.0.2.2", "/api/login", limits, 132) + assert state.rate_limited("192.0.2.1", "/api/login", limits, 132) + + +def test_waf_hit_table_stays_bounded_and_known_clients_can_reach_threshold(): + state = _waf.WafRateState(max_entries=1, ban_threshold=2, ban_window_seconds=10) + assert not state.register_block("192.0.2.1", 100) + + assert not state.register_block("192.0.2.2", 101) + assert state.register_block("192.0.2.1", 102) + assert set(state._hits) == {"192.0.2.1"} + + assert not state.register_block("192.0.2.2", 113) + assert state.register_block("192.0.2.2", 114) + assert set(state._hits) == {"192.0.2.2"} + + +def test_waf_ban_counter_ignores_hits_outside_its_window(): + state = _waf.WafRateState(ban_threshold=2, ban_window_seconds=10) + assert not state.register_block("192.0.2.1", 100) + + assert not state.register_block("192.0.2.1", 111) + assert state.register_block("192.0.2.1", 112) + + +def test_waf_expiry_frees_state_even_when_there_are_no_new_requests(): + state = _waf.WafRateState(ban_threshold=2, ban_window_seconds=5) + limits = {"/api/login": [1, 5]} + state.rate_limited("192.0.2.1", "/api/login", limits, 100) + state.register_block("192.0.2.1", 100) + + state.expire(106) + + assert not state._buckets + assert not state._hits + + # -- WAF middleware behaviour --------------------------------------------------- From 7e11660d96ea1bf41c31b510313f928929ba8141 Mon Sep 17 00:00:00 2001 From: noiemany <51255434+compnew2006@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:07:21 +0200 Subject: [PATCH 3/5] fix: recover committed guest voucher redemptions --- api/app.py | 41 ++++--- quota/db.py | 109 +++++++++++++++--- quota/service.py | 31 +++++- run.py | 10 ++ tests/test_api.py | 60 ++++++++++ tests/test_guest_vouchers.py | 210 +++++++++++++++++++++++++++++++++++ 6 files changed, 428 insertions(+), 33 deletions(-) diff --git a/api/app.py b/api/app.py index 4c23549..de637a9 100644 --- a/api/app.py +++ b/api/app.py @@ -3204,17 +3204,18 @@ async def revoke_guest_voucher(code: str) -> dict[str, Any]: @app.post("/api/guest/voucher/redeem") async def redeem_guest_voucher(body: GuestVoucherRedeem, request: Request) -> dict[str, Any]: - if not await service.is_guest_mode(): - raise HTTPException(403, {"code": "guest_mode_disabled"}) - if await service.stop_new_connections(): - raise HTTPException(403, {"code": "new_guests_paused"}) - + guest_mode_enabled = await service.is_guest_mode() + new_guests_paused = await service.stop_new_connections() host = request.client.host if request.client else "" snapshot = holder.get() if holder else None mac = (str(snapshot.ip_to_mac.get(host, "") or "").strip().lower() if snapshot else "") dev = await database.get_device(mac=mac) if mac else None if dev is None or not dev.user_id: + if not guest_mode_enabled: + raise HTTPException(403, {"code": "guest_mode_disabled"}) + if new_guests_paused: + raise HTTPException(403, {"code": "new_guests_paused"}) raise HTTPException(403, {"code": "device_unrecognized"}) deny_macs = {str(value).strip().lower() @@ -3225,11 +3226,6 @@ async def redeem_guest_voucher(body: GuestVoucherRedeem, if dev.mac.lower() in deny_macs or dev.mac.lower() in kicked_macs: raise HTTPException(403, {"code": "device_blocked"}) - user = await database.get_user(dev.user_id) - if user is None or not is_pending_guest( - user.guest, user.block_state, dev.block_state): - raise HTTPException(403, {"code": "guest_not_pending"}) - async with voucher_attempts.serialize(dev.mac): kicked_getter = getattr(service, "active_kicked_macs", None) kicked_macs = kicked_getter() if callable(kicked_getter) else set() @@ -3262,11 +3258,26 @@ async def redeem_guest_voucher(body: GuestVoucherRedeem, raise HTTPException(503, {"code": "voucher_storage_unsupported"}) raise HTTPException(500, {"code": "voucher_service_error"}) - await service.recompute_allowances() - _schedule_shaping_sync() - await database.add_event( - f"Guest voucher redeemed for {dev.mac} ({quota_gb:g} GB)", - "info", dev.id) + # Redemption already committed atomically. A stale allowance snapshot + # must not turn that accepted claim into an HTTP error; the durable + # marker is retried by the next request, startup, and maintenance tick. + allowances_recovered = False + try: + allowances_recovered = await service.recover_guest_voucher_allowances() + except Exception: # noqa: BLE001 - committed voucher remains accepted + log.exception("guest voucher allowance recovery deferred") + if reason != "already_redeemed" or allowances_recovered: + try: + _schedule_shaping_sync() + except Exception: # noqa: BLE001 - shaping will be reconciled later + log.exception("guest voucher shaping sync deferred") + if reason != "already_redeemed": + try: + await database.add_event( + f"Guest voucher redeemed for {dev.mac} ({quota_gb:g} GB)", + "info", dev.id) + except Exception: # noqa: BLE001 - event logging is post-commit + log.exception("guest voucher audit event failed after redemption commit") return {"ok": True, "status": "approved", "quota_gb": quota_gb} # -- Guest Mode (Admin Accept / Reject) ----------------------------------- diff --git a/quota/db.py b/quota/db.py index a6b0750..80f957f 100644 --- a/quota/db.py +++ b/quota/db.py @@ -198,6 +198,7 @@ class GuestVoucher: used_mac: str = "" comment: str = "" revoked_at: Optional[float] = None + allowance_sync_pending: bool = False @dataclass @@ -482,7 +483,10 @@ class VpnRoutingRule: used_at REAL, used_mac TEXT NOT NULL DEFAULT '', comment TEXT NOT NULL DEFAULT '', - revoked_at REAL + revoked_at REAL, + used_user_id INTEGER, + used_device_id INTEGER, + allowance_sync_pending INTEGER NOT NULL DEFAULT 0 ); -- Bundle recharges queue (add-on packs) @@ -555,6 +559,18 @@ async def connect(self) -> None: await self._conn.execute( "ALTER TABLE guest_vouchers ADD COLUMN revoked_at REAL") await self._conn.commit() + for column, definition in ( + ("used_user_id", "INTEGER"), + ("used_device_id", "INTEGER"), + ("allowance_sync_pending", "INTEGER NOT NULL DEFAULT 0")): + if column not in voucher_columns: + await self._conn.execute( + f"ALTER TABLE guest_vouchers ADD COLUMN {column} {definition}") + await self._conn.commit() + await self._conn.execute( + "CREATE INDEX IF NOT EXISTS idx_guest_vouchers_allowance_sync_pending " + "ON guest_vouchers(code) WHERE allowance_sync_pending=1") + await self._conn.commit() # Legacy cleanup: the old guest-deletion `suppressed_macs` table (v20, # pre-blacklist) is orphaned — delete->deny-list replaced it and nothing # references it anymore. Idempotent; a fresh DB simply has no such table. @@ -1329,6 +1345,32 @@ async def set_bundle(self, bundle: Bundle) -> None: ) await self.conn.commit() + async def set_bundle_allowances(self, bundle: Bundle) -> None: + """Persist a recomputed snapshot without overwriting bundle policy.""" + await self.conn.execute( + """INSERT INTO bundle_config + (id, total_gb, reset_day, period_type, allowances, period_start, period_end) + VALUES (1, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + allowances=excluded.allowances, period_end=excluded.period_end""", + (bundle.total_gb, bundle.reset_day, bundle.period_type, + json.dumps(bundle.allowances), bundle.period_start, bundle.period_end)) + await self.conn.commit() + + async def set_bundle_period(self, bundle: Bundle) -> None: + """Persist a new period while preserving concurrently edited policy.""" + await self.conn.execute( + """INSERT INTO bundle_config + (id, total_gb, reset_day, period_type, allowances, period_start, period_end) + VALUES (1, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + allowances=excluded.allowances, + period_start=excluded.period_start, + period_end=excluded.period_end""", + (bundle.total_gb, bundle.reset_day, bundle.period_type, + json.dumps(bundle.allowances), bundle.period_start, bundle.period_end)) + await self.conn.commit() + # -- bundle recharges (add-on packs) -------------------------------------- async def create_recharge(self, gb: float, @@ -2125,6 +2167,20 @@ async def revoke_guest_voucher(self, code: str) -> bool: await self.conn.commit() return cur.rowcount > 0 + async def pending_guest_voucher_allowance_sync(self) -> list[str]: + rows = await self.conn.execute_fetchall( + "SELECT code FROM guest_vouchers WHERE allowance_sync_pending=1") + return [str(row["code"]) for row in rows] + + async def complete_guest_voucher_allowance_sync(self, codes: list[str]) -> None: + if not codes: + return + placeholders = ",".join("?" for _ in codes) + await self.conn.execute( + f"UPDATE guest_vouchers SET allowance_sync_pending=0 " + f"WHERE allowance_sync_pending=1 AND code IN ({placeholders})", codes) + await self.conn.commit() + async def redeem_guest_voucher_for_device( self, code: str, mac: str) -> tuple[bool, str, Optional[float]]: """Atomically claim a voucher and approve its eligible pending guest. @@ -2154,17 +2210,13 @@ async def redeem_guest_voucher_for_device( settings = {str(item["key"]): str(item["value"]) for item in await settings_cursor.fetchall()} await settings_cursor.close() - if settings.get("guest_mode", "0") != "1": - await conn.rollback() - return False, "guest_mode_disabled", None - if settings.get("stop_new_connections", "0") == "1": - await conn.rollback() - return False, "new_guests_paused", None - cursor = await conn.execute( """SELECT v.quota_gb, v.used_at, v.expires_at, v.revoked_at, + v.used_mac, v.used_user_id, v.used_device_id, d.id device_id, d.user_id, d.block_state device_state, - u.guest, u.block_state user_state + d.quota_mode device_quota_mode, d.fixed_gb device_fixed_gb, + u.guest, u.block_state user_state, + u.quota_mode user_quota_mode, u.fixed_gb user_fixed_gb FROM guest_vouchers v JOIN devices d ON lower(d.mac)=? JOIN users u ON u.id=d.user_id @@ -2185,10 +2237,6 @@ async def redeem_guest_voucher_for_device( if denied is not None: await conn.rollback() return False, "device_blocked", None - if not is_pending_guest( - bool(row["guest"]), row["user_state"], row["device_state"]): - await conn.rollback() - return False, "guest_not_pending", None count_cursor = await conn.execute( "SELECT COUNT(*) FROM devices WHERE user_id=?", @@ -2198,19 +2246,47 @@ async def redeem_guest_voucher_for_device( if device_count != 1: await conn.rollback() return False, "guest_account_shared", None - if row["used_at"] is not None or row["revoked_at"] is not None: + if row["used_at"] is not None: + same_claim = (row["used_mac"] == mac_clean + and row["used_user_id"] == row["user_id"] + and row["used_device_id"] == row["device_id"]) + same_guest = ( + bool(row["guest"]) + and row["user_state"] == BLOCK_OK + and row["device_state"] == BLOCK_OK + and row["user_quota_mode"] == QUOTA_FIXED + and row["device_quota_mode"] == QUOTA_FIXED + and row["user_fixed_gb"] == row["quota_gb"] + and row["device_fixed_gb"] == row["quota_gb"]) + await conn.rollback() + if same_claim and same_guest: + return True, "already_redeemed", float(row["quota_gb"]) + return False, "guest_not_pending", None + if row["revoked_at"] is not None: await conn.rollback() return False, "voucher_invalid", None if row["expires_at"] is not None and row["expires_at"] <= now: await conn.rollback() return False, "voucher_invalid", None + if settings.get("guest_mode", "0") != "1": + await conn.rollback() + return False, "guest_mode_disabled", None + if settings.get("stop_new_connections", "0") == "1": + await conn.rollback() + return False, "new_guests_paused", None + if not is_pending_guest( + bool(row["guest"]), row["user_state"], row["device_state"]): + await conn.rollback() + return False, "guest_not_pending", None + quota_gb = float(row["quota_gb"]) claim = await conn.execute( - """UPDATE guest_vouchers SET used_at=?, used_mac=? + """UPDATE guest_vouchers SET used_at=?, used_mac=?, + used_user_id=?, used_device_id=?, allowance_sync_pending=1 WHERE code=? AND used_at IS NULL AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > ?)""", - (now, mac_clean, code_clean, now)) + (now, mac_clean, row["user_id"], row["device_id"], code_clean, now)) if claim.rowcount != 1: await conn.rollback() return False, "voucher_invalid", None @@ -2337,6 +2413,7 @@ def _row_to_guest_voucher(row: Any) -> GuestVoucher: comment=row["comment"] or "", revoked_at=(float(row["revoked_at"]) if row["revoked_at"] is not None else None), + allowance_sync_pending=bool(row["allowance_sync_pending"]), ) diff --git a/quota/service.py b/quota/service.py index d8be988..012dfeb 100644 --- a/quota/service.py +++ b/quota/service.py @@ -60,6 +60,7 @@ def __init__(self, database: _db.Database, timezone: str = "", #: injectable clock (callable returning datetime) for tests self._clock = clock self._temporary_kicks: dict[str, float] = {} + self._allowance_lock = asyncio.Lock() #: "everyone is out of quota and nobody has an add-on pack" — the box #: opens the internet for all (see refresh_free_mode). Off by default #: until the first refresh. @@ -250,6 +251,10 @@ def _next_period_end(self, bundle: _db.Bundle, now: _dt.datetime) -> str: return timeutil.period_bounds(now, bundle.effective_reset_day)[1].date().isoformat() async def open_period(self) -> None: + async with self._allowance_lock: + await self._open_period_locked() + + async def _open_period_locked(self) -> None: """Open a fresh period: recompute allowances and set ``period_start`` to now. Called at startup, at each month roll-over, and by the manual @@ -257,6 +262,7 @@ async def open_period(self) -> None: touches historical usage rows. With ``reset_day <= 0`` the period is opened once and stays open (no automatic roll). """ + pending_voucher_sync = await self.db.pending_guest_voucher_allowance_sync() bundle = await self.db.get_bundle() now = self._now() effective = bundle.effective_reset_day @@ -274,25 +280,46 @@ async def open_period(self) -> None: # effective<=0 -> period_bounds returns "today"; period_end stays "". bundle.period_start = start.date().isoformat() bundle.period_end = end.date().isoformat() if effective > 0 else "" - await self.db.set_bundle(bundle) + await self.db.set_bundle_period(bundle) + await self.db.complete_guest_voucher_allowance_sync(pending_voucher_sync) log.info("quota period opened: %s -> %s (%d allowances)", bundle.period_start, bundle.period_end or "manual", len(bundle.allowances)) async def recompute_allowances(self) -> None: + async with self._allowance_lock: + await self._recompute_allowances_locked() + + async def _recompute_allowances_locked(self) -> None: """Refresh allowances + period_end without moving ``period_start``. Used after device edits, bundle changes, and mid-month top-ups of the bundle itself. Unlike :meth:`open_period`, it never rolls the period, so usage already recorded in the current period is preserved. """ + pending_voucher_sync = await self.db.pending_guest_voucher_allowance_sync() bundle = await self.db.get_bundle() now = self._now() bundle.allowances = await self.compute_allowances() bundle.period_end = self._next_period_end(bundle, now) - await self.db.set_bundle(bundle) + await self.db.set_bundle_allowances(bundle) + await self.db.complete_guest_voucher_allowance_sync(pending_voucher_sync) log.info("allowances recomputed (%d users)", len(bundle.allowances)) + async def recover_guest_voucher_allowances(self) -> bool: + """Retry the derived allowance snapshot after a committed voucher claim. + + The voucher transaction stores this pending marker before commit. A + successful recompute clears only markers observed before that recompute; + later claims remain queued for the next pass. Recompute derives from + current policy, so recovery never reapplies an old quota over edits. + """ + pending = await self.db.pending_guest_voucher_allowance_sync() + if not pending: + return False + await self.recompute_allowances() + return True + async def ensure_period(self) -> None: """Roll the period if stale, open if missing.""" bundle = await self.db.get_bundle() diff --git a/run.py b/run.py index 261444a..8d673ed 100644 --- a/run.py +++ b/run.py @@ -493,6 +493,10 @@ async def startup_core(self) -> None: script_path=cfg_mod.PROJECT_ROOT / "scripts" / "topology.sh") await self._seed_bundle_from_cfg() await self.service.ensure_period() + try: + await self.service.recover_guest_voucher_allowances() + except Exception: # noqa: BLE001 - maintenance retries the durable marker + log.exception("guest voucher allowance recovery deferred at startup") log.info("database ready: %s", self.cfg.db_path) if self.cfg.engine.enabled and self.engine is None: @@ -1501,6 +1505,12 @@ async def _timed(self, name: str, coro: Any) -> Any: async def _maintenance_tick(self) -> None: # 1. Roll the quota period if stale (covers month boundary). await self.service.ensure_period() + # A previous derived allowance write can fail after a voucher claim + # committed. Retry it before evaluating device blocks this tick. + try: + await self.service.recover_guest_voucher_allowances() + except Exception: # noqa: BLE001 - continue normal maintenance work + log.exception("guest voucher allowance recovery deferred") # 1b. Learn device bindings from dnsmasq's lease file. await self._timed("_sync_dnsmasq_leases", self._sync_dnsmasq_leases()) diff --git a/tests/test_api.py b/tests/test_api.py index 06244c4..a3df925 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -901,6 +901,66 @@ async def _seed(): assert user_view["blocked"] is True +@pytest.mark.parametrize("failure_point", ["recompute", "audit"]) +def test_voucher_retry_recovers_after_post_commit_failure(tmp_path, failure_point): + """A committed voucher stays accepted if derived work or audit logging fails.""" + database = _db.Database(tmp_path / "voucher-recovery.db") + service = QuotaService(database, timezone="Africa/Cairo") + holder = SnapshotHolder() + + async def _init(): + await database.connect() + await service.open_period() + await database.set_setting("guest_mode", "1") + guest = await database.create_user( + name="", quota_mode=_db.QUOTA_FIXED, fixed_gb=0.0, guest=True) + device = await database.upsert_device( + "aa:bb:cc:dd:ee:96", name="Visitor", user_id=guest.id, + guest=True, quota_mode=_db.QUOTA_FIXED, fixed_gb=0.0) + await database.set_device_state(device.id, _db.BLOCK_GUEST_PENDING) + await database.update_user(guest.id, block_state=_db.BLOCK_GUEST_PENDING) + await database.create_guest_voucher("recover-1234", 2.5) + holder.swap(EngineSnapshot(ip_to_mac={"127.0.0.1": device.mac})) + return guest.id + + guest_id = _get_loop().run_until_complete(_init()) + original_recompute = service.recompute_allowances + original_add_event = database.add_event + failures = [True] + + async def fail_once(): + if failures.pop() if failures else False: + raise RuntimeError("injected post-commit recompute failure") + await original_recompute() + + async def fail_event_once(*args, **kwargs): + if failures.pop() if failures else False: + raise RuntimeError("injected post-commit event failure") + await original_add_event(*args, **kwargs) + + if failure_point == "recompute": + service.recompute_allowances = fail_once + else: + database.add_event = fail_event_once + app = create_app(database, service, holder) + try: + with TestClient(app, client=("127.0.0.1", 50000)) as c: + first = c.post("/api/guest/voucher/redeem", json={"code": "recover-1234"}) + assert first.status_code == 200, first.text + assert first.json() == {"ok": True, "status": "approved", "quota_gb": 2.5} + + retry = c.post("/api/guest/voucher/redeem", json={"code": "recover-1234"}) + assert retry.status_code == 200, retry.text + assert retry.json() == first.json() + + guest = _get_loop().run_until_complete(database.get_user(guest_id)) + voucher = _get_loop().run_until_complete(database.get_guest_voucher("recover-1234")) + assert guest is not None and guest.fixed_gb == 2.5 + assert voucher is not None and voucher.used_at is not None + finally: + _get_loop().run_until_complete(database.close()) + + def test_connected_follows_arp_responders(tmp_path): """With the ARP probe running, a leased device is "connected" only if it ALSO answered the latest sweep — a lease alone lags reality by up to diff --git a/tests/test_guest_vouchers.py b/tests/test_guest_vouchers.py index 972c8df..f832226 100644 --- a/tests/test_guest_vouchers.py +++ b/tests/test_guest_vouchers.py @@ -6,6 +6,8 @@ import re import sqlite3 +import pytest + from quota import db as _db from quota.service import QuotaService @@ -58,6 +60,8 @@ async def scenario(): cursor = await database.conn.execute("PRAGMA table_info(guest_vouchers)") columns = {row["name"] for row in await cursor.fetchall()} assert "revoked_at" in columns + assert {"used_user_id", "used_device_id", + "allowance_sync_pending"} <= columns voucher = await database.get_guest_voucher(" keep-me ") assert voucher is not None assert voucher.quota_gb == 1.5 @@ -118,6 +122,185 @@ async def scenario(): asyncio.run(scenario()) +def test_same_guest_retry_is_idempotent_and_does_not_regrant(tmp_path): + async def scenario(): + database = _db.Database(tmp_path / "voucher-idempotent.db") + await database.connect() + try: + device = await _pending_guest(database, "aa:bb:cc:dd:ee:41") + await database.create_guest_voucher("retry-5678", 3.0) + + first = await database.redeem_guest_voucher_for_device( + "retry-5678", device.mac) + await database.set_setting("guest_mode", "0") + retry = await database.redeem_guest_voucher_for_device( + "retry-5678", device.mac) + + assert first == (True, "redeemed", 3.0) + assert retry == (True, "already_redeemed", 3.0) + user = await database.get_user(device.user_id) + current = await database.get_device(device_id=device.id) + voucher = await database.get_guest_voucher("retry-5678") + assert user is not None and user.fixed_gb == 3.0 + assert current is not None and current.fixed_gb == 3.0 + assert voucher is not None and voucher.allowance_sync_pending + finally: + await database.close() + + asyncio.run(scenario()) + + +def test_same_voucher_retry_rejects_changed_deleted_and_shared_accounts(tmp_path): + async def scenario(): + database = _db.Database(tmp_path / "voucher-stale-retry.db") + await database.connect() + try: + changed = await _pending_guest(database, "aa:bb:cc:dd:ee:42") + await database.create_guest_voucher("changed-5678", 3.0) + assert (await database.redeem_guest_voucher_for_device( + "changed-5678", changed.mac))[0] + await database.update_user(changed.user_id, fixed_gb=4.0) + assert await database.redeem_guest_voucher_for_device( + "changed-5678", changed.mac) == (False, "guest_not_pending", None) + + shared = await _pending_guest(database, "aa:bb:cc:dd:ee:43") + await database.create_guest_voucher("shared-5678", 2.0) + assert (await database.redeem_guest_voucher_for_device( + "shared-5678", shared.mac))[0] + await database.upsert_device("aa:bb:cc:dd:ee:44", "Sibling", + user_id=shared.user_id) + assert await database.redeem_guest_voucher_for_device( + "shared-5678", shared.mac) == (False, "guest_account_shared", None) + + deleted = await _pending_guest(database, "aa:bb:cc:dd:ee:45") + await database.create_guest_voucher("deleted-5678", 1.0) + assert (await database.redeem_guest_voucher_for_device( + "deleted-5678", deleted.mac))[0] + await database.delete_user(deleted.user_id) + assert await database.redeem_guest_voucher_for_device( + "deleted-5678", deleted.mac) == (False, "voucher_invalid", None) + + denied = await _pending_guest(database, "aa:bb:cc:dd:ee:48") + await database.create_guest_voucher("denied-5678", 1.0) + assert (await database.redeem_guest_voucher_for_device( + "denied-5678", denied.mac))[0] + await database.add_mac_list("deny", [denied.mac]) + assert await database.redeem_guest_voucher_for_device( + "denied-5678", denied.mac) == (False, "device_blocked", None) + finally: + await database.close() + + asyncio.run(scenario()) + + +def test_allowance_recovery_after_restart_uses_current_policy_once(tmp_path): + path = tmp_path / "voucher-restart.db" + + async def claim_and_restart(): + database = _db.Database(path) + await database.connect() + device = await _pending_guest(database, "aa:bb:cc:dd:ee:46") + await database.create_guest_voucher("restart-5678", 2.5) + assert await database.redeem_guest_voucher_for_device( + "restart-5678", device.mac) == (True, "redeemed", 2.5) + await database.update_user(device.user_id, fixed_gb=4.0) + await database.close() + return device.user_id + + user_id = asyncio.run(claim_and_restart()) + + async def recover(): + database = _db.Database(path) + await database.connect() + try: + service = QuotaService(database) + assert await service.recover_guest_voucher_allowances() is True + bundle = await database.get_bundle() + assert bundle.allowances[user_id] == 4.0 + voucher = await database.get_guest_voucher("restart-5678") + assert voucher is not None and not voucher.allowance_sync_pending + assert await service.recover_guest_voucher_allowances() is False + assert (await database.get_bundle()).allowances[user_id] == 4.0 + finally: + await database.close() + + asyncio.run(recover()) + + +def test_concurrent_allowance_refreshes_serialize_and_preserve_bundle_policy(tmp_path): + async def scenario(): + database = _db.Database(tmp_path / "voucher-refresh-order.db") + await database.connect() + try: + service = QuotaService(database) + original_compute = service.compute_allowances + first_entered = asyncio.Event() + release_first = asyncio.Event() + active = 0 + max_active = 0 + + async def delayed_compute(): + nonlocal active, max_active + active += 1 + max_active = max(max_active, active) + try: + if not first_entered.is_set(): + first_entered.set() + await release_first.wait() + return await original_compute() + finally: + active -= 1 + + service.compute_allowances = delayed_compute + first = asyncio.create_task(service.recompute_allowances()) + await first_entered.wait() + second = asyncio.create_task(service.recompute_allowances()) + await asyncio.sleep(0) + bundle = await database.get_bundle() + bundle.total_gb = 222.0 + bundle.period_start = "2026-11-01" + await database.set_bundle(bundle) + release_first.set() + await asyncio.gather(first, second) + + saved = await database.get_bundle() + assert max_active == 1 + assert saved.total_gb == 222.0 + assert saved.period_start == "2026-11-01" + finally: + await database.close() + + asyncio.run(scenario()) + + +def test_database_failure_before_commit_leaves_voucher_unspent(tmp_path): + async def scenario(): + database = _db.Database(tmp_path / "voucher-precommit-error.db") + await database.connect() + try: + device = await _pending_guest(database, "aa:bb:cc:dd:ee:47") + await database.create_guest_voucher("abort-5678", 1.0) + await database.conn.execute(""" + CREATE TRIGGER reject_guest_approval BEFORE UPDATE ON users + WHEN OLD.id = NEW.id AND OLD.guest = 1 + BEGIN SELECT RAISE(ABORT, 'injected approval failure'); END + """) + await database.conn.commit() + + with pytest.raises(Exception, match="injected approval failure"): + await database.redeem_guest_voucher_for_device( + "abort-5678", device.mac) + + voucher = await database.get_guest_voucher("abort-5678") + current = await database.get_device(device_id=device.id) + assert voucher is not None and voucher.used_at is None + assert current is not None and current.block_state == _db.BLOCK_GUEST_PENDING + finally: + await database.close() + + asyncio.run(scenario()) + + def test_memory_database_rejects_redemption_with_clear_reason(): async def scenario(): database = _db.Database(":memory:") @@ -139,6 +322,33 @@ async def scenario(): asyncio.run(scenario()) +def test_fresh_claim_still_respects_disabled_and_paused_guest_gates(tmp_path): + async def scenario(): + database = _db.Database(tmp_path / "voucher-gates.db") + await database.connect() + try: + disabled = await _pending_guest(database, "aa:bb:cc:dd:ee:49") + await database.create_guest_voucher("disabled-5678", 1.0) + await database.set_setting("guest_mode", "0") + assert await database.redeem_guest_voucher_for_device( + "disabled-5678", disabled.mac) == ( + False, "guest_mode_disabled", None) + + paused = await _pending_guest(database, "aa:bb:cc:dd:ee:50") + await database.create_guest_voucher("paused-5678", 1.0) + await database.set_setting("stop_new_connections", "1") + assert await database.redeem_guest_voucher_for_device( + "paused-5678", paused.mac) == ( + False, "new_guests_paused", None) + for code in ("disabled-5678", "paused-5678"): + voucher = await database.get_guest_voucher(code) + assert voucher is not None and voucher.used_at is None + finally: + await database.close() + + asyncio.run(scenario()) + + def test_expired_and_revoked_vouchers_do_not_redeem(tmp_path): async def scenario(): database = _db.Database(tmp_path / "voucher-ineligible.db") From 991a585a3586b014ce69abd27040f63884ba21f3 Mon Sep 17 00:00:00 2001 From: Noiemany Mostafa Mohamed <51255434+compnew2006@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:11:14 +0200 Subject: [PATCH 4/5] docs: document consistent SQLite backup and recovery --- README.md | 2 +- README_AR.md | 2 +- Structure_README.md | 141 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 143 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 26f1aa2..742a330 100644 --- a/README.md +++ b/README.md @@ -215,7 +215,7 @@ sudo apt remove quota-manager # rem sudo apt purge quota-manager # remove everything ``` -Your data lives in `/var/lib/quota-gateway/quota.db` — copy it now and then as a backup. +Your data lives in `/var/lib/quota-gateway/quota.db`. Back it up with SQLite's online backup procedure, which works while the gateway is running and includes committed WAL data. For backup and restore commands, see the [SQLite backup and restore guide](Structure_README.md#sqlite-backup-and-restore). ## Troubleshooting diff --git a/README_AR.md b/README_AR.md index 05dd886..0697cb5 100644 --- a/README_AR.md +++ b/README_AR.md @@ -220,7 +220,7 @@ sudo apt purge quota-manager # إ
-بياناتك في `/var/lib/quota-gateway/quota.db` — انسخها من وقت للتاني كنسخة احتياطية. +بياناتك موجودة في `/var/lib/quota-gateway/quota.db`. اعمل نسخة احتياطية بأداة SQLite للنسخ المباشر، وهي آمنة والبوابة شغالة وبتشمل البيانات المحفوظة في WAL. أوامر النسخ والاستعادة موجودة في [دليل نسخ واستعادة SQLite](Structure_README.md#sqlite-backup-and-restore). ## حل المشاكل diff --git a/Structure_README.md b/Structure_README.md index 831b9f0..543279b 100644 --- a/Structure_README.md +++ b/Structure_README.md @@ -15,6 +15,7 @@ the project layout, tests, and the release process. - [Topology: a one-armed gateway](#topology-a-one-armed-gateway) - [The packet path (no Python)](#the-packet-path-no-python) - [The maintenance loop](#the-maintenance-loop) +- [SQLite backup and restore](#sqlite-backup-and-restore) - [Quota model](#quota-model) - [Speed shaping](#speed-shaping) - [DNS filtering (domain rules, presets, per-client DNS servers)](#dns-filtering-domain-rules-presets-per-client-dns-servers) @@ -252,6 +253,146 @@ below. --- +## SQLite backup and restore + +The runtime database is `/var/lib/quota-gateway/quota.db`; `Database.connect()` +opens it in WAL mode (`PRAGMA journal_mode=WAL`). While the service is running, +recent committed changes can still live in `quota.db-wal` and are not necessarily +checkpointed into `quota.db`. A plain `cp quota.db backup.db` is therefore not a +consistent live backup. Do not copy the main file and its `-wal`/`-shm` sidecars +separately while SQLite is open; writes and checkpoints can race that copy. + +Use Python's standard-library `sqlite3.Connection.backup()` API. It takes a +consistent SQLite snapshot while writers continue and includes committed WAL +content visible to that snapshot (later writes are not included). After the +copy, switch the destination to rollback-journal `DELETE` mode and close it; +this checkpoints any destination WAL and makes the backup a standalone file +without sidecars. The script checks it with `PRAGMA integrity_check` before +reporting success and restricts its mode: + +```bash +( set -eu + sudo install -d -m 700 /var/lib/quota-gateway/backups + BACKUP="/var/lib/quota-gateway/backups/quota-$(date +%F-%H%M%S).db" + sudo test ! -e "$BACKUP" + sudo python3 - "$BACKUP" <<'PY' +from contextlib import closing +import os +import sqlite3 +import sys + +destination = sys.argv[1] +with closing(sqlite3.connect( + "file:/var/lib/quota-gateway/quota.db?mode=ro", uri=True)) as source: + with closing(sqlite3.connect(destination)) as backup: + source.backup(backup) + mode = backup.execute("PRAGMA journal_mode=DELETE").fetchone()[0] + if mode.lower() != "delete": + raise SystemExit(f"Could not make backup standalone: {mode}") + check = backup.execute("PRAGMA integrity_check").fetchone()[0] + if check != "ok": + raise SystemExit(f"Backup validation failed: {check}") +os.chmod(destination, 0o600) +print(f"Backup saved and verified: {destination}") +PY +) +``` + +Restore only with the service stopped. Validate the standalone backup first; +then move the old database and any sidecars aside as one set before installing +the backup. Never put an old `quota.db-wal` beside a restored database. For +example: + +```bash +( set -eu + DB_DIR=/var/lib/quota-gateway + BACKUP="/var/lib/quota-gateway/backups/quota-YYYY-MM-DD-HHMMSS.db" + STAMP="$(date +%F-%H%M%S)" + STAGED="$DB_DIR/.quota.db.restore-$STAMP-$$" + ARCHIVE="$DB_DIR/quota.db.pre-restore-$STAMP" + sudo test -f "$BACKUP" + sudo test ! -e "$STAGED" + sudo test ! -e "$ARCHIVE" + sudo python3 - "$BACKUP" <<'PY' +import sqlite3 +import sys + +with sqlite3.connect( + f"file:{sys.argv[1]}?mode=ro&immutable=1", uri=True) as backup: + check = backup.execute("PRAGMA integrity_check").fetchone()[0] +if check != "ok": + raise SystemExit(f"Backup validation failed: {check}") +print("Backup is valid") +PY + sudo install -o root -g root -m 600 "$BACKUP" "$STAGED" + sudo python3 - "$STAGED" <<'PY' +import sqlite3 +import sys + +with sqlite3.connect( + f"file:{sys.argv[1]}?mode=ro&immutable=1", uri=True) as staged: + check = staged.execute("PRAGMA integrity_check").fetchone()[0] +if check != "ok": + raise SystemExit(f"Staged database validation failed: {check}") +PY + sudo mkdir -m 700 "$ARCHIVE" + sudo systemctl stop quota-gateway + if sudo test -e "$DB_DIR/quota.db"; then + sudo mv "$DB_DIR/quota.db" "$ARCHIVE/quota.db" + fi + for suffix in -wal -shm; do + if sudo test -e "$DB_DIR/quota.db$suffix"; then + sudo mv "$DB_DIR/quota.db$suffix" "$ARCHIVE/quota.db$suffix" + fi + done + sudo mv "$STAGED" "$DB_DIR/quota.db" + printf 'Old database and sidecars are preserved in %s\n' "$ARCHIVE" + sudo systemctl start quota-gateway +) +``` + +The restore block uses `set -eu`: any failed validation, stop, move, or start +ends the block immediately. It validates a staged replacement before stopping +the service and uses unique paths that refuse to overwrite existing files. If +the service does not start after replacement, leave it stopped and restore the +preserved files. Substitute the exact archive path printed by the restore +block: + +```bash +( set -eu + DB_DIR=/var/lib/quota-gateway + ARCHIVE="$DB_DIR/quota.db.pre-restore-YYYY-MM-DD-HHMMSS" + sudo systemctl stop quota-gateway + sudo test -f "$ARCHIVE/quota.db" + sudo test ! -e "$ARCHIVE/quota.db.failed-restore" + if sudo test -e "$DB_DIR/quota.db"; then + sudo mv "$DB_DIR/quota.db" "$ARCHIVE/quota.db.failed-restore" + fi + for suffix in -wal -shm; do + if sudo test -e "$DB_DIR/quota.db$suffix"; then + sudo test ! -e "$ARCHIVE/quota.db.failed-restore$suffix" + sudo mv "$DB_DIR/quota.db$suffix" \ + "$ARCHIVE/quota.db.failed-restore$suffix" + fi + done + sudo mv "$ARCHIVE/quota.db" "$DB_DIR/quota.db" + for suffix in -wal -shm; do + if sudo test -e "$ARCHIVE/quota.db$suffix"; then + sudo mv "$ARCHIVE/quota.db$suffix" "$DB_DIR/quota.db$suffix" + fi + done + sudo systemctl start quota-gateway +) +``` + +Keep the backup file outside the live DB path. This procedure targets the +packaged systemd service and its default DB path; custom `db_path` or service +setups must use their configured path and unit name. An online DB backup does +not include unrelated files in the DB directory, such as `firewall_config.json`; +back up that file separately when needed. + +--- + ## Quota model The monthly allowance lives on a **user**, not a device (`users` table; From 0cb892112f5e0ed57459c2ffcfd03a4c9ca2142c Mon Sep 17 00:00:00 2001 From: Youssef Alkhodary <82382970+UserJoo9@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:34:25 +0200 Subject: [PATCH 5/5] README: one-line live backup; CHANGELOG credits for #49, #55, #56 (@compnew2006) The README pointed users to a 40-line script; it now shows one safe command (sqlite3 backup API, works while the gateway runs). The full backup/restore procedure stays in Structure_README. --- CHANGELOG.md | 3 +++ README.md | 8 +++++++- README_AR.md | 12 +++++++++++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 203aca3..2102f56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ Added: - **Internet schedule** (new page). Turn the internet off at set times of the week for chosen people (all their devices) or single devices: bedtime on school nights, study time, meal times. One click starts from a ready plan ("School nights", "Every night", "Study time", "Meal times"); a schedule can have several times, a time can run past midnight, and dates can be marked as days off (holidays, Eid). **Bonus time** gives a few extra minutes without changing the schedule. **Always allowed** sites (a school platform, a study site) keep working during every schedule. While a schedule is on, the device's card shows when the internet comes back, the home network (printer, shared drives, the dashboard) keeps working, and the cut is done by the gateway itself, so it works on any phone, tablet, TV or console with no app. Each device gets its end time in the system kernel, so it comes back online on time even if the gateway service restarts or stops. Sites on the "always allowed" list only open on devices that look names up through the gateway; a phone with Private DNS (or a browser with secure DNS) turned on keeps them blocked during a schedule. Contributed by @amr-elgharip2006. Closes #32. Fixed: +- A guest who typed a valid code could get an error even though the code was accepted, and then be told the code was already used. The approval now always comes back, and a guest who retries gets the same approval again. Contributed by @compnew2006. +- The security filter on the dashboard (for access from outside the home) now checks a request's size as it arrives and keeps its memory bounded, so a flood of large or never-ending requests can no longer slow the gateway down. Access from inside the home is unchanged. Contributed by @compnew2006. +- README: a one-line, safe way to back up the gateway's data while it runs, plus a restore guide. Contributed by @compnew2006. - **Share** (files sent between devices at home) can no longer fill the gateway's disk: one file can be up to 4 GB, all shared files together up to 16 GB, and the gateway always keeps 1 GB free for itself. A file that does not fit is refused with a clear message instead of being half-saved. Contributed by @compnew2006. - The guest waiting page: entering a guest code now also works when the same browser is logged in to the dashboard, the "start browsing" button gets the focus after approval, hidden parts stay hidden, and the pulsing animation stops for people who turned off motion on their device. Contributed by @compnew2006. - Website block/allow rules were rebuilt every time the gateway started, so their numbers changed on each restart. They are now kept as they are. If an older version was interrupted in the middle of that rebuild (for example by a power cut), the rules it left behind are put back on the next start instead of being lost. Contributed by @compnew2006. diff --git a/README.md b/README.md index bfcfcf8..61b699b 100644 --- a/README.md +++ b/README.md @@ -248,7 +248,13 @@ sudo apt remove quota-manager # rem sudo apt purge quota-manager # remove everything ``` -Your data lives in `/var/lib/quota-gateway/quota.db`. Back it up with SQLite's online backup procedure, which works while the gateway is running and includes committed WAL data. For backup and restore commands, see the [SQLite backup and restore guide](Structure_README.md#sqlite-backup-and-restore). +Your data lives in `/var/lib/quota-gateway/quota.db`. To back it up (safe while the gateway is running): + +```bash +sudo python3 -c "import sqlite3; sqlite3.connect('/var/lib/quota-gateway/quota.db').backup(sqlite3.connect('/root/netrex-backup.db'))" +``` + +Don't just copy `quota.db` with `cp` while the gateway runs: recent changes may still sit in a side file and the copy can come out broken. Restoring a backup is in the [backup and restore guide](Structure_README.md#sqlite-backup-and-restore). ## Troubleshooting diff --git a/README_AR.md b/README_AR.md index fb0211d..6a2ef1a 100644 --- a/README_AR.md +++ b/README_AR.md @@ -257,7 +257,17 @@ sudo apt purge quota-manager # إ
-بياناتك موجودة في `/var/lib/quota-gateway/quota.db`. اعمل نسخة احتياطية بأداة SQLite للنسخ المباشر، وهي آمنة والبوابة شغالة وبتشمل البيانات المحفوظة في WAL. أوامر النسخ والاستعادة موجودة في [دليل نسخ واستعادة SQLite](Structure_README.md#sqlite-backup-and-restore). +بياناتك موجودة في `/var/lib/quota-gateway/quota.db`. عشان تاخد نسخة احتياطية منها (آمن والبوابة شغالة): + +
+ +```bash +sudo python3 -c "import sqlite3; sqlite3.connect('/var/lib/quota-gateway/quota.db').backup(sqlite3.connect('/root/netrex-backup.db'))" +``` + +
+ +ما تنسخش `quota.db` بـ `cp` والبوابة شغالة: آخر التغييرات ممكن تكون لسه في ملف جانبي والنسخة تطلع بايظة. استرجاع النسخة موجود في [دليل النسخ والاسترجاع](Structure_README.md#sqlite-backup-and-restore). ## حل المشاكل