diff --git a/backend/auth.py b/backend/auth.py index 565f8c3e..7b35e012 100644 --- a/backend/auth.py +++ b/backend/auth.py @@ -410,6 +410,16 @@ def require_local_operator(request: Request): raise HTTPException(status_code=403, detail="Forbidden — operator authentication required") +def is_local_operator_request(request: Request) -> bool: + """Non-raising form of ``require_local_operator`` for routes that are + public by design but have operator-only branches.""" + try: + require_local_operator(request) + except HTTPException: + return False + return True + + # --------------------------------------------------------------------------- # OpenClaw HMAC authentication # --------------------------------------------------------------------------- diff --git a/backend/main.py b/backend/main.py index 86b81eea..4dca26f2 100644 --- a/backend/main.py +++ b/backend/main.py @@ -348,6 +348,7 @@ from auth import ( _transport_tier_precondition, require_admin, require_local_operator, + is_local_operator_request, _validate_admin_startup, _validate_insecure_admin_startup, _validate_peer_push_secret, @@ -4106,45 +4107,6 @@ async def oracle_region_intel( return get_region_oracle_intel(lat, lng, news_items) -@app.get("/api/thermal/verify") -@limiter.limit("10/minute") -async def thermal_verify( - request: Request, - lat: float = Query(..., ge=-90, le=90), - lng: float = Query(..., ge=-180, le=180), - radius_km: float = Query(10, ge=1, le=100), -): - """On-demand thermal anomaly verification using Sentinel-2 SWIR bands.""" - from services.thermal_sentinel import search_thermal_anomaly - - result = search_thermal_anomaly(lat, lng, radius_km) - return result - - -@app.post("/api/sigint/transmit") -@limiter.limit("5/minute") -async def sigint_transmit(request: Request): - """Send an APRS-IS message to a specific callsign. Requires ham radio credentials.""" - from services.wormhole_supervisor import get_transport_tier - - tier = get_transport_tier() - if str(tier or "").startswith("private_"): - return {"ok": False, "detail": "APRS transmit blocked in private transport mode"} - body = await request.json() - callsign = body.get("callsign", "") - passcode = body.get("passcode", "") - target = body.get("target", "") - message = body.get("message", "") - if not all([callsign, passcode, target, message]): - return { - "ok": False, - "detail": "Missing required fields: callsign, passcode, target, message", - } - from services.sigint_bridge import send_aprs_message - - return send_aprs_message(callsign, passcode, target, message) - - @app.get("/api/sigint/nearest-sdr") @limiter.limit("30/minute") async def nearest_sdr( @@ -4495,6 +4457,23 @@ async def mesh_send(request: Request): # ─── Per-identity throttle ──────────────────────────────────── priority_str = signed_payload["priority"] transport_lock = str(body.get("transport_lock", "") or "").lower() + # Public radio lanes (APRS-IS, Meshtastic MQTT) and the all-transport + # EMERGENCY broadcast are operator-only; see routers/mesh_public.py. + is_operator = is_local_operator_request(request) + from services.meshtastic_mqtt_settings import mqtt_bridge_enabled + + allow_aprs = is_operator + allow_meshtastic = is_operator and mqtt_bridge_enabled() + if not is_operator and (priority_str == "emergency" or transport_lock in {"aprs", "meshtastic"}): + return JSONResponse( + status_code=403, + content={ + "ok": False, + "detail": "Radio transports and emergency broadcast require operator authentication", + }, + ) + if transport_lock == "meshtastic" and not allow_meshtastic: + return {"ok": False, "detail": "Meshtastic MQTT bridge is disabled"} throttle_ok, throttle_reason = _check_throttle(node_id, priority_str, transport_lock) if not throttle_ok: return {"ok": False, "detail": throttle_reason} @@ -4562,9 +4541,19 @@ async def mesh_send(request: Request): "Private-tier content cannot be sent over APRS" )] else: - results = mesh_router.route(envelope, credentials) + results = mesh_router.route( + envelope, + credentials, + allow_aprs=allow_aprs, + allow_meshtastic=allow_meshtastic, + ) else: - results = mesh_router.route(envelope, credentials) + results = mesh_router.route( + envelope, + credentials, + allow_aprs=allow_aprs, + allow_meshtastic=allow_meshtastic, + ) any_ok = any(r.ok for r in results) # ─── Mirror to Meshtastic bridge feed ──────────────────────── @@ -8866,21 +8855,6 @@ def _rewrite_cctv_hls_playlist(base_url: str, body: str) -> str: return "\n".join(rewritten_lines) + ("\n" if body.endswith("\n") else "") -@app.get("/api/cctv/media") -@limiter.limit("120/minute") -async def cctv_media_proxy(request: Request, url: str = Query(...)): - """Proxy CCTV media through the backend to bypass browser CORS restrictions.""" - from urllib.parse import urlparse - - parsed = urlparse(url) - if not _cctv_host_allowed(parsed.hostname): - raise HTTPException(status_code=403, detail="Host not allowed") - if parsed.scheme not in ("http", "https"): - raise HTTPException(status_code=400, detail="Invalid scheme") - - return _proxy_cctv_media_response(request, url) - - @app.get("/api/health", response_model=HealthResponse) @limiter.limit("30/minute") async def health_check(request: Request): @@ -8931,19 +8905,6 @@ async def api_get_openmhz_systems(request: Request): return get_openmhz_systems() -@app.get("/api/radio/openmhz/calls/{sys_name}") -@limiter.limit("60/minute") -async def api_get_openmhz_calls(request: Request, sys_name: str): - return get_recent_openmhz_calls(sys_name) - - -@app.get("/api/radio/openmhz/audio") -@limiter.limit("120/minute") -async def api_get_openmhz_audio(request: Request, url: str = Query(..., min_length=10)): - from services.radio_intercept import openmhz_audio_response - return openmhz_audio_response(url) - - @app.get("/api/radio/nearest") @limiter.limit("60/minute") async def api_get_nearest_radio( @@ -9062,204 +9023,10 @@ def api_sentinel2_search( return search_sentinel2_scene(lat, lng) -@app.post("/api/sentinel/token") -@limiter.limit("60/minute") -async def api_sentinel_token(request: Request): - """Proxy Copernicus CDSE OAuth2 token request (avoids browser CORS block). - - The user's client_id + client_secret are forwarded to the Copernicus - identity provider and never stored on the server. - """ - import requests as req - - # Parse URL-encoded form body manually (avoids python-multipart dependency) - body = await request.body() - from urllib.parse import parse_qs - params = parse_qs(body.decode("utf-8")) - client_id = params.get("client_id", [""])[0] - client_secret = params.get("client_secret", [""])[0] - - if not client_id or not client_secret: - raise HTTPException(400, "client_id and client_secret required") - - token_url = "https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/openid-connect/token" - try: - resp = await asyncio.to_thread( - req.post, - token_url, - data={ - "grant_type": "client_credentials", - "client_id": client_id, - "client_secret": client_secret, - }, - timeout=15, - ) - return Response( - content=resp.content, - status_code=resp.status_code, - media_type="application/json", - ) - except Exception as exc: - logger.exception("Token request failed") - raise HTTPException(502, "Token request failed") - - # Server-side token cache for tile requests (avoids re-auth on every tile) _sh_token_cache: dict = {"token": None, "expiry": 0, "client_id": ""} -@app.post("/api/sentinel/tile") -@limiter.limit("300/minute") -async def api_sentinel_tile(request: Request): - """Proxy Sentinel Hub Process API tile request (avoids CORS block). - - Expects JSON body with: client_id, client_secret, preset, date, z, x, y. - Returns the PNG tile directly. - """ - import requests as req - import time as _time - - try: - body = await request.json() - except Exception: - return JSONResponse(status_code=422, content={"ok": False, "detail": "invalid JSON body"}) - - client_id = body.get("client_id", "") - client_secret = body.get("client_secret", "") - preset = body.get("preset", "TRUE-COLOR") - date_str = body.get("date", "") - z = body.get("z", 0) - x = body.get("x", 0) - y = body.get("y", 0) - - if not client_id or not client_secret or not date_str: - raise HTTPException(400, "client_id, client_secret, and date required") - - # Reuse cached token if same client_id and not expired - now = _time.time() - if ( - _sh_token_cache["token"] - and _sh_token_cache["client_id"] == client_id - and now < _sh_token_cache["expiry"] - 30 - ): - token = _sh_token_cache["token"] - else: - # Fetch new token - token_url = "https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/openid-connect/token" - try: - tresp = await asyncio.to_thread( - req.post, - token_url, - data={ - "grant_type": "client_credentials", - "client_id": client_id, - "client_secret": client_secret, - }, - timeout=15, - ) - if tresp.status_code != 200: - raise HTTPException(401, f"Token auth failed: {tresp.text[:200]}") - tdata = tresp.json() - token = tdata["access_token"] - _sh_token_cache["token"] = token - _sh_token_cache["expiry"] = now + tdata.get("expires_in", 300) - _sh_token_cache["client_id"] = client_id - except HTTPException: - raise - except Exception as exc: - logger.exception("Token request failed") - raise HTTPException(502, "Token request failed") - - # Compute bounding box from tile coordinates (EPSG:3857) - import math - - half = 20037508.342789244 - tile_size = (2 * half) / math.pow(2, z) - min_x = -half + x * tile_size - max_x = min_x + tile_size - max_y = half - y * tile_size - min_y = max_y - tile_size - bbox = [min_x, min_y, max_x, max_y] - - # Evalscripts - evalscripts = { - "TRUE-COLOR": '//VERSION=3\nfunction setup(){return{input:["B04","B03","B02"],output:{bands:3}};}\nfunction evaluatePixel(s){return[2.5*s.B04,2.5*s.B03,2.5*s.B02];}', - "FALSE-COLOR": '//VERSION=3\nfunction setup(){return{input:["B08","B04","B03"],output:{bands:3}};}\nfunction evaluatePixel(s){return[2.5*s.B08,2.5*s.B04,2.5*s.B03];}', - "NDVI": '//VERSION=3\nfunction setup(){return{input:["B04","B08"],output:{bands:3}};}\nfunction evaluatePixel(s){var n=(s.B08-s.B04)/(s.B08+s.B04);if(n<-0.2)return[0.05,0.05,0.05];if(n<0)return[0.75,0.75,0.75];if(n<0.1)return[0.86,0.86,0.86];if(n<0.2)return[0.92,0.84,0.68];if(n<0.3)return[0.77,0.88,0.55];if(n<0.4)return[0.56,0.80,0.32];if(n<0.5)return[0.35,0.72,0.18];if(n<0.6)return[0.20,0.60,0.08];if(n<0.7)return[0.10,0.48,0.04];return[0.0,0.36,0.0];}', - "MOISTURE-INDEX": '//VERSION=3\nfunction setup(){return{input:["B8A","B11"],output:{bands:3}};}\nfunction evaluatePixel(s){var m=(s.B8A-s.B11)/(s.B8A+s.B11);var r=Math.max(0,Math.min(1,1.5-3*m));var g=Math.max(0,Math.min(1,m<0?1.5+3*m:1.5-3*m));var b=Math.max(0,Math.min(1,1.5+3*(m-0.5)));return[r,g,b];}', - } - evalscript = evalscripts.get(preset, evalscripts["TRUE-COLOR"]) - - # Adaptive time range: wider window at lower zoom for better coverage. - # Sentinel-2 has 5-day revisit — a single day often has gaps. - # At low zoom we mosaic over more days to fill gaps. - from datetime import datetime as _dt, timedelta as _td - - try: - end_date = _dt.strptime(date_str, "%Y-%m-%d") - except ValueError: - end_date = _dt.utcnow() - - if z <= 6: - lookback_days = 30 # continent-level: mosaic a full month - elif z <= 9: - lookback_days = 14 # region-level: 2 weeks - elif z <= 11: - lookback_days = 7 # country-level: 1 week - else: - lookback_days = 5 # close-up: 5 days (one revisit cycle) - - start_date = end_date - _td(days=lookback_days) - - process_body = { - "input": { - "bounds": { - "bbox": bbox, - "properties": {"crs": "http://www.opengis.net/def/crs/EPSG/0/3857"}, - }, - "data": [ - { - "type": "sentinel-2-l2a", - "dataFilter": { - "timeRange": { - "from": start_date.strftime("%Y-%m-%dT00:00:00Z"), - "to": end_date.strftime("%Y-%m-%dT23:59:59Z"), - }, - "maxCloudCoverage": 30, - "mosaickingOrder": "leastCC", - }, - } - ], - }, - "output": { - "width": 256, - "height": 256, - "responses": [{"identifier": "default", "format": {"type": "image/png"}}], - }, - "evalscript": evalscript, - } - - try: - resp = await asyncio.to_thread( - req.post, - "https://sh.dataspace.copernicus.eu/api/v1/process", - json=process_body, - headers={ - "Authorization": f"Bearer {token}", - "Accept": "image/png", - }, - timeout=30, - ) - return Response( - content=resp.content, - status_code=resp.status_code, - media_type=resp.headers.get("content-type", "image/png"), - ) - except Exception as exc: - logger.exception("Process API failed") - raise HTTPException(502, "Process API failed") - - # --------------------------------------------------------------------------- # API Settings — key registry & management # --------------------------------------------------------------------------- @@ -9649,7 +9416,7 @@ async def api_set_node_settings(request: Request, body: NodeSettingsUpdate): return result -@app.post("/api/mesh/infonet/swarm/join") +@app.post("/api/mesh/infonet/swarm/join", dependencies=[Depends(require_local_operator)]) @limiter.limit("10/minute") async def infonet_swarm_join(request: Request): """Announce this node to the fleet seed and pull the signed peer manifest.""" @@ -10436,77 +10203,6 @@ async def api_get_wormhole_status(request: Request): ) -@app.post("/api/wormhole/join") -@limiter.limit("10/minute") -async def api_wormhole_join(request: Request): - existing = read_wormhole_settings() - updated = write_wormhole_settings( - enabled=True, - transport="tor_arti", - socks_proxy=f"socks5h://127.0.0.1:{int(get_settings().MESH_ARTI_SOCKS_PORT or 9050)}", - socks_dns=True, - anonymous_mode=True, - ) - transport_changed = ( - str(existing.get("transport", "direct")) != "tor_arti" - or str(existing.get("socks_proxy", "")) != str(updated.get("socks_proxy", "")) - or bool(existing.get("socks_dns", True)) is not True - or bool(existing.get("anonymous_mode", False)) is not True - or bool(existing.get("enabled", False)) is not True - ) - tor_result: dict[str, Any] = {"ok": False, "detail": "not started"} - try: - from services.tor_hidden_service import tor_service - from routers.ai_intel import _write_env_value - - tor_result = await asyncio.to_thread(tor_service.start) - if tor_result.get("ok"): - _write_env_value("MESH_ARTI_ENABLED", "true") - get_settings.cache_clear() - except Exception as exc: - tor_result = {"ok": False, "detail": str(exc or type(exc).__name__)} - bootstrap_wormhole_identity() - bootstrap_wormhole_persona_state() - state = ( - restart_wormhole(reason="join_wormhole") - if transport_changed - else connect_wormhole(reason="join_wormhole") - ) - - # Enable node participation so the sync/push workers connect to peers. - # This is the voluntary opt-in — the node only joins the network when - # the user explicitly opens the Wormhole. - from services.node_settings import write_node_settings - - write_node_settings(enabled=True) - _refresh_node_peer_store() - - return { - "ok": True, - "identity": get_transport_identity(), - "runtime": state, - "settings": updated, - "tor": tor_result, - } - - -@app.post("/api/wormhole/leave") -@limiter.limit("10/minute") -async def api_wormhole_leave(request: Request): - updated = write_wormhole_settings(enabled=False) - state = disconnect_wormhole(reason="leave_wormhole") - - # Leaving private DM mode must not disable Infonet participation. Infonet - # sync has its own private transport warmup and can remain connected to - # seed/peer nodes while MeshChat stays separately opt-in. - - return { - "ok": True, - "runtime": state, - "settings": updated, - } - - @app.get("/api/wormhole/identity", dependencies=[Depends(require_local_operator)]) @limiter.limit("30/minute") async def api_wormhole_identity(request: Request): diff --git a/backend/routers/ai_intel.py b/backend/routers/ai_intel.py index 7e5d6ab2..90f0cc4f 100644 --- a/backend/routers/ai_intel.py +++ b/backend/routers/ai_intel.py @@ -3455,7 +3455,11 @@ async def channel_websocket(ws: WebSocket): """ # Auth: check HMAC on upgrade, or allow local connections host = (ws.client.host or "").lower() if ws.client else "" - is_local = host in ("127.0.0.1", "::1", "localhost") + # Behind a same-host reverse proxy every internet client arrives as + # loopback; the operator declares that with SHADOWBROKER_UNTRUSTED_LOOPBACK. + from auth import _loopback_untrusted + + is_local = host in ("127.0.0.1", "::1", "localhost") and not _loopback_untrusted() if not is_local and not await _verify_ws_hmac(ws): # Must accept before sending close with custom code diff --git a/backend/routers/cctv.py b/backend/routers/cctv.py index 9ff9a160..29eaa89d 100644 --- a/backend/routers/cctv.py +++ b/backend/routers/cctv.py @@ -155,17 +155,60 @@ class _CCTVProxyProfile: headers: dict = field(default_factory=dict) +# Shared storage hosts: a subdomain or path is somebody else's bucket, so only +# the exact host is accepted, and only under the listed path prefixes. +_CCTV_SHARED_STORAGE_PATH_PREFIXES = { + "s3-eu-west-1.amazonaws.com": ("/jamcams.tfl.gov.uk/",), +} + + def _cctv_host_allowed(hostname) -> bool: host = str(hostname or "").strip().lower() if not host: return False for allowed in _CCTV_PROXY_ALLOWED_HOSTS: normalized = str(allowed or "").strip().lower() - if host == normalized or host.endswith(f".{normalized}"): + if host == normalized: + return True + if normalized in _CCTV_SHARED_STORAGE_PATH_PREFIXES: + continue + if host.endswith(f".{normalized}"): return True return False +def _cctv_path_allowed(parsed) -> bool: + host = str(getattr(parsed, "hostname", "") or "").strip().lower() + prefixes = _CCTV_SHARED_STORAGE_PATH_PREFIXES.get(host) + if prefixes is None: + return True + path = str(getattr(parsed, "path", "") or "") + return any(path.startswith(prefix) for prefix in prefixes) + + +# Only media is relayed. Anything a browser could render as a page or run as +# script (HTML, SVG, XML, JS) is refused even from an allowed host. +_CCTV_ALLOWED_MEDIA_PREFIXES = ("image/", "video/") +_CCTV_ALLOWED_MEDIA_TYPES = { + "application/vnd.apple.mpegurl", + "application/x-mpegurl", + "audio/mpegurl", + "audio/x-mpegurl", + "application/octet-stream", + "binary/octet-stream", + "multipart/x-mixed-replace", +} + + +def _cctv_media_type_allowed(content_type: str) -> bool: + clean = str(content_type or "").split(";", 1)[0].strip().lower() + if not clean: + return True + if clean == "image/svg+xml": + return False + return clean.startswith(_CCTV_ALLOWED_MEDIA_PREFIXES) or clean in _CCTV_ALLOWED_MEDIA_TYPES + + def _proxied_cctv_url(target_url: str) -> str: from urllib.parse import quote return f"/api/cctv/media?url={quote(target_url, safe='')}" @@ -327,7 +370,11 @@ def _cctv_upstream_headers(request: Request, profile: _CCTVProxyProfile) -> dict def _cctv_response_headers(resp, cache_seconds: int, include_length: bool = True) -> dict: - headers = {"Cache-Control": f"public, max-age={cache_seconds}", "Access-Control-Allow-Origin": "*"} + headers = { + "Cache-Control": f"public, max-age={cache_seconds}", + "Access-Control-Allow-Origin": "*", + "X-Content-Type-Options": "nosniff", + } for key in ("Accept-Ranges", "Content-Range", "ETag", "Last-Modified"): value = resp.headers.get(key) if value: @@ -391,7 +438,7 @@ def _fetch_cctv_upstream_response(request: Request, target_url: str, profile: _C next_parsed = urlparse(next_url) if next_parsed.scheme not in ("http", "https"): raise HTTPException(status_code=502, detail="Upstream redirect to non-HTTP scheme") - if not _cctv_host_allowed(next_parsed.hostname): + if not _cctv_host_allowed(next_parsed.hostname) or not _cctv_path_allowed(next_parsed): logger.warning( "CCTV upstream redirect to disallowed host [%s] %s -> %s", profile.name, current_url, next_url, @@ -426,7 +473,7 @@ def _rewrite_cctv_hls_playlist(base_url: str, body: str) -> str: parsed_target = urlparse(absolute) if parsed_target.scheme not in ("http", "https"): return candidate - if not _cctv_host_allowed(parsed_target.hostname): + if not _cctv_host_allowed(parsed_target.hostname) or not _cctv_path_allowed(parsed_target): return candidate return _proxied_cctv_url(absolute) @@ -521,8 +568,14 @@ def _proxy_cctv_media_response(request: Request, target_url: str): if "#EXTM3U" in body: body = _rewrite_cctv_hls_playlist(target_url, body) resp.close() - return Response(content=body, media_type=content_type, + if "#EXTM3U" not in body: + raise HTTPException(status_code=415, detail="Upstream did not return a playlist") + return Response(content=body, media_type="application/vnd.apple.mpegurl", headers=_cctv_response_headers(resp, cache_seconds=profile.cache_seconds, include_length=False)) + if not _cctv_media_type_allowed(content_type): + logger.warning("CCTV upstream non-media type [%s] %s: %s", profile.name, target_url, content_type) + resp.close() + raise HTTPException(status_code=415, detail="Upstream returned non-media content") return StreamingResponse(resp.iter_content(chunk_size=65536), status_code=resp.status_code, media_type=content_type, headers=_cctv_response_headers(resp, cache_seconds=profile.cache_seconds), @@ -535,7 +588,7 @@ async def cctv_media_proxy(request: Request, url: str = Query(...)): """Proxy CCTV media through the backend to bypass browser CORS restrictions.""" from urllib.parse import urlparse parsed = urlparse(url) - if not _cctv_host_allowed(parsed.hostname): + if not _cctv_host_allowed(parsed.hostname) or not _cctv_path_allowed(parsed): raise HTTPException(status_code=403, detail="Host not allowed") if parsed.scheme not in ("http", "https"): raise HTTPException(status_code=400, detail="Invalid scheme") diff --git a/backend/routers/infonet.py b/backend/routers/infonet.py index d742bf65..10befa2c 100644 --- a/backend/routers/infonet.py +++ b/backend/routers/infonet.py @@ -21,7 +21,9 @@ import logging import time from typing import Any -from fastapi import APIRouter, Body, Path +from fastapi import APIRouter, Body, Path, Request + +from limiter import limiter # Triggers the chain cutover at module-load time so registered # validators are live for any subsequent route invocation. @@ -491,7 +493,8 @@ def get_bootstrap_market_state(market_id: str = Path(...)) -> dict[str, Any]: # ─── Signed write: append an Infonet economy event ────────────────────── @router.post("/append") -def append_event(body: dict[str, Any] = Body(...)) -> dict[str, Any]: +@limiter.limit("30/minute") +def append_event(request: Request, body: dict[str, Any] = Body(...)) -> dict[str, Any]: """Append a signed Infonet economy event to the chain. Body shape (all required for production): diff --git a/backend/routers/mesh_public.py b/backend/routers/mesh_public.py index 302eb625..a54cddbd 100644 --- a/backend/routers/mesh_public.py +++ b/backend/routers/mesh_public.py @@ -18,6 +18,7 @@ from auth import ( _private_infonet_policy_snapshot, require_admin, require_local_operator, + is_local_operator_request, ) from limiter import limiter @@ -665,9 +666,30 @@ async def mesh_send(request: Request): except Exception: pass # Non-critical — don't block sends if reputation module fails - # ─── Per-identity throttle ──────────────────────────────────── + # ─── Public radio lanes are operator-only ──────────────────── + # A signed write proves who wrote the message, not that they may use + # this node's APRS-IS login or Meshtastic MQTT uplink. Anyone can mint + # a keypair, so radio transmission and the all-transport EMERGENCY + # broadcast require the node's own operator credential. priority_str = signed_payload["priority"] transport_lock = str(body.get("transport_lock", "") or "").lower() + is_operator = is_local_operator_request(request) + from services.meshtastic_mqtt_settings import mqtt_bridge_enabled + + allow_aprs = is_operator + allow_meshtastic = is_operator and mqtt_bridge_enabled() + if not is_operator and (priority_str == "emergency" or transport_lock in {"aprs", "meshtastic"}): + return JSONResponse( + status_code=403, + content={ + "ok": False, + "detail": "Radio transports and emergency broadcast require operator authentication", + }, + ) + if transport_lock == "meshtastic" and not allow_meshtastic: + return {"ok": False, "detail": "Meshtastic MQTT bridge is disabled"} + + # ─── Per-identity throttle ──────────────────────────────────── throttle_ok, throttle_reason = _check_throttle(node_id, priority_str, transport_lock) if not throttle_ok: return {"ok": False, "detail": throttle_reason} @@ -735,9 +757,19 @@ async def mesh_send(request: Request): "Private-tier content cannot be sent over APRS" )] else: - results = mesh_router.route(envelope, credentials) + results = mesh_router.route( + envelope, + credentials, + allow_aprs=allow_aprs, + allow_meshtastic=allow_meshtastic, + ) else: - results = mesh_router.route(envelope, credentials) + results = mesh_router.route( + envelope, + credentials, + allow_aprs=allow_aprs, + allow_meshtastic=allow_meshtastic, + ) any_ok = any(r.ok for r in results) # ─── Mirror to Meshtastic bridge feed ──────────────────────── diff --git a/backend/routers/road_corridors.py b/backend/routers/road_corridors.py index d5d9521b..74869b54 100644 --- a/backend/routers/road_corridors.py +++ b/backend/routers/road_corridors.py @@ -1,8 +1,9 @@ """Road corridor Sentinel-2 freight trend endpoints (opt-in slow layer).""" -from fastapi import APIRouter, HTTPException, Query, Request +from fastapi import APIRouter, Depends, HTTPException, Query, Request from pydantic import BaseModel, Field +from auth import require_local_operator from limiter import limiter from services.road_corridor_sat.config import optional_deps_available, road_corridor_sat_enabled from services.road_corridor_sat.credentials import sentinel_credentials_configured @@ -61,7 +62,7 @@ async def list_road_corridors(request: Request) -> dict: } -@router.post("/api/road-corridors/analyze") +@router.post("/api/road-corridors/analyze", dependencies=[Depends(require_local_operator)]) @limiter.limit("6/minute") async def analyze_road_corridor_here(request: Request, payload: AnalyzeRequest) -> dict: """Start an on-demand Sentinel-2 corridor analysis at map center.""" diff --git a/backend/routers/wormhole.py b/backend/routers/wormhole.py index d8b10fe3..a15fa08d 100644 --- a/backend/routers/wormhole.py +++ b/backend/routers/wormhole.py @@ -679,7 +679,7 @@ async def api_wormhole_join(request: Request): } -@router.post("/api/wormhole/leave") +@router.post("/api/wormhole/leave", dependencies=[Depends(require_local_operator)]) @limiter.limit("10/minute") async def api_wormhole_leave(request: Request): updated = write_wormhole_settings(enabled=False) diff --git a/backend/services/fetchers/airframes.py b/backend/services/fetchers/airframes.py index 3d47b415..58614c24 100644 --- a/backend/services/fetchers/airframes.py +++ b/backend/services/fetchers/airframes.py @@ -26,6 +26,11 @@ RETENTION_HOURS = max(6, int(os.environ.get("AIRFRAMES_RETENTION_HOURS", "48"))) REQUEST_PAUSE_S = float(os.environ.get("AIRFRAMES_REQUEST_PAUSE_S", "2.0")) PRIORITY_LOOKBACK_HOURS = max(6, int(os.environ.get("AIRFRAMES_PRIORITY_LOOKBACK_HOURS", "48"))) FETCH_TIMEOUT_S = max(5, int(os.environ.get("AIRFRAMES_FETCH_TIMEOUT_S", "20"))) +# Click-driven lookups jump the queue. Cap them so a crowd of map clicks can +# neither grow the queue without bound nor use the whole API budget and +# starve the bulk sync: at most this many per minute, and this many waiting. +ON_DEMAND_LOOKUPS_PER_MIN = max(1, int(os.environ.get("AIRFRAMES_ON_DEMAND_PER_MIN", "10"))) +ON_DEMAND_QUEUE_MAX = max(1, int(os.environ.get("AIRFRAMES_ON_DEMAND_QUEUE_MAX", "20"))) _DATA_DIR = Path(os.environ.get("SB_DATA_DIR", str(Path(__file__).resolve().parents[2] / "data"))) if not _DATA_DIR.is_absolute(): @@ -37,6 +42,7 @@ _queue_lock = threading.Lock() _worker_guard = threading.Lock() _queue: deque[dict[str, Any]] = deque() _queued_aircraft_keys: set[str] = set() +_on_demand_times: deque[float] = deque() _bulk_cursor: dict[str, Any] = {"since_iso": "", "before_id": None, "pages": 0} _worker_started = False _cache_loaded = False @@ -305,6 +311,15 @@ def _prioritize_aircraft_scan(entry: dict[str, str]) -> bool: item = {"type": "aircraft", **entry} with _queue_lock: + if key not in _queued_aircraft_keys: + # Re-ordering an already-queued aircraft costs no extra API call; + # only new lookups count against the per-minute budget. + now = time.monotonic() + while _on_demand_times and now - _on_demand_times[0] > 60.0: + _on_demand_times.popleft() + if len(_on_demand_times) >= ON_DEMAND_LOOKUPS_PER_MIN: + return False + _on_demand_times.append(now) kept: deque[dict[str, Any]] = deque() for queued in _queue: if queued.get("type") == "aircraft" and _aircraft_queue_key(queued) == key: @@ -315,6 +330,10 @@ def _prioritize_aircraft_scan(entry: dict[str, str]) -> bool: _queued_aircraft_keys.discard(key) _queued_aircraft_keys.add(key) _queue.appendleft(item) + aircraft_items = [queued for queued in _queue if queued.get("type") == "aircraft"] + for stale in aircraft_items[ON_DEMAND_QUEUE_MAX:]: + _queue.remove(stale) + _queued_aircraft_keys.discard(_aircraft_queue_key(stale)) return True diff --git a/backend/services/mesh/mesh_router.py b/backend/services/mesh/mesh_router.py index bf84a2b4..41a678d8 100644 --- a/backend/services/mesh/mesh_router.py +++ b/backend/services/mesh/mesh_router.py @@ -1085,10 +1085,19 @@ class MeshRouter: self._dedupe[key] = now return False - def route(self, envelope: MeshEnvelope, credentials: dict) -> list[TransportResult]: + def route( + self, + envelope: MeshEnvelope, + credentials: dict, + *, + allow_aprs: bool = True, + allow_meshtastic: bool = True, + ) -> list[TransportResult]: """Route a message through the optimal transport(s). Returns list of TransportResult (multiple for EMERGENCY broadcast). + ``allow_aprs`` / ``allow_meshtastic`` set to False keep the message off + that public radio lane (APRS-IS, Meshtastic MQTT). """ results: list[TransportResult] = [] # Sprint 2 / Rec #2 + #7: re-verify the envelope's trust_tier @@ -1137,6 +1146,10 @@ class MeshRouter: for transport in self.transports: if private_tier and transport.NAME in {"aprs", "meshtastic"}: continue + if transport.NAME == "aprs" and not allow_aprs: + continue + if transport.NAME == "meshtastic" and not allow_meshtastic: + continue if private_tier and transport.NAME == "internet": continue if transport.can_reach(envelope): @@ -1148,7 +1161,7 @@ class MeshRouter: return results # ─── Gate 2: APRS callsign target → APRS-IS ─────────────────── - if not private_tier and self.aprs.can_reach(envelope): + if allow_aprs and not private_tier and self.aprs.can_reach(envelope): # Check circuit breaker before sending cb_ok, cb_reason = self.breakers["aprs"].check_and_record(envelope.priority) if not cb_ok: @@ -1166,7 +1179,7 @@ class MeshRouter: results.append(r) # ─── Gate 3: Small payload → Meshtastic LoRa ────────────────── - if not private_tier and self.meshtastic.can_reach(envelope): + if allow_meshtastic and not private_tier and self.meshtastic.can_reach(envelope): # Check circuit breaker before sending cb_ok, cb_reason = self.breakers["meshtastic"].check_and_record(envelope.priority) if not cb_ok: diff --git a/backend/tests/mesh/test_mesh_endpoint_integrity.py b/backend/tests/mesh/test_mesh_endpoint_integrity.py index e2c97680..4c7d3e18 100644 --- a/backend/tests/mesh/test_mesh_endpoint_integrity.py +++ b/backend/tests/mesh/test_mesh_endpoint_integrity.py @@ -92,7 +92,7 @@ class _FakeMeshRouter: self.breakers = {"meshtastic": _DummyBreaker()} self.route_called = False - def route(self, _envelope, _credentials): + def route(self, _envelope, _credentials, **_kwargs): self.route_called = True return [] diff --git a/backend/tests/mesh/test_mesh_public_meshtastic_boundary.py b/backend/tests/mesh/test_mesh_public_meshtastic_boundary.py index b8c96ab8..b08b09d7 100644 --- a/backend/tests/mesh/test_mesh_public_meshtastic_boundary.py +++ b/backend/tests/mesh/test_mesh_public_meshtastic_boundary.py @@ -3,6 +3,18 @@ import time from collections import deque from types import SimpleNamespace +import pytest + + +@pytest.fixture(autouse=True) +def _reset_send_rate_limit(): + """This file posts to /api/mesh/send more often than its 10/minute limit.""" + from limiter import limiter + + limiter.reset() + yield + limiter.reset() + class _DummyBreaker: def check_and_record(self, _priority): @@ -33,11 +45,22 @@ class _FakeMeshRouter: self.breakers = {"meshtastic": _DummyBreaker()} self.route_called = False - def route(self, _envelope, _credentials): + def route(self, _envelope, _credentials, **kwargs): self.route_called = True + self.route_kwargs = kwargs return [] +def _operator_headers(monkeypatch, *, mqtt_enabled: bool = True) -> dict: + """Radio transports are operator-only: sign in and set the MQTT bridge.""" + import auth + from services import meshtastic_mqtt_settings + + monkeypatch.setattr(auth, "_current_admin_key", lambda: "test-admin") + monkeypatch.setattr(meshtastic_mqtt_settings, "mqtt_bridge_enabled", lambda: mqtt_enabled) + return {"X-Admin-Key": "test-admin"} + + def _valid_body(**overrides): body = { "destination": "!a0cc7a80", @@ -74,9 +97,11 @@ def test_meshtastic_transport_lock_stays_on_public_direct_path(monkeypatch): monkeypatch.setattr(mesh_router_mod, "mesh_router", fake_router) monkeypatch.setattr(sigint_grid, "mesh", fake_bridge) + headers = _operator_headers(monkeypatch) + async def _run(): async with AsyncClient(transport=ASGITransport(app=main.app), base_url="http://test") as ac: - response = await ac.post("/api/mesh/send", json=_valid_body()) + response = await ac.post("/api/mesh/send", json=_valid_body(), headers=headers) return response.json() result = asyncio.run(_run()) @@ -102,9 +127,11 @@ def test_meshtastic_transport_lock_does_not_fallback_when_unreachable(monkeypatc monkeypatch.setattr(main, "_check_throttle", lambda *_: (True, "ok")) monkeypatch.setattr(mesh_router_mod, "mesh_router", fake_router) + headers = _operator_headers(monkeypatch) + async def _run(): async with AsyncClient(transport=ASGITransport(app=main.app), base_url="http://test") as ac: - response = await ac.post("/api/mesh/send", json=_valid_body(message="x" * 10)) + response = await ac.post("/api/mesh/send", json=_valid_body(message="x" * 10), headers=headers) return response.json() result = asyncio.run(_run()) @@ -240,9 +267,11 @@ def test_private_tier_blocks_meshtastic_transport_lock(monkeypatch): monkeypatch.setattr(mesh_router_mod, "mesh_router", fake_router) monkeypatch.setattr(wormhole_supervisor, "get_transport_tier", lambda: "private_transitional") + headers = _operator_headers(monkeypatch) + async def _run(): async with AsyncClient(transport=ASGITransport(app=main.app), base_url="http://test") as ac: - response = await ac.post("/api/mesh/send", json=_valid_body()) + response = await ac.post("/api/mesh/send", json=_valid_body(), headers=headers) return response.json() result = asyncio.run(_run()) @@ -268,7 +297,7 @@ def test_envelope_trust_tier_set_from_wormhole_state(monkeypatch): self.meshtastic = _FakeMeshtasticTransport(can_reach=True, send_ok=True) self.breakers = {"meshtastic": _DummyBreaker()} - def route(self, envelope, _credentials): + def route(self, envelope, _credentials, **_kwargs): from services.mesh.mesh_router import TransportResult captured_envelopes.append(envelope) @@ -296,3 +325,125 @@ def test_envelope_trust_tier_set_from_wormhole_state(monkeypatch): assert result["ok"] is True assert len(captured_envelopes) == 1 assert captured_envelopes[0].trust_tier == "private_transitional" + + +def test_anonymous_signed_send_cannot_use_radio_transports(monkeypatch): + """A signed write proves authorship, not permission to use this node's + APRS-IS login or Meshtastic uplink: locks and EMERGENCY need the operator.""" + import main + from services.mesh import mesh_router as mesh_router_mod + from httpx import ASGITransport, AsyncClient + + fake_meshtastic = _FakeMeshtasticTransport(can_reach=True, send_ok=True) + fake_router = _FakeMeshRouter(fake_meshtastic) + + monkeypatch.setattr(main, "_verify_signed_write", lambda **_: (True, "ok")) + monkeypatch.setattr(main, "_check_throttle", lambda *_: (True, "ok")) + monkeypatch.setattr(mesh_router_mod, "mesh_router", fake_router) + + bodies = [ + _valid_body(), + _valid_body(transport_lock="aprs", destination="N0CALL"), + _valid_body(transport_lock="", priority="emergency"), + ] + + async def _run(): + out = [] + async with AsyncClient(transport=ASGITransport(app=main.app), base_url="http://test") as ac: + for body in bodies: + response = await ac.post("/api/mesh/send", json=body) + out.append((response.status_code, response.json())) + return out + + for status, result in asyncio.run(_run()): + assert status == 403 + assert result["ok"] is False + assert fake_meshtastic.sent == [] + assert fake_router.route_called is False + + +def test_anonymous_signed_send_routes_without_radio(monkeypatch): + import main + from services.mesh import mesh_router as mesh_router_mod + from httpx import ASGITransport, AsyncClient + + fake_router = _FakeMeshRouter(_FakeMeshtasticTransport()) + + monkeypatch.setattr(main, "_verify_signed_write", lambda **_: (True, "ok")) + monkeypatch.setattr(main, "_check_throttle", lambda *_: (True, "ok")) + monkeypatch.setattr(mesh_router_mod, "mesh_router", fake_router) + + body = _valid_body() + del body["transport_lock"] + + async def _run(): + async with AsyncClient(transport=ASGITransport(app=main.app), base_url="http://test") as ac: + return await ac.post("/api/mesh/send", json=body) + + asyncio.run(_run()) + + assert fake_router.route_called is True + assert fake_router.route_kwargs == {"allow_aprs": False, "allow_meshtastic": False} + + +def test_operator_meshtastic_lock_respects_mqtt_switch(monkeypatch): + import main + from services.mesh import mesh_router as mesh_router_mod + from httpx import ASGITransport, AsyncClient + + fake_meshtastic = _FakeMeshtasticTransport(can_reach=True, send_ok=True) + fake_router = _FakeMeshRouter(fake_meshtastic) + + monkeypatch.setattr(main, "_verify_signed_write", lambda **_: (True, "ok")) + monkeypatch.setattr(main, "_check_throttle", lambda *_: (True, "ok")) + monkeypatch.setattr(mesh_router_mod, "mesh_router", fake_router) + headers = _operator_headers(monkeypatch, mqtt_enabled=False) + + async def _run(): + async with AsyncClient(transport=ASGITransport(app=main.app), base_url="http://test") as ac: + response = await ac.post("/api/mesh/send", json=_valid_body(), headers=headers) + return response.json() + + result = asyncio.run(_run()) + + assert result["ok"] is False + assert "bridge is disabled" in result["detail"] + assert fake_meshtastic.sent == [] + + +def test_router_radio_switches_skip_aprs_and_meshtastic(monkeypatch): + from services.mesh import mesh_router + from services.mesh.mesh_router import MeshEnvelope, MeshRouter, Priority, TransportResult + + monkeypatch.setattr(mesh_router, "_supervisor_verified_trust_tier", lambda: "public_degraded") + + class _FakeTransport: + def __init__(self, name): + self.NAME = name + self.sent = [] + + def can_reach(self, _envelope): + return True + + def send(self, envelope, _credentials): + self.sent.append(envelope) + return TransportResult(True, self.NAME, "sent") + + router = MeshRouter() + router.aprs = _FakeTransport("aprs") + router.meshtastic = _FakeTransport("meshtastic") + router.internet = _FakeTransport("internet") + router.transports = [router.aprs, router.meshtastic, router.internet] + + for priority, payload in ((Priority.EMERGENCY, "help"), (Priority.NORMAL, "hello")): + envelope = MeshEnvelope( + sender_id="!sb_sender", + destination="N0CALL", + priority=priority, + payload=payload, + trust_tier="public_degraded", + ) + router.route(envelope, {}, allow_aprs=False, allow_meshtastic=False) + + assert router.aprs.sent == [] + assert router.meshtastic.sent == [] diff --git a/backend/tests/mesh/test_runtime_smoke_lane.py b/backend/tests/mesh/test_runtime_smoke_lane.py index cb94ef14..91cdd6ae 100644 --- a/backend/tests/mesh/test_runtime_smoke_lane.py +++ b/backend/tests/mesh/test_runtime_smoke_lane.py @@ -162,7 +162,7 @@ class _FakeMeshRouter: self.breakers = {"meshtastic": _DummyBreaker()} self.route_called = False - def route(self, _envelope, _credentials): + def route(self, _envelope, _credentials, **_kwargs): self.route_called = True return [] @@ -380,10 +380,18 @@ def test_runtime_smoke_public_meshtastic_send_route(monkeypatch): monkeypatch.setattr(main, "_check_throttle", lambda *_args: (True, "ok")) monkeypatch.setattr(mesh_router_mod, "mesh_router", fake_router) monkeypatch.setattr(sigint_grid, "mesh", fake_bridge) + # Radio transports are operator-only. + import auth + from services import meshtastic_mqtt_settings + + monkeypatch.setattr(auth, "_current_admin_key", lambda: "test-admin") + monkeypatch.setattr(meshtastic_mqtt_settings, "mqtt_bridge_enabled", lambda: True) async def _run(): async with AsyncClient(transport=ASGITransport(app=main.app), base_url="http://test") as ac: - response = await ac.post("/api/mesh/send", json=_meshtastic_send_body()) + response = await ac.post( + "/api/mesh/send", json=_meshtastic_send_body(), headers={"X-Admin-Key": "test-admin"} + ) return response.status_code, response.json() status_code, result = asyncio.run(_run()) diff --git a/backend/tests/mesh/test_signed_write_transport_matrix.py b/backend/tests/mesh/test_signed_write_transport_matrix.py index 9da630cc..b38c75d6 100644 --- a/backend/tests/mesh/test_signed_write_transport_matrix.py +++ b/backend/tests/mesh/test_signed_write_transport_matrix.py @@ -483,7 +483,7 @@ class _FakeMeshRouter: self.meshtastic = meshtastic self.breakers = {"meshtastic": _DummyBreaker()} - def route(self, _envelope, _credentials): + def route(self, _envelope, _credentials, **_kwargs): from services.mesh.mesh_router import TransportResult return [TransportResult(True, "internet", "sent")] @@ -517,6 +517,11 @@ def test_mesh_send_transport_lock_matrix(monkeypatch, tier, transport_lock, expe ) monkeypatch.setattr(main, "_check_throttle", lambda *_: (True, "ok")) monkeypatch.setattr(wormhole_supervisor, "get_transport_tier", lambda: tier) + # Radio locks are operator-only; this matrix covers the tier rules. + monkeypatch.setattr(main, "is_local_operator_request", lambda _request: True) + from services import meshtastic_mqtt_settings + + monkeypatch.setattr(meshtastic_mqtt_settings, "mqtt_bridge_enabled", lambda: True) monkeypatch.setattr(mesh_router_mod, "mesh_router", fake_router) monkeypatch.setattr(sigint_grid, "mesh", fake_bridge) diff --git a/backend/tests/test_airframes_datalink.py b/backend/tests/test_airframes_datalink.py index ac64ca2f..30487f5e 100644 --- a/backend/tests/test_airframes_datalink.py +++ b/backend/tests/test_airframes_datalink.py @@ -26,6 +26,7 @@ def airframes_env(tmp_path, monkeypatch): } airframes._queue.clear() airframes._queued_aircraft_keys.clear() + airframes._on_demand_times.clear() airframes._bulk_cursor = {"since_iso": "", "before_id": None, "pages": 0} airframes._cache_loaded = True airframes._api_key_known_configured = True diff --git a/backend/tests/test_control_surface_auth.py b/backend/tests/test_control_surface_auth.py index 54944d9a..3e675dd5 100644 --- a/backend/tests/test_control_surface_auth.py +++ b/backend/tests/test_control_surface_auth.py @@ -57,6 +57,12 @@ import pytest # identity-takeover surface as /identity/bootstrap. PR #227 hardened # the latter but missed the former. ("post", "/api/wormhole/join", {}), + ("post", "/api/wormhole/leave", {}), + # Joining the swarm changes this node's network participation. + ("post", "/api/mesh/infonet/swarm/join", {}), + # Corridor analysis runs Sentinel-2 jobs on the operator's imagery + # credentials. + ("post", "/api/road-corridors/analyze", {}), # /api/sigint/transmit relays APRS-IS packets over radio using # operator-supplied credentials. Any caller who reaches this endpoint # could transmit on the operator's authority. Must be local-only. diff --git a/backend/tests/test_endpoint_hardening.py b/backend/tests/test_endpoint_hardening.py new file mode 100644 index 00000000..0b49be05 --- /dev/null +++ b/backend/tests/test_endpoint_hardening.py @@ -0,0 +1,147 @@ +"""Regression coverage for public-endpoint hardening: CCTV relay limits, +the on-demand Airframes budget, and the AI channel loopback rule.""" + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch +from urllib.parse import urlparse + +import pytest +from fastapi import HTTPException + + +# --- CCTV relay ------------------------------------------------------------- + +def test_cctv_shared_storage_host_rejects_subdomains_and_other_paths(): + from routers.cctv import _cctv_host_allowed, _cctv_path_allowed + + tfl = "https://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk/00001.06514.mp4" + other_bucket = "https://s3-eu-west-1.amazonaws.com/someone-else/page.html" + + assert _cctv_host_allowed("s3-eu-west-1.amazonaws.com") + assert not _cctv_host_allowed("evil.s3-eu-west-1.amazonaws.com") + assert _cctv_path_allowed(urlparse(tfl)) + assert not _cctv_path_allowed(urlparse(other_bucket)) + # Ordinary camera hosts keep their subdomains and any path. + assert _cctv_host_allowed("strmr5.sha.maryland.gov") + assert _cctv_path_allowed(urlparse("https://images.data.gov.sg/any/path.jpg")) + + +@pytest.mark.parametrize( + ("content_type", "allowed"), + [ + ("image/jpeg", True), + ("video/mp4", True), + ("multipart/x-mixed-replace; boundary=frame", True), + ("application/octet-stream", True), + ("text/html; charset=utf-8", False), + ("image/svg+xml", False), + ("application/javascript", False), + ("application/xml", False), + ], +) +def test_cctv_media_type_filter(content_type, allowed): + from routers.cctv import _cctv_media_type_allowed + + assert _cctv_media_type_allowed(content_type) is allowed + + +def _upstream(content_type, text=""): + resp = MagicMock() + resp.status_code = 200 + resp.headers = {"Content-Type": content_type} + resp.text = text + resp.iter_content = MagicMock(return_value=iter([b""])) + return resp + + +def test_cctv_proxy_refuses_non_media_upstream(): + from routers import cctv + + with patch.object(cctv, "_fetch_cctv_upstream_response", return_value=_upstream("text/html")): + with pytest.raises(HTTPException) as exc: + cctv._proxy_cctv_media_response(MagicMock(), "https://images.data.gov.sg/cam") + assert exc.value.status_code == 415 + + +def test_cctv_proxy_refuses_playlist_without_extm3u(): + from routers import cctv + + upstream = _upstream("application/vnd.apple.mpegurl", text="") + with patch.object(cctv, "_fetch_cctv_upstream_response", return_value=upstream): + with pytest.raises(HTTPException) as exc: + cctv._proxy_cctv_media_response(MagicMock(), "https://video.deldot.gov/live/cam.m3u8") + assert exc.value.status_code == 415 + + +def test_cctv_proxy_media_response_sets_nosniff(): + from routers import cctv + + with patch.object(cctv, "_fetch_cctv_upstream_response", return_value=_upstream("image/jpeg")): + response = cctv._proxy_cctv_media_response(MagicMock(), "https://images.data.gov.sg/cam.jpg") + assert response.headers["X-Content-Type-Options"] == "nosniff" + + +# --- Airframes on-demand budget --------------------------------------------- + +@pytest.fixture +def airframes_queue(monkeypatch): + from services.fetchers import airframes + + airframes._queue.clear() + airframes._queued_aircraft_keys.clear() + airframes._on_demand_times.clear() + yield airframes + airframes._queue.clear() + airframes._queued_aircraft_keys.clear() + airframes._on_demand_times.clear() + + +def test_airframes_on_demand_lookups_are_rate_capped(airframes_queue, monkeypatch): + monkeypatch.setattr(airframes_queue, "ON_DEMAND_LOOKUPS_PER_MIN", 2) + + assert airframes_queue._prioritize_aircraft_scan({"icao24": "aaa111"}) + assert airframes_queue._prioritize_aircraft_scan({"icao24": "bbb222"}) + assert not airframes_queue._prioritize_aircraft_scan({"icao24": "ccc333"}) + # Re-clicking an aircraft that is already waiting costs nothing. + assert airframes_queue._prioritize_aircraft_scan({"icao24": "aaa111"}) + + +def test_airframes_on_demand_queue_is_bounded(airframes_queue, monkeypatch): + monkeypatch.setattr(airframes_queue, "ON_DEMAND_LOOKUPS_PER_MIN", 100) + monkeypatch.setattr(airframes_queue, "ON_DEMAND_QUEUE_MAX", 3) + + for i in range(6): + airframes_queue._prioritize_aircraft_scan({"icao24": f"abc{i:03d}"}) + + with airframes_queue._queue_lock: + waiting = [item["icao24"] for item in airframes_queue._queue if item.get("type") == "aircraft"] + keys = set(airframes_queue._queued_aircraft_keys) + # Newest clicks win; older ones drop out of the queue and the key set. + assert waiting == ["abc005", "abc004", "abc003"] + assert len(keys) == 3 + + +# --- AI channel WebSocket --------------------------------------------------- + +def _fake_ws(host): + return SimpleNamespace( + client=SimpleNamespace(host=host), + accept=AsyncMock(), + close=AsyncMock(), + ) + + +def test_ai_channel_ws_loopback_needs_hmac_when_loopback_untrusted(monkeypatch): + from routers import ai_intel + + monkeypatch.setenv("SHADOWBROKER_UNTRUSTED_LOOPBACK", "1") + verify = AsyncMock(return_value=False) + monkeypatch.setattr(ai_intel, "_verify_ws_hmac", verify) + ws = _fake_ws("127.0.0.1") + + asyncio.run(ai_intel.channel_websocket(ws)) + + verify.assert_awaited_once() + ws.close.assert_awaited_once() + assert ws.close.await_args.kwargs.get("code") == 4001 diff --git a/backend/tests/test_road_corridor_sat.py b/backend/tests/test_road_corridor_sat.py index f22dfc4b..99903bff 100644 --- a/backend/tests/test_road_corridor_sat.py +++ b/backend/tests/test_road_corridor_sat.py @@ -58,10 +58,12 @@ class TestAnalyzeHere: monkeypatch.setattr("routers.road_corridors.optional_deps_available", lambda: True) monkeypatch.setattr("routers.road_corridors.sentinel_credentials_configured", lambda: False) + monkeypatch.setattr("auth._current_admin_key", lambda: "test-admin") client = TestClient(app) resp = client.post( "/api/road-corridors/analyze", json={"lat": 27.51, "lon": -99.53}, + headers={"X-Admin-Key": "test-admin"}, ) assert resp.status_code == 503 @@ -77,10 +79,12 @@ class TestAnalyzeHere: return AnalyzeJob(job_id="job123", lat=lat, lon=lon, status="queued") monkeypatch.setattr("routers.road_corridors.enqueue_analyze", fake_enqueue) + monkeypatch.setattr("auth._current_admin_key", lambda: "test-admin") client = TestClient(app) resp = client.post( "/api/road-corridors/analyze", json={"lat": 27.51, "lon": -99.53}, + headers={"X-Admin-Key": "test-admin"}, ) assert resp.status_code == 200 body = resp.json() diff --git a/desktop-shell/tauri-skeleton/src-tauri/src/companion_server.rs b/desktop-shell/tauri-skeleton/src-tauri/src/companion_server.rs index 31b642e1..e7bc9a1d 100644 --- a/desktop-shell/tauri-skeleton/src-tauri/src/companion_server.rs +++ b/desktop-shell/tauri-skeleton/src-tauri/src/companion_server.rs @@ -240,6 +240,9 @@ fn operator_http_command(path: &str) -> Option<&'static str> { | "/api/mesh/reputation/all" | "/api/mesh/trust/vouches" | "/api/mesh/meshtastic/send" + | "/api/mesh/send" + | "/api/mesh/infonet/swarm/join" + | "/api/road-corridors/analyze" ) { return Some("settings.api_keys.get"); diff --git a/frontend/src/app/api/[...path]/route.ts b/frontend/src/app/api/[...path]/route.ts index b7c9e5b9..8aac39ff 100644 --- a/frontend/src/app/api/[...path]/route.ts +++ b/frontend/src/app/api/[...path]/route.ts @@ -82,6 +82,11 @@ function isSensitiveProxyPath(pathSegments: string[]): boolean { if (['mesh/infonet/session-stream', 'mesh/infonet/peer-registry', 'mesh/reputation/all', 'mesh/trust/vouches'].includes(joined)) return true; if (pathSegments[0] === 'mesh' && pathSegments[1] === 'oracle') return true; if (joined === 'mesh/meshtastic/send') return true; + // Public by design, but radio transports and emergency broadcast are + // operator-only on the backend, so forward the operator key when present. + if (joined === 'mesh/send') return true; + if (joined === 'mesh/infonet/swarm/join') return true; + if (joined === 'road-corridors/analyze') return true; // mesh/peers and all tools/* use require_local_operator on the backend and // need X-Admin-Key injected on the server-side proxy leg. if (pathSegments[0] === 'mesh' && pathSegments[1] === 'peers') return true;