# SPDX-License-Identifier: AGPL-3.0-only # Copyright (c) 2026 sol pbc from __future__ import annotations import io import json import sys from pathlib import Path from unittest.mock import MagicMock, patch import pytest import requests from cryptography.hazmat.primitives import serialization import solstone.think.utils as think_utils from solstone.observe import export from solstone.observe.export import UPLOAD_TIMEOUT from solstone.observe.peer_lookup import PeerInfo from solstone.observe.peer_unpair import maybe_prompt_unpair from solstone.observe.pl_http import PlHttpResponse, PlHttpSession from solstone.think.link.ca import cert_fingerprint, generate_ca def _set_journal(monkeypatch: pytest.MonkeyPatch, journal: Path) -> None: monkeypatch.setenv("SOLSTONE_JOURNAL", str(journal)) think_utils._journal_path_cache = None def _write_peer(journal: Path) -> PeerInfo: peer_dir = journal / "peers" / "12345678-1234-1234-1234-123456789abc" peer_dir.mkdir(parents=True) ca = generate_ca(peer_dir / "ca") cert_pem = ca.cert.public_bytes(serialization.Encoding.PEM).decode("ascii") peer = { "label": "host-a", "instance_id": "12345678-1234-1234-1234-123456789abc", "home_label": "solstone", "local_endpoints": [], } (peer_dir / "private.pem").write_text("private", encoding="utf-8") (peer_dir / "cert.pem").write_text(cert_pem, encoding="utf-8") (peer_dir / "chain.pem").write_text(cert_pem, encoding="utf-8") (peer_dir / "home_attestation.jwt").write_text("jwt", encoding="utf-8") (peer_dir / "peer.json").write_text(json.dumps(peer), encoding="utf-8") return PeerInfo( dir=peer_dir, instance_id=peer["instance_id"], label=peer["label"], local_endpoints=[], cert_fingerprint=cert_fingerprint(cert_pem), ) def _patch_exporters(monkeypatch: pytest.MonkeyPatch, calls: list[tuple]) -> None: from solstone.observe import export def make_exporter(area: str): def fake_export(base_url, key, *args, session=None): session.post(f"{base_url}/app/import/journal/{key[:8]}/ingest/{area}") calls.append(("area", area, session)) return export.ExportResult(area=area, sent=1) return fake_export monkeypatch.setattr(export, "export_segments", make_exporter("segments")) monkeypatch.setattr(export, "export_imports", make_exporter("imports")) monkeypatch.setattr(export, "export_entities", make_exporter("entities")) monkeypatch.setattr(export, "export_facets", make_exporter("facets")) monkeypatch.setattr(export, "export_config", make_exporter("config")) def _patch_tunnel( monkeypatch: pytest.MonkeyPatch, requests_seen: list[tuple[str, str, dict[str, str], bytes]], ) -> None: class FakeTunnelSession: @property def is_alive(self) -> bool: return True async def request(self, method, path, *, headers=None, body=b""): requests_seen.append((method, path, headers or {}, body)) return (200, {}, b'{"ok": true}') async def close(self) -> None: return None async def fake_open_tunnel(_identity, _relay_url, **_kwargs): return FakeTunnelSession() monkeypatch.setattr("solstone.think.link.dialer.open_tunnel", fake_open_tunnel) monkeypatch.setenv("SOL_LINK_RELAY_URL", "https://relay.test") def test_query_manifest_forwards_upload_timeout() -> None: class RecordingTunnel: def __init__(self) -> None: self.calls: list[tuple[str, str, dict[str, str], bytes, float | None]] = [] def request( self, method: str, path: str, *, headers: dict[str, str], body: bytes, timeout: float | None = None, ) -> tuple[int, dict[str, str], bytes]: self.calls.append((method, path, headers, body, timeout)) return 200, {}, b"{}" def close(self) -> None: return None tunnel = RecordingTunnel() session = PlHttpSession(tunnel) assert ( export._query_manifest( session, "https://pl.peer", "12345678-1234-1234-1234-123456789abc", ) == {} ) assert tunnel.calls == [ ( "GET", "/app/import/journal/12345678/manifest/segments", {"Host": "pl.peer"}, b"", UPLOAD_TIMEOUT, ) ] def test_export_pl_single_area_uses_pl_url_and_no_authorization( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: from solstone.observe import export journal = tmp_path / "journal" journal.mkdir() _set_journal(monkeypatch, journal) _write_peer(journal) area_calls: list[tuple] = [] requests_seen: list[tuple[str, str, dict[str, str], bytes]] = [] _patch_exporters(monkeypatch, area_calls) _patch_tunnel(monkeypatch, requests_seen) prompt_called = False def prompt(*_args, **_kwargs): nonlocal prompt_called prompt_called = True monkeypatch.setattr(export, "maybe_prompt_unpair", prompt) monkeypatch.setattr( sys, "argv", ["sol", "--to", "host-a", "--only", "entities", "--day", "20260520"], ) export.main() assert [call[1] for call in area_calls] == ["entities"] assert requests_seen[0][1] == "/app/import/journal/12345678/ingest/entities" assert "Authorization" not in requests_seen[0][2] assert prompt_called is False @pytest.mark.parametrize( "only_arg", [ None, "segments,imports,entities,facets,config", "entities,facets,segments,imports,config", ], ) def test_export_pl_full_pipeline_reuses_single_tunnel_and_prompts( only_arg: str | None, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: from solstone.observe import export journal = tmp_path / "journal" journal.mkdir() _set_journal(monkeypatch, journal) _write_peer(journal) area_calls: list[tuple] = [] requests_seen: list[tuple[str, str, dict[str, str], bytes]] = [] _patch_exporters(monkeypatch, area_calls) _patch_tunnel(monkeypatch, requests_seen) prompt_calls = 0 def prompt(*_args, **_kwargs): nonlocal prompt_calls prompt_calls += 1 monkeypatch.setattr(export, "maybe_prompt_unpair", prompt) argv = ["sol", "--to", "host-a", "--day", "20260520"] if only_arg is not None: argv.extend(["--only", only_arg]) monkeypatch.setattr(sys, "argv", argv) export.main() assert [call[1] for call in area_calls] == [ "segments", "imports", "entities", "facets", "config", ] assert [call[1] for call in requests_seen] == [ "/app/import/journal/12345678/ingest/segments", "/app/import/journal/12345678/ingest/imports", "/app/import/journal/12345678/ingest/entities", "/app/import/journal/12345678/ingest/facets", "/app/import/journal/12345678/ingest/config", ] assert prompt_calls == 1 def test_export_pl_partial_and_dry_run_do_not_prompt( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: from solstone.observe import export journal = tmp_path / "journal" journal.mkdir() _set_journal(monkeypatch, journal) _write_peer(journal) area_calls: list[tuple] = [] requests_seen: list[tuple[str, str, dict[str, str], bytes]] = [] _patch_exporters(monkeypatch, area_calls) _patch_tunnel(monkeypatch, requests_seen) prompt_calls = 0 def prompt(*_args, **_kwargs): nonlocal prompt_calls prompt_calls += 1 monkeypatch.setattr(export, "maybe_prompt_unpair", prompt) monkeypatch.setattr( sys, "argv", [ "sol", "--to", "host-a", "--only", "segments,entities", "--day", "20260520", ], ) export.main() assert [call[1] for call in area_calls] == ["segments", "entities"] assert prompt_calls == 0 monkeypatch.setattr( sys, "argv", ["sol", "--to", "host-a", "--dry-run", "--day", "20260520"], ) export.main() assert prompt_calls == 0 def test_export_url_with_key_refuses_without_network_contact( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: from solstone.observe import export journal = tmp_path / "journal" journal.mkdir() _set_journal(monkeypatch, journal) area_calls: list[tuple] = [] _patch_exporters(monkeypatch, area_calls) session_calls = 0 def session_factory(): nonlocal session_calls session_calls += 1 raise AssertionError("network contact") monkeypatch.setattr(export.requests, "Session", session_factory) monkeypatch.setattr( sys, "argv", [ "sol", "--to", "https://receiver.test", "--key", "api-key", "--day", "20260520", ], ) with pytest.raises(SystemExit) as exc: export.main() assert exc.value.code == 2 assert ( "Sending to a URL with a key is retired. " "Use '--to