"""Regression tests for collector auth_type, secret persistence, Space-Track config, and probes.""" from __future__ import annotations import asyncio import gzip from types import SimpleNamespace import httpx import pytest from httpx import ASGITransport, AsyncClient from sqlalchemy import create_engine, select from sqlalchemy.orm import sessionmaker from app.core.enums import AuthType from app.core.security import get_current_user from app.core.websocket.broadcaster import broadcaster from app.db.session import Base, get_db from app.main import app from app.models.collected_data import CollectedData from app.models.datasource import DataSource from app.models.datasource_config import DataSourceConfig from app.models.earth_news import EarthNewsItem from app.models.system_setting import SystemSetting from app.services import datasource_connectivity from app.services.collectors.base import BaseCollector from app.services.collectors.iptoasn import IPtoASNPrefixGeoCollector from app.services.collectors.spacetrack import SpaceTrackTLECollector class _SyncAsAsyncSession: def __init__(self, sync_session): self._s = sync_session def add(self, obj): return self._s.add(obj) async def execute(self, stmt, *args, **kwargs): return self._s.execute(stmt, *args, **kwargs) async def scalar(self, stmt, *args, **kwargs): return self._s.scalar(stmt, *args, **kwargs) async def get(self, model, ident): return self._s.get(model, ident) async def delete(self, obj): return self._s.delete(obj) async def commit(self): return self._s.commit() async def rollback(self): return self._s.rollback() async def refresh(self, obj): return self._s.refresh(obj) async def close(self): return self._s.close() def _make_db(): engine = create_engine("sqlite:///:memory:") Base.metadata.create_all( engine, tables=[ DataSourceConfig.__table__, DataSource.__table__, CollectedData.__table__, SystemSetting.__table__, EarthNewsItem.__table__, ], ) sync_factory = sessionmaker(engine, expire_on_commit=False) class _Ctx: def __call__(self): return self async def __aenter__(self): self._sess = _SyncAsAsyncSession(sync_factory()) return self._sess async def __aexit__(self, *_args): await self._sess.close() return engine, _Ctx() def _mock_httpx_factory(handler): real_async_client = httpx.AsyncClient transport = httpx.MockTransport(handler) def _factory(*_args, **kwargs): kwargs.pop("follow_redirects", None) kwargs["transport"] = transport return real_async_client(**kwargs) return _factory @pytest.mark.asyncio async def test_barentswatch_oauth_client_accepted_and_partial_update_preserves_secret(monkeypatch): assert AuthType.OAUTH_CLIENT.value == "oauth_client" engine, factory = _make_db() captured: dict = {} def handler(request: httpx.Request) -> httpx.Response: captured["urls"] = [*captured.get("urls", []), str(request.url)] if "barentswatch.no/connect/token" in str(request.url): captured["token_body"] = request.content.decode() return httpx.Response(200, json={"access_token": "tok_test_123"}) captured["auth_header"] = request.headers.get("Authorization") return httpx.Response(200, json=[]) monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler)) async def override_db(): async with factory() as session: yield session def override_user(): return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") app.dependency_overrides[get_db] = override_db app.dependency_overrides[get_current_user] = override_user try: async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: # 1. Create BarentsWatch config with auth_type=oauth_client (previously 422) create_resp = await client.post( "/api/v1/datasources/configs", json={ "name": "barentswatch_vessels", "source_type": "api", "endpoint": "https://live.ais.barentswatch.no/v1/latest/combined", "auth_type": "oauth_client", "auth_config": {"client_id": "id-1", "client_secret": "real-secret-1"}, }, ) assert create_resp.status_code == 200, create_resp.text cfg_id = create_resp.json()["id"] # 2. Partial PUT updating client_id (omitting masked client_secret) preserves real-secret-1 put_resp = await client.put( f"/api/v1/datasources/configs/{cfg_id}", json={ "endpoint": "https://live.ais.barentswatch.no/v1/latest/combined", "auth_type": "oauth_client", "auth_config": {"client_id": "id-2", "client_secret": "••••••••"}, }, ) assert put_resp.status_code == 200, put_resp.text async with factory() as db: row = (await db.execute(select(DataSourceConfig).where(DataSourceConfig.id == cfg_id))).scalar_one() assert row.auth_config["client_id"] == "id-2" assert row.auth_config["client_secret"] == "real-secret-1" # 3. Builtin connect with partial auth_config uses merged saved secret conn_resp = await client.post( "/api/v1/datasources/configs/builtin/connect", json={ "name": "barentswatch_vessels", "source_type": "api", "endpoint": "https://live.ais.barentswatch.no/v1/latest/combined", "auth_type": "oauth_client", "auth_config": {"client_id": "id-2"}, }, ) assert conn_resp.status_code == 200, conn_resp.text assert conn_resp.json()["success"] is True assert "client_secret=real-secret-1" in captured["token_body"] assert captured["auth_header"] == "Bearer tok_test_123" finally: app.dependency_overrides.clear() engine.dispose() @pytest.mark.asyncio async def test_spacetrack_collector_uses_saved_database_credentials(monkeypatch): engine, factory = _make_db() monkeypatch.delenv("SPACETRACK_USERNAME", raising=False) monkeypatch.delenv("SPACETRACK_PASSWORD", raising=False) monkeypatch.setattr(datasource_connectivity, "_read_zshrc_env", lambda: {}) posted: list[str] = [] def handler(request: httpx.Request) -> httpx.Response: if request.method == "POST" and "ajaxauth/login" in str(request.url): posted.append(request.content.decode()) return httpx.Response(200, text="{}") if request.method == "GET" and str(request.url).rstrip("/").endswith("space-track.org"): return httpx.Response(200, text="ok") return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}]) monkeypatch.setattr("app.services.collectors.spacetrack.httpx.AsyncClient", _mock_httpx_factory(handler)) try: async with factory() as db: db.add( DataSourceConfig( name="spacetrack_tle", source_type="api", endpoint="https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json", auth_type="basic", auth_config={"username": "db-user", "password": "db-password"}, is_active=True, ) ) await db.commit() collector = SpaceTrackTLECollector() collector._db_session = db collector._resolved_url = "https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json" rows = await collector.fetch() assert rows == [{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}] assert posted and "identity=db-user" in posted[0] and "password=db-password" in posted[0] finally: engine.dispose() @pytest.mark.asyncio async def test_builtin_connectivity_probes_match_collector_protocols(monkeypatch): seen_requests: list[tuple[str, dict[str, str]]] = [] def handler(request: httpx.Request) -> httpx.Response: url = str(request.url) seen_requests.append((url, dict(request.headers))) if "broker.bgpstream.caida.org" in url: if url.endswith("/v2"): return httpx.Response(404) return httpx.Response(200, json={"error": None, "data": {"resources": []}}) if "celestrak.org" in url: if "CATNR=25544" not in url: return httpx.Response(200, text='Invalid query: ""') return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544}]) if "services.arcgis.com" in url: if "f=json" not in url: return httpx.Response(200, text="ArcGIS HTML") return httpx.Response(200, json={"count": 42}) if "epoch.ai" in url: if url.endswith("gpu-clusters"): return httpx.Response(200, text="", headers={"content-type": "text/html"}) return httpx.Response(200, text="Name,Country,Status\nFrontier,USA,Active\n", headers={"content-type": "text/csv"}) if "ris-live.ripe.net" in url: assert "x-ris-subscribe" in request.headers return httpx.Response(200, text='{"type":"ris_message","data":{}}\n', headers={"content-type": "application/x-ndjson"}) return httpx.Response(404) monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler)) engine, factory = _make_db() try: async with factory() as db: for source, endpoint in [ ("bgpstream_bgp", "https://broker.bgpstream.caida.org/v2"), ("celestrak_tle", "https://celestrak.org/NORAD/elements/gp.php"), ("arcgis_cables", "https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query"), ("epoch_ai_gpu", "https://epoch.ai/data/gpu-clusters"), ("ris_live_bgp", "https://ris-live.ripe.net/v1/stream/?format=json&client=planet-ris-live"), ("media_news_archive", ""), ]: res = await datasource_connectivity.test_builtin_connectivity( source, endpoint, "none", {}, {"timeout": 10}, db=db ) assert res["success"] is True, (source, res) assert any("/v2/data?" in url and "intervals%5B%5D=" in url for url, _ in seen_requests) # Reject fake HTTP 200 responses when content fails validation (e.g., ArcGIS/CelesTrak bad params) bad_arcgis = await datasource_connectivity.test_builtin_connectivity( "arcgis_cables", "https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query?f=html", "none", {}, {"timeout": 10}, ) assert bad_arcgis["success"] is False bad_celestrak = await datasource_connectivity.test_builtin_connectivity( "celestrak_tle", "https://celestrak.org/NORAD/elements/gp.php?BAD=1", "none", {}, {"timeout": 10}, ) assert bad_celestrak["success"] is False finally: engine.dispose() class _StrictNonConcurrentSession: """Fake AsyncSession that fails immediately if commit() is entered concurrently.""" def __init__(self, task: SimpleNamespace) -> None: self.task = task self._in_commit = False self.active_commits = 0 self.max_concurrent_commits = 0 self.commit_count = 0 self.committed_progress: list[int] = [] async def commit(self) -> None: if self._in_commit: raise RuntimeError("concurrent operations are not permitted") self._in_commit = True self.active_commits += 1 self.max_concurrent_commits = max(self.max_concurrent_commits, self.active_commits) try: self.committed_progress.append(int(self.task.records_processed or 0)) await asyncio.sleep(0.01) self.commit_count += 1 finally: self.active_commits -= 1 self._in_commit = False def _make_task_stub(task_id: int = 29) -> SimpleNamespace: return SimpleNamespace( id=task_id, status="running", phase="downloading", phase_progress=0.0, phase_message="", phase_current=0, phase_total=0, phase_unit="bytes", progress=0.0, records_processed=0, total_records=0, started_at=None, completed_at=None, error_message=None, ) @pytest.mark.asyncio async def test_iptoasn_parallel_download_progress_serializes_db_commits(tmp_path, monkeypatch): v4_path = tmp_path / "ip2asn-v4.tsv.gz" v6_path = tmp_path / "ip2asn-v6.tsv.gz" with gzip.open(v4_path, "wt", encoding="utf-8") as f: f.write("1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET\n") with gzip.open(v6_path, "wt", encoding="utf-8") as f: f.write("2606:4700::\t2606:4700::ffff\t13335\tUS\tCLOUDFLARENET\n") async def _noop_broadcast(_payload): return None monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast) collector = IPtoASNPrefixGeoCollector() task = _make_task_stub(task_id=29) strict_session = _StrictNonConcurrentSession(task) collector._resolved_url = "https://iptoasn.com/data/ip2asn-combined.tsv.gz" collector._db_session = strict_session collector._current_task = task async def _fake_fetch_remote_info(_client, _url): return {"content_length": 10_000_000} async def _fake_download_dataset_file(_client, url, *, progress_callback=None): for step in (2_500_000, 5_000_000, 7_500_000, 10_000_000, 10_000_000): if progress_callback: await progress_callback(step, 10_000_000) await asyncio.sleep(0) return v4_path if "v4" in url else v6_path async def _no_short_circuit(_db, *, file_sha256): return None monkeypatch.setattr(collector._downloader, "fetch_remote_info", _fake_fetch_remote_info) monkeypatch.setattr(collector, "_download_dataset_file", _fake_download_dataset_file) monkeypatch.setattr(collector, "_can_short_circuit_unchanged_file", _no_short_circuit) rows = await collector.fetch() assert len(rows) == 2 assert {row["asn"] for row in rows} == {"13335"} assert strict_session.max_concurrent_commits == 1 assert strict_session.commit_count >= 2 assert strict_session.committed_progress == sorted(strict_session.committed_progress) assert collector._current_task.records_processed == 20_000_000 @pytest.mark.asyncio async def test_base_collector_serializes_concurrent_progress_and_phase_commits(monkeypatch): class _DummyCollector(BaseCollector): name = "dummy_concurrent_collector" async def fetch(self): return [] async def _noop_broadcast(_payload): return None monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast) collector = _DummyCollector() task = _make_task_stub(task_id=30) task.total_records = 10 strict_session = _StrictNonConcurrentSession(task) collector._current_task = task collector._db_session = strict_session await asyncio.gather( collector.update_progress(1, commit=True, force=True), collector.update_phase_progress(current=2, total=10, unit="rows", message="step 2", commit=True, force=True), collector.set_phase("downloading", message="step 3"), collector.update_progress(4, commit=True, force=True), collector.update_phase_progress(current=5, total=10, unit="rows", message="step 5", commit=True, force=True), collector.set_phase("parsing", message="step 6"), ) assert strict_session.max_concurrent_commits == 1 assert strict_session.commit_count == 6