diff --git a/backend/docs/CONFIGURATION.md b/backend/docs/CONFIGURATION.md index 752ea985c9..93b1f20cd5 100644 --- a/backend/docs/CONFIGURATION.md +++ b/backend/docs/CONFIGURATION.md @@ -1995,17 +1995,33 @@ With `approval: prompt`, a denied public domain becomes a Human Input card with **Deny**, **Allow temporarily**, and **Allow for this sandbox** choices. DeerFlow does not replay the failed command after approval because it may already have performed local side effects; the agent must retry it explicitly. Non-interactive -runs auto-deny without opening a card or waiting for input. The sidecar rejects -hostnames that policy does not allow before DNS resolution; allowed hostnames -that resolve to loopback, private, link-local, multicast, IPv6 ULA/site-local, -or cloud metadata destinations are rejected and can never be approved. This -screening also unwraps IPv6 spellings that carry an IPv4 destination — -IPv4-mapped, 6to4, NAT64 (`64:ff9b::/96`), IPv4-translated (`::ffff:0:0:0/96`), -and the deprecated IPv4-compatible form — and judges the embedded IPv4 -address, while NAT64 spellings of public IPv4 targets stay reachable. -The RFC 8215 local-use translation prefix (`64:ff9b:1::/48`) is rejected -explicitly. Operator-defined NAT64 prefixes outside `64:ff9b::/96` are not -recognized. +runs auto-deny without opening a card or waiting for input. + +The sidecar records denials in a fixed-size tmpfs, so it keeps that history +bounded: a sandbox can request an unlimited number of unique hosts, and a full +tmpfs would stop both denial recording and approval handling. Once the limit is +reached it drops denials that were superseded by another approval card, then +trims resolved history — ordered by when each decision was applied, so a card +answered just now is kept — to leave room for pending approvals. A card that is +currently awaiting a decision is never dropped, so a burst of unanswered cards +can exceed the limit, but reaching that needs one poll per tool call rather +than a flood. Persisted request fields are truncated (the method to 16 +characters), so the row limit also bounds the bytes on disk. Recording is best +effort: if the policy database cannot be read or written, the request is still +denied with the policy message instead of the connection being closed. A failed +policy lookup denies without recording, so a transient database error cannot +create an approval card for a destination that already holds a grant. + +The sidecar rejects hostnames that policy does not allow before DNS resolution; +allowed hostnames that resolve to loopback, private, link-local, multicast, +IPv6 ULA/site-local, or cloud metadata destinations are rejected and can never +be approved. This screening also unwraps IPv6 spellings that carry an IPv4 +destination — IPv4-mapped, 6to4, NAT64 (`64:ff9b::/96`), IPv4-translated +(`::ffff:0:0:0/96`), and the deprecated IPv4-compatible form — and judges the +embedded IPv4 address, while NAT64 spellings of public IPv4 targets stay +reachable. The RFC 8215 local-use translation prefix (`64:ff9b:1::/48`) is +rejected explicitly. Operator-defined NAT64 prefixes outside `64:ff9b::/96` +are not recognized. Raw TCP/UDP, Git-over-SSH, and other non-HTTP protocols remain unavailable in restricted modes. diff --git a/backend/packages/harness/deerflow/community/aio_sandbox/AGENTS.md b/backend/packages/harness/deerflow/community/aio_sandbox/AGENTS.md index 23b41506e1..c341b10bb0 100644 --- a/backend/packages/harness/deerflow/community/aio_sandbox/AGENTS.md +++ b/backend/packages/harness/deerflow/community/aio_sandbox/AGENTS.md @@ -77,6 +77,13 @@ make test-blocking-io egress. Reject a host that the policy denies before any DNS lookup. - **An approval never replays a tool call.** Subagent and non-interactive runs deny without asking. +- **Denial recording is bounded and best effort.** The sidecar's only writable + space is a 16 MiB tmpfs, and a sandbox can deny unlimited unique hosts, so + superseded and resolved events are pruned inside the recording transaction. + Retention orders resolved rows by when the decision was applied and reserves + room for pending approvals. A surfaced undecided row is a card the user is + looking at and survives pruning, and a policy-database failure still returns + a denial rather than closing the connection. - **Discovery and enumeration are read-only**, also when the policy or network mode does not match. Only the provider replaces a sandbox, under the teardown reservation and the cross-instance lease. The sandbox, its sidecar and both diff --git a/backend/packages/harness/deerflow/community/aio_sandbox/network_proxy.py b/backend/packages/harness/deerflow/community/aio_sandbox/network_proxy.py index 99612773d4..c523feb2cc 100644 --- a/backend/packages/harness/deerflow/community/aio_sandbox/network_proxy.py +++ b/backend/packages/harness/deerflow/community/aio_sandbox/network_proxy.py @@ -16,6 +16,7 @@ import json import os import socket import sqlite3 +import sys import time import uuid from pathlib import Path @@ -25,6 +26,18 @@ MAX_HEADER_BYTES = 65_536 POLICY_DB = Path(os.environ.get("DEERFLOW_POLICY_DB", "/tmp/deerflow-network-policy.sqlite3")) RELAY_AUTH_HEADER = "X-DeerFlow-Relay-Token" RELAY_TOKEN_ENV = "DEERFLOW_RELAY_TOKEN" +# The policy database lives on the proxy container's read-only root filesystem, +# whose only writable space is a 16 MiB /tmp tmpfs. Events are kept bounded so a +# sandbox that requests many unique hosts cannot fill that tmpfs and break +# denial recording and approval handling for the rest of its lifetime. At the +# real row size (roughly 140 bytes) this holds the database well under 1 MiB. +MAX_EVENTS = 4000 +# The request line has no token-length limit of its own, so a method can be +# nearly MAX_HEADER_BYTES long. Persisting it verbatim would let a few hundred +# rows fill the tmpfs long before MAX_EVENTS is reached. The longest standard +# method is CONNECT (7 characters); anything longer is kept only as a prefix +# for the approval card. +MAX_METHOD_CHARS = 16 class _InvalidHttpRequest(ValueError): @@ -54,10 +67,15 @@ def _connect_db() -> sqlite3.Connection: method TEXT NOT NULL, created_at REAL NOT NULL, surfaced INTEGER NOT NULL DEFAULT 0, - decision TEXT + decision TEXT, + decided_at REAL ) """ ) + # Databases created before decided_at existed keep their rows; retention + # falls back to created_at for them. + if "decided_at" not in {row[1] for row in db.execute("PRAGMA table_info(events)")}: + db.execute("ALTER TABLE events ADD COLUMN decided_at REAL") db.execute( """ CREATE TABLE IF NOT EXISTS grants ( @@ -169,8 +187,69 @@ def policy_allows(host: str, port: int, now: float | None = None) -> bool: return _is_granted(host, port, now) +def _prune_events(db: sqlite3.Connection) -> None: + """Bound the size of the events table so it cannot fill the /tmp tmpfs. + + Runs inside the caller's write transaction, so it adds no extra lock + acquisition against the Gateway's CLI reads of the same database. + + Rows fall into three classes, each pruned in its own step: + + * Superseded rows are noise. ``pending_events`` supersedes every unsurfaced + row it does not surface, so a flood of unique hosts collapses into one + card plus a batch of superseded rows. ``decide`` already reports ``False`` + for a superseded request, so dropping them up front changes no outcome. + This is what keeps the flood from crowding out real, still-undecided + denials. + * Decided rows are history. The newest ``MAX_EVENTS`` are kept, ordered by + when the decision was applied (``decided_at``), not when the destination + was denied: an old card answered just now must survive a resumed run + re-applying its decision. Pending approvals reserve capacity first, so a + full history trims itself rather than evicting an unsurfaced denial and + reversing the oldest-first order ``pending_events`` surfaces cards in. + * If the table is still over ``MAX_EVENTS`` after trimming history, drop + unsurfaced undecided rows oldest first. They have no open approval card. + + A row that has been surfaced but not yet decided is the card a user is + looking at. It is never deleted -- removing it would leave their decision + pointing at a request_id that no longer resolves, and enough of them to + matter requires one poll per tool call. + + Pruning runs before the insert so an already-full database recovers instead + of failing on every subsequent write. + """ + total = db.execute("SELECT COUNT(*) FROM events").fetchone()[0] + if total <= MAX_EVENTS: + return + db.execute("DELETE FROM events WHERE decision = 'superseded'") + # Pending approvals reserve capacity: trim resolved history to the room + # they leave, so a full history trims itself instead of evicting an + # unsurfaced denial and reversing the oldest-first order pending_events + # surfaces cards in. + pending = db.execute("SELECT COUNT(*) FROM events WHERE decision IS NULL").fetchone()[0] + keep_decided = max(MAX_EVENTS - pending, 0) + # History is ordered by when the decision was applied, so an old card + # answered just now survives a resumed run re-applying its decision. The + # most recent decision is always kept, even when pending rows alone fill + # the cap: deleting a just-applied decision would make its replay fail. + db.execute( + "DELETE FROM events WHERE decision IS NOT NULL AND request_id NOT IN (SELECT request_id FROM events WHERE decision IS NOT NULL ORDER BY COALESCE(decided_at, created_at) DESC LIMIT ?)", + (max(keep_decided, 1),), + ) + overflow = db.execute("SELECT COUNT(*) FROM events").fetchone()[0] - MAX_EVENTS + if overflow > 0: + db.execute( + "DELETE FROM events WHERE request_id IN ( SELECT request_id FROM events WHERE surfaced = 0 AND decision IS NULL ORDER BY created_at LIMIT ?)", + (overflow,), + ) + + def record_denial(host: str, port: int, method: str) -> str: now = time.time() + # Truncate before persisting so the row-count cap also bounds bytes: an + # oversized method stored verbatim could fill the tmpfs in a few hundred + # rows. The denial response itself is unaffected. + method = method[:MAX_METHOD_CHARS] with _connect_db() as db: # Serialize the read-before-insert deduplication so simultaneous proxy # requests cannot create multiple approval cards for one destination. @@ -181,6 +260,10 @@ def record_denial(host: str, port: int, method: str) -> str: ).fetchone() if recent is not None: return str(recent[0]) + # Prune after the deduplication lookup, before the insert: pruning first + # could drop the row this request should have matched, and pruning before + # the insert still lets an already-full database recover. + _prune_events(db) request_id = str(uuid.uuid4()) db.execute( "INSERT INTO events(request_id, host, port, method, created_at) VALUES (?, ?, ?, ?, ?)", @@ -204,7 +287,7 @@ def pending_events() -> list[dict[str, object]]: # One Human Input card makes one destination decision. Close any # sibling denials from the same tool call so a later retry records # a fresh event instead of leaving an invisible surfaced request. - db.execute("UPDATE events SET decision = 'superseded' WHERE surfaced = 0 AND decision IS NULL") + db.execute("UPDATE events SET decision = 'superseded', decided_at = ? WHERE surfaced = 0 AND decision IS NULL", (time.time(),)) if row is None: return [] return [{"request_id": row[0], "host": row[1], "port": row[2], "method": row[3], "created_at": row[4]}] @@ -214,7 +297,7 @@ def deny_pending_events() -> int: """Atomically deny every event that has not been surfaced to a user.""" with _connect_db() as db: db.execute("BEGIN IMMEDIATE") - result = db.execute("UPDATE events SET surfaced = 1, decision = 'deny' WHERE surfaced = 0 AND decision IS NULL") + result = db.execute("UPDATE events SET surfaced = 1, decision = 'deny', decided_at = ? WHERE surfaced = 0 AND decision IS NULL", (time.time(),)) return max(result.rowcount, 0) @@ -238,7 +321,7 @@ def decide(request_id: str, decision: str, ttl: int) -> bool: ) elif decision != "deny": return False - db.execute("UPDATE events SET decision = ? WHERE request_id = ?", (decision, request_id)) + db.execute("UPDATE events SET decision = ?, decided_at = ? WHERE request_id = ?", (decision, time.time(), request_id)) return True @@ -554,12 +637,29 @@ async def handle_proxy(reader: asyncio.StreamReader, writer: asyncio.StreamWrite else: await _reject(writer, "403 Forbidden", "IP-literal destinations are not allowed by sandbox network policy") return - if not policy_allows(host, port): + try: + allowed = policy_allows(host, port) + except sqlite3.Error as exc: + # The policy lookup reads grants and may rewrite an expired one, so it + # can fail when the tmpfs holding the database is full. Fail closed + # without recording: a transient lookup failure must not create an + # approval card for a destination that may already hold a grant, since + # answering it with "Allow temporarily" would replace a sandbox-lifetime + # grant with an expiring one. + print(f"network policy lookup for {host}:{port} failed: {exc}", file=sys.stderr) + await _reject(writer, "403 Forbidden", f"Sandbox network policy denied {host}:{port}") + return + if not allowed: + detail = "" if os.environ.get("DEERFLOW_RECORD_DENIALS") == "1": - request_id = record_denial(host, port, method) - detail = f" (request {request_id})" - else: - detail = "" + # Recording is best effort. An exception escaping this handler would + # close the connection without a response, so a sandbox would see a + # reset where the policy meant a clean denial. sqlite3 errors are not + # OSError subclasses, so catch them explicitly. + try: + detail = f" (request {record_denial(host, port, method)})" + except sqlite3.Error as exc: + print(f"network policy denial for {host}:{port} was not recorded: {exc}", file=sys.stderr) await _reject(writer, "403 Forbidden", f"Sandbox network policy denied {host}:{port}{detail}") return resolved = await resolve_public(host, port) diff --git a/backend/tests/test_aio_sandbox_network_proxy.py b/backend/tests/test_aio_sandbox_network_proxy.py index cdb87cfa00..2c5728afee 100644 --- a/backend/tests/test_aio_sandbox_network_proxy.py +++ b/backend/tests/test_aio_sandbox_network_proxy.py @@ -4,6 +4,7 @@ import asyncio import ipaddress import json import socket +import sqlite3 import ssl from unittest.mock import MagicMock @@ -457,3 +458,305 @@ async def test_http_proxy_rejects_ambiguous_field_names_before_policy_check(monk finally: proxy.close() await proxy.wait_closed() + + +@pytest.mark.anyio +async def test_denied_destination_still_gets_403_when_the_policy_database_fails(tmp_path, monkeypatch) -> None: + """A full policy database must degrade to a clean denial, not a bare reset. + + The proxy container's only writable space is a 16 MiB /tmp tmpfs, so the + policy database can fill up. An exception escaping ``handle_proxy`` closes + the connection with no response at all, which a sandbox cannot distinguish + from a network failure. The failure is injected at ``_connect_db`` so that + both database touch points are exercised: the policy lookup reads grants + (and may rewrite an expired one), and recording the denial writes a row. + """ + monkeypatch.setattr(network_proxy, "POLICY_DB", tmp_path / "policy.sqlite3") + monkeypatch.setenv("DEERFLOW_NETWORK_MODE", "allowlist") + monkeypatch.setenv("DEERFLOW_ALLOW_DOMAINS_JSON", json.dumps(["allowed.example"])) + monkeypatch.setenv("DEERFLOW_RECORD_DENIALS", "1") + + def full_database() -> None: + # sqlite3 errors are not OSError subclasses, so this is not caught by the + # handler's surrounding OSError handling. + raise sqlite3.OperationalError("database or disk is full") + + monkeypatch.setattr(network_proxy, "_connect_db", full_database) + + proxy = await asyncio.start_server(network_proxy.handle_proxy, "127.0.0.1", 0) + proxy_port = proxy.sockets[0].getsockname()[1] + try: + reader, writer = await asyncio.open_connection("127.0.0.1", proxy_port) + writer.write(b"CONNECT denied.example:443 HTTP/1.1\r\nHost: denied.example:443\r\n\r\n") + await writer.drain() + response = await asyncio.wait_for(reader.read(), timeout=2) + writer.close() + await writer.wait_closed() + + assert b"403 Forbidden" in response + assert b"Sandbox network policy denied denied.example:443" in response + # The request_id is unavailable, so it is omitted rather than invented. + assert b"(request " not in response + finally: + proxy.close() + await proxy.wait_closed() + + +def test_events_are_bounded_under_a_flood_of_unique_hosts(tmp_path, monkeypatch) -> None: + """Unique hosts each insert a row, so the cap is what bounds the table. + + The 30 second deduplication in ``record_denial`` only matches a repeated + host and port, and the policy check runs before DNS resolution, so a sandbox + needs no real network egress to produce unbounded undecided rows. + """ + monkeypatch.setattr(network_proxy, "POLICY_DB", tmp_path / "policy.sqlite3") + monkeypatch.setattr(network_proxy, "MAX_EVENTS", 50) + + for index in range(500): + network_proxy.record_denial(f"host-{index}.example", 443, "CONNECT") + + with network_proxy._connect_db() as db: + total = db.execute("SELECT COUNT(*) FROM events").fetchone()[0] + + # One row above the cap is the row the triggering insert just added. + assert total <= 51 + + +def test_pruning_keeps_decided_history_bounded_and_approvals_usable(tmp_path, monkeypatch) -> None: + monkeypatch.setattr(network_proxy, "POLICY_DB", tmp_path / "policy.sqlite3") + monkeypatch.setattr(network_proxy, "MAX_EVENTS", 5) + for index in range(30): + network_proxy.record_denial(f"host-{index}.example", 443, "CONNECT") + + denied = network_proxy.deny_pending_events() + assert denied > 0 + fresh = network_proxy.record_denial("fresh.example", 443, "CONNECT") + + with network_proxy._connect_db() as db: + total = db.execute("SELECT COUNT(*) FROM events").fetchone()[0] + decided = db.execute("SELECT COUNT(*) FROM events WHERE decision IS NOT NULL").fetchone()[0] + + # One row above the cap is the row the triggering insert just added. + assert total <= 6 + assert decided <= 5 + # The newest decided rows survive, and approvals still work after the flood. + assert [event["request_id"] for event in network_proxy.pending_events()] == [fresh] + + +def test_pruning_never_removes_a_card_a_user_is_currently_viewing(tmp_path, monkeypatch) -> None: + """A surfaced, undecided row is a live approval card and must survive pruning. + + Deleting it would leave the user's decision pointing at a request_id that no + longer resolves, so ``decide`` would silently return False on their click. + """ + monkeypatch.setattr(network_proxy, "POLICY_DB", tmp_path / "policy.sqlite3") + monkeypatch.setenv("DEERFLOW_NETWORK_MODE", "allowlist") + surfaced = network_proxy.record_denial("card.example", 443, "CONNECT") + assert [event["request_id"] for event in network_proxy.pending_events()] == [surfaced] + + monkeypatch.setattr(network_proxy, "MAX_EVENTS", 5) + for index in range(50): + network_proxy.record_denial(f"host-{index}.example", 443, "CONNECT") + + with network_proxy._connect_db() as db: + row = db.execute("SELECT surfaced, decision FROM events WHERE request_id = ?", (surfaced,)).fetchone() + + assert row == (1, None) + assert network_proxy.decide(surfaced, "allow_temporary", ttl=60) + assert network_proxy.policy_allows("card.example", 443) + + +def test_flood_does_not_evict_fresh_denials_or_break_deduplication(tmp_path, monkeypatch) -> None: + """Superseded flood rows must be pruned before real, undecided denials. + + ``pending_events`` supersedes every unsurfaced row it does not surface, so a + flood leaves a batch of superseded rows behind. If pruning instead dropped + the oldest undecided rows, a real denial recorded after the flood would be + deleted before ``pending_events`` could surface it, and the 30 second + deduplication would stop matching. + """ + monkeypatch.setattr(network_proxy, "POLICY_DB", tmp_path / "policy.sqlite3") + monkeypatch.setattr(network_proxy, "MAX_EVENTS", 100) + for index in range(300): + network_proxy.record_denial(f"noise-{index}.example", 443, "CONNECT") + network_proxy.pending_events() + + first = network_proxy.record_denial("pypi.org", 443, "CONNECT") + again = network_proxy.record_denial("pypi.org", 443, "CONNECT") + + assert again == first + assert [event["request_id"] for event in network_proxy.pending_events()] == [first] + + +@pytest.mark.anyio +async def test_oversized_method_is_truncated_in_storage_and_denials_stay_bounded(tmp_path, monkeypatch) -> None: + """The row cap only bounds bytes if persisted fields are bounded too. + + The request line has no token-length limit of its own, so a method can be + nearly MAX_HEADER_BYTES long. Stored verbatim, a few hundred such rows + would fill the 16 MiB tmpfs long before MAX_EVENTS is reached. The method + is truncated for storage; the denial response is unchanged. + """ + db_path = tmp_path / "policy.sqlite3" + monkeypatch.setattr(network_proxy, "POLICY_DB", db_path) + monkeypatch.setenv("DEERFLOW_NETWORK_MODE", "allowlist") + monkeypatch.setenv("DEERFLOW_ALLOW_DOMAINS_JSON", json.dumps(["allowed.example"])) + monkeypatch.setenv("DEERFLOW_RECORD_DENIALS", "1") + + oversized_method = b"X" * 60_000 + proxy = await asyncio.start_server(network_proxy.handle_proxy, "127.0.0.1", 0) + proxy_port = proxy.sockets[0].getsockname()[1] + try: + reader, writer = await asyncio.open_connection("127.0.0.1", proxy_port) + writer.write(oversized_method + b" http://denied.example/ HTTP/1.1\r\nHost: denied.example\r\n\r\n") + await writer.drain() + response = await asyncio.wait_for(reader.read(), timeout=2) + writer.close() + await writer.wait_closed() + + assert b"403 Forbidden" in response + assert b"Sandbox network policy denied denied.example:80" in response + finally: + proxy.close() + await proxy.wait_closed() + + with network_proxy._connect_db() as db: + stored = db.execute("SELECT method FROM events").fetchone()[0] + assert stored == "X" * network_proxy.MAX_METHOD_CHARS + + # A burst of oversized-method denials stays small on disk: the row cap and + # the field truncation together bound the bytes, not just the row count. + for index in range(300): + network_proxy.record_denial(f"host-{index}.example", 80, "X" * 60_000) + assert db_path.stat().st_size < 1_000_000 + + +def test_recently_answered_old_card_survives_history_pruning(tmp_path, monkeypatch) -> None: + """Resolved history must be ordered by when the decision was applied. + + An old card can be answered after newer cards. Ordering retention by the + denial timestamp would delete the just-applied decision on the next prune, + and a resumed run re-applying it would get False from decide() and raise. + """ + monkeypatch.setattr(network_proxy, "POLICY_DB", tmp_path / "policy.sqlite3") + monkeypatch.setattr(network_proxy, "MAX_EVENTS", 5) + monkeypatch.setenv("DEERFLOW_NETWORK_MODE", "allowlist") + + old = network_proxy.record_denial("old.example", 443, "CONNECT") + assert [event["request_id"] for event in network_proxy.pending_events()] == [old] + for index in range(10): + network_proxy.record_denial(f"newer-{index}.example", 443, "CONNECT") + network_proxy.deny_pending_events() + + # The old card is answered last, after all the newer decisions exist. + assert network_proxy.decide(old, "allow_temporary", ttl=60) + + pending = network_proxy.record_denial("pending.example", 443, "CONNECT") + assert [event["request_id"] for event in network_proxy.pending_events()] == [pending] + + # Exercise pruning with both a recent decision and an open approval card. + for index in range(20): + network_proxy.record_denial(f"flood-{index}.example", 443, "CONNECT") + + with network_proxy._connect_db() as db: + total = db.execute("SELECT COUNT(*) FROM events").fetchone()[0] + assert total <= network_proxy.MAX_EVENTS + 1 + + # The latest decision can still replay, and the open card is still decidable. + assert network_proxy.decide(old, "allow_temporary", ttl=60) + assert network_proxy.policy_allows("old.example", 443) + assert network_proxy.decide(pending, "deny", ttl=0) + + +def test_full_history_trims_itself_instead_of_evicting_pending_denials(tmp_path, monkeypatch) -> None: + """Pending approvals reserve capacity once resolved history fills the cap. + + With the cap full of decided rows, two denials arriving before the next + poll must both survive: evicting the older one would reverse the + oldest-first order pending_events() surfaces cards in. + """ + monkeypatch.setattr(network_proxy, "POLICY_DB", tmp_path / "policy.sqlite3") + monkeypatch.setattr(network_proxy, "MAX_EVENTS", 5) + + for index in range(10): + network_proxy.record_denial(f"history-{index}.example", 443, "CONNECT") + network_proxy.deny_pending_events() + + first = network_proxy.record_denial("first.example", 443, "CONNECT") + second = network_proxy.record_denial("second.example", 443, "CONNECT") + + # The oldest denial is surfaced first, and the newer one is superseded + # rather than silently deleted by pruning. + assert [event["request_id"] for event in network_proxy.pending_events()] == [first] + with network_proxy._connect_db() as db: + row = db.execute("SELECT decision FROM events WHERE request_id = ?", (second,)).fetchone() + assert row == ("superseded",) + + +def test_pre_decided_at_database_migrates_and_keeps_old_decisions(tmp_path, monkeypatch) -> None: + """A database created before decided_at existed must migrate on connect. + + CREATE TABLE IF NOT EXISTS does not add columns to an existing table, so + the sidecar adds decided_at explicitly. Old decided rows have no decision + timestamp; retention falls back to created_at for them and their replay + still resolves. + """ + db_path = tmp_path / "old.sqlite3" + legacy = sqlite3.connect(db_path) + legacy.execute("CREATE TABLE events (request_id TEXT PRIMARY KEY, host TEXT NOT NULL, port INTEGER NOT NULL, method TEXT NOT NULL, created_at REAL NOT NULL, surfaced INTEGER NOT NULL DEFAULT 0, decision TEXT)") + legacy.execute("INSERT INTO events VALUES ('r1', 'old.example', 443, 'CONNECT', 1.0, 1, 'allow_temporary')") + legacy.commit() + legacy.close() + + monkeypatch.setattr(network_proxy, "POLICY_DB", db_path) + monkeypatch.setattr(network_proxy, "MAX_EVENTS", 5) + for index in range(20): + network_proxy.record_denial(f"flood-{index}.example", 443, "CONNECT") + + with network_proxy._connect_db() as db: + columns = {row[1] for row in db.execute("PRAGMA table_info(events)")} + row = db.execute("SELECT decision, decided_at FROM events WHERE request_id = 'r1'").fetchone() + assert "decided_at" in columns + assert row == ("allow_temporary", None) + assert network_proxy.decide("r1", "allow_temporary", ttl=60) + + +@pytest.mark.anyio +async def test_lookup_failure_does_not_create_an_approval_card(tmp_path, monkeypatch) -> None: + """A transient lookup failure must not record a denial. + + Recording can succeed on a fresh connection after the lookup failed. The + destination may already hold a sandbox-lifetime grant, and answering the + spurious card with "Allow temporarily" would replace that grant with an + expiring one. Lookup errors fail closed without creating an event. + """ + monkeypatch.setattr(network_proxy, "POLICY_DB", tmp_path / "policy.sqlite3") + monkeypatch.setenv("DEERFLOW_NETWORK_MODE", "allowlist") + monkeypatch.setenv("DEERFLOW_ALLOW_DOMAINS_JSON", json.dumps([])) + monkeypatch.setenv("DEERFLOW_RECORD_DENIALS", "1") + + def failing_lookup(host: str, port: int) -> bool: + raise sqlite3.OperationalError("database is locked") + + monkeypatch.setattr(network_proxy, "policy_allows", failing_lookup) + + proxy = await asyncio.start_server(network_proxy.handle_proxy, "127.0.0.1", 0) + proxy_port = proxy.sockets[0].getsockname()[1] + try: + reader, writer = await asyncio.open_connection("127.0.0.1", proxy_port) + writer.write(b"CONNECT granted.example:443 HTTP/1.1\r\nHost: granted.example:443\r\n\r\n") + await writer.drain() + response = await asyncio.wait_for(reader.read(), timeout=2) + writer.close() + await writer.wait_closed() + + assert b"403 Forbidden" in response + assert b"Sandbox network policy denied granted.example:443" in response + assert b"(request " not in response + finally: + proxy.close() + await proxy.wait_closed() + + with network_proxy._connect_db() as db: + total = db.execute("SELECT COUNT(*) FROM events").fetchone()[0] + assert total == 0