Skip to content

Autonomous AI sales agent powered by Claude Code or Codex. Finds prospects, writes cold emails, sends campaigns, handles replies, books meetings. No API keys needed — runs on your Claude or Codex subscriptions.

fix: enforce public website and outreach approval boundaries

burkan28e67c61b278b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b1c5a75..f50453b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,13 @@ minor versions can still change behaviour.
### Fixed
+- Keep local website requests out of private networks, including redirects and
+ DNS rebinding. Preserve the original hostname for TLS verification.
+- Hold legacy Instantly campaign deployment and replies when approval is
+ required, instead of silently bypassing the setting. Instantly autopilot now
+ requires explicitly setting `channels.email.require_approval: false`.
+- Disable LinkedIn by default in the model, sample config, and product trainer;
+ save the setup wizard's explicit LinkedIn choice when updating a config.
- Protect the local dashboard with an access token, restrict requests to trusted
local origins, and save settings with owner-only permissions. Update and restart
Harvey, then open the dashboard link printed in your terminal.
diff --git a/README.md b/README.md
index 26099a9..df021ee 100644
--- a/README.md
+++ b/README.md
@@ -218,6 +218,12 @@ Cities geocode themselves (cached forever, one lookup each). Directories, aggreg
**Free.** Three HTTP requests per business. No browser, no model call. This is the highest value-per-effort stage in the whole system, because it produces the facts that make an email specific.
+Website requests from Scout, Profile, and the local training crawler are limited
+to public HTTP(S) destinations. Every DNS answer and redirect is checked; local,
+private, link-local, and metadata addresses are rejected. Connections use a
+validated IP while preserving the website's TLS identity. These website clients
+ignore environment proxies, so proxy routing cannot bypass that boundary.
+
Homepage, `robots.txt`, `sitemap.xml`, plus the team and careers pages when they exist — then regex over HTML already in hand. Out comes the incumbent agency, the ad pixels, the missing schema, the abandoned blog, the open roles, the named humans.
Agency detection is the compounding one. Almost every agency credits itself in the footer, and Harvey scores the wording: *"Powered by"* / *"Website by"* → 0.9 confidence; a bare descriptive link → 0.75; an unlabelled link → 0.35 and **not recorded**. A wrong incumbent in an email is worse than saying nothing.
@@ -327,6 +333,13 @@ Optionally, the same step can ask [Precleared](https://precleared.dev) whether c
When you trust it, set `channels.email.require_approval: false` for full autopilot.
+**Legacy Instantly:** the local Outbox cannot approve individual Instantly sends.
+With `require_approval: true`, Harvey holds campaign deployment (including
+activation retries) and routes replies to a human. Choose Gmail, Microsoft 365,
+or SMTP for the approval queue. Set `require_approval: false` explicitly to use
+Instantly's automatic sending. This does not pause campaigns already running
+on Instantly; manage those in Instantly itself.
+
---
## The dashboard
@@ -479,6 +492,10 @@ Harvey automates outreach, but **you are the sender.** Cold email is legal in mo
**LinkedIn.** Browser automation violates LinkedIn's ToS and can get the account restricted. Off by default. If you turn it on, use an account you can afford to lose.
+LinkedIn requires both `channels.linkedin.enabled: true` and configured
+credentials. Training a product does not enable it; the setup wizard records
+your explicit choice.
+
**Deliverability — warm up or burn out.** Sending cold email from your main domain, or at volume on day one, lands you in spam permanently.
1. Buy a **dedicated sending domain** (`getacme.com`, not `acme.com`).
diff --git a/harvey.yaml b/harvey.yaml
index 8c2f94b..8463521 100644
--- a/harvey.yaml
+++ b/harvey.yaml
@@ -49,11 +49,11 @@ channels:
enabled: true
provider: "gmail" # gmail (recommended) | microsoft | smtp | instantly
max_daily_sends: 50
- require_approval: true # native providers: emails wait in the Outbox
+ require_approval: true # native: review in Outbox; Instantly: sending held
send_to_risky: false # also send to catch-all domains (off = safest)
max_bounce_rate: 0.05 # pause all sending if bounces exceed this
linkedin:
- enabled: true
+ enabled: false # explicit opt-in; credentials alone do not enable it
max_daily_connections: 20
max_daily_messages: 10
diff --git a/harvey/agents/handler.py b/harvey/agents/handler.py
index bf31dcb..7b9f8e0 100644
--- a/harvey/agents/handler.py
+++ b/harvey/agents/handler.py
@@ -344,6 +344,18 @@ class Handler:
response, prospect, convo, reply_meta or {}, intent
)
elif reply_uuid:
+ if getattr(self.config.channels.email, "require_approval", True):
+ await self.state.update_conversation(convo.id, status="needs_human")
+ await self.state.log_action(
+ action_type="escalation", agent="handler",
+ details={"prospect_email": lead_email, "reason": "instantly_approval_required"},
+ )
+ logger.warning(
+ "Handler: Instantly reply held for human handling because "
+ "require_approval is true. Use a native provider for outbox "
+ "review, or explicitly disable require_approval for autopilot."
+ )
+ return
result = await self.instantly.send_reply(reply_uuid, response)
if result is not None:
# Add our response to conversation
diff --git a/harvey/agents/scout.py b/harvey/agents/scout.py
index 12f4ede..80e72f5 100644
--- a/harvey/agents/scout.py
+++ b/harvey/agents/scout.py
@@ -41,6 +41,7 @@ from harvey.integrations.email_finder import find_email, verify_published_addres
from harvey.integrations.linkedin import LinkedInAutomation
from harvey.models.company import Company
from harvey.models.prospect import COMPANY_INBOX_SOURCE, Prospect
+from harvey.public_http import public_http_client
from harvey.state import StateManager
logger = logging.getLogger("harvey.scout")
@@ -248,9 +249,7 @@ class Scout:
last_status = None
for attempt in range(retries):
try:
- async with httpx.AsyncClient(
- timeout=timeout, follow_redirects=True
- ) as client:
+ async with public_http_client(timeout=timeout) as client:
resp = await client.request(
method,
url,
diff --git a/harvey/agents/sender.py b/harvey/agents/sender.py
index 75653ad..d556014 100644
--- a/harvey/agents/sender.py
+++ b/harvey/agents/sender.py
@@ -126,6 +126,16 @@ class Sender:
async def _deploy_campaign(self, campaign):
"""Deploy a single campaign to Instantly. Idempotent: safe to retry."""
+ # Instantly owns campaign scheduling and has no per-message outbox
+ # approval here. Fail closed rather than silently bypass the setting,
+ # including retries of an already-created remote campaign.
+ if getattr(self.config.channels.email, "require_approval", True):
+ logger.warning(
+ "Sender: Instantly campaign held because require_approval is true. "
+ "Use a native mail provider for outbox review, or explicitly set "
+ "channels.email.require_approval: false for Instantly autopilot."
+ )
+ return
logger.info(f"Sender: Deploying campaign '{campaign.name}'...")
# 0. Validate before touching the network
diff --git a/harvey/collectors/profile.py b/harvey/collectors/profile.py
index 5c10652..4e9c855 100644
--- a/harvey/collectors/profile.py
+++ b/harvey/collectors/profile.py
@@ -18,6 +18,8 @@ from urllib.parse import urljoin, urlparse
import httpx
+from harvey.public_http import public_http_client
+
from harvey.collectors.discover import (
name_from_domain, name_matches_domain, site_name_from_html,
)
@@ -237,8 +239,8 @@ class ProfileCollector:
return code in self.confirmed
async def __aenter__(self):
- self._client = httpx.AsyncClient(
- timeout=TIMEOUT, follow_redirects=True,
+ self._client = public_http_client(
+ timeout=TIMEOUT,
headers={"User-Agent": random.choice(USER_AGENTS),
"Accept": "text/html,application/xhtml+xml,*/*;q=0.8"},
)
diff --git a/harvey/config.py b/harvey/config.py
index 642eb7d..b941929 100644
--- a/harvey/config.py
+++ b/harvey/config.py
@@ -79,9 +79,9 @@ class EmailChannelConfig(BaseModel):
# mailboxes. Off by default — catch-alls accept everything, so a bad
# guess still bounces.
send_to_risky: bool = False
- # Copilot mode (native providers): every outgoing email waits in the
- # outbox for your approval (dashboard → Outbox, or `harvey outbox`).
- # Set false for full autopilot once you trust the output.
+ # Native providers queue mail for approval. Instantly cannot use that
+ # outbox, so it holds campaigns and escalates replies while this is true.
+ # Set false explicitly for full autopilot once you trust the output.
require_approval: bool = True
# Kill switch: pause all sending when bounces exceed this fraction of
# sent mail (measured over the trailing sends). 0 disables the switch.
@@ -96,7 +96,7 @@ class EmailChannelConfig(BaseModel):
class LinkedInChannelConfig(BaseModel):
- enabled: bool = True
+ enabled: bool = False
max_daily_connections: int = 20
max_daily_messages: int = 10
diff --git a/harvey/public_http.py b/harvey/public_http.py
new file mode 100644
index 0000000..c459cb4
--- /dev/null
+++ b/harvey/public_http.py
@@ -0,0 +1,127 @@
+"""HTTP for untrusted public websites, with a boundary around the local network.
+
+Each request (including redirects) resolves and checks every address, then
+connects to a checked numeric IP. Host and TLS SNI retain the original domain.
+Checking DNS and then connecting to the hostname would allow DNS rebinding.
+Environment proxies are disabled so they cannot resolve or reroute the target.
+Fixed mail/API integrations keep their own clients and authentication settings.
+"""
+
+import asyncio
+import ipaddress
+import socket
+from time import monotonic
+
+import httpx
+
+
+class UnsafeURLError(httpx.RequestError):
+ """The requested destination is outside the public website boundary."""
+
+
+_TRANSLATION_NETWORKS = (
+ ipaddress.ip_network("64:ff9b::/96"),
+ ipaddress.ip_network("64:ff9b:1::/48"),
+)
+
+
+def _public_address(value: str) -> str:
+ """Reject special-use addresses, including IPv6 routes to embedded IPv4."""
+ if "%" in value:
+ raise ValueError("Scoped addresses are not public website targets")
+ address = ipaddress.ip_address(value)
+ if (not address.is_global or address.is_multicast or address.is_reserved
+ or address.is_unspecified):
+ raise ValueError("Address is not public")
+ if isinstance(address, ipaddress.IPv6Address):
+ if (address.is_site_local or address.ipv4_mapped or address.sixtofour or address.teredo
+ or any(address in network for network in _TRANSLATION_NETWORKS)):
+ raise ValueError("Translated IPv6 addresses are not supported")
+ return str(address)
+
+
+class PublicHTTPTransport(httpx.AsyncBaseTransport):
+ def __init__(self):
+ # Different domains may resolve to the same IP. Do not reuse a TLS
+ # connection checked for one domain for a different domain's request.
+ self._transport = httpx.AsyncHTTPTransport(
+ trust_env=False, limits=httpx.Limits(max_keepalive_connections=0),
+ )
+
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
+ url = request.url
+ host = url.raw_host.decode("ascii")
+ if (url.scheme not in {"http", "https"} or not host
+ or url.username or url.password or "%" in host
+ or host.rstrip(".").lower() == "localhost"
+ or host.rstrip(".").lower().endswith(".localhost")):
+ raise UnsafeURLError("Only public HTTP(S) websites are allowed", request=request)
+ port = url.port if url.port is not None else (443 if url.scheme == "https" else 80)
+ if not 1 <= port <= 65535:
+ raise UnsafeURLError("Invalid website port", request=request)
+ timeout = request.extensions.get("timeout", {}).get("connect")
+ connect_budget = timeout if timeout is not None else 10.0
+ deadline = monotonic() + connect_budget
+
+ try:
+ literal = ipaddress.ip_address(host)
+ except ValueError:
+ literal = None
+ try:
+ if literal is not None:
+ addresses = [_public_address(host)]
+ else:
+ # Include DNS time in the client's connect budget, with a
+ # finite default even if the caller disables other timeouts.
+ answers = await asyncio.wait_for(
+ asyncio.get_running_loop().getaddrinfo(host, port, type=socket.SOCK_STREAM),
+ timeout=connect_budget,
+ )
+ addresses = list(dict.fromkeys(_public_address(row[4][0]) for row in answers))
+ if not addresses:
+ raise ValueError("DNS returned no addresses")
+ # Many operator machines have no IPv6 route even when DNS
+ # publishes AAAA first. Prefer a validated IPv4 answer.
+ addresses.sort(key=lambda value: ipaddress.ip_address(value).version)
+ except ValueError as exc:
+ raise UnsafeURLError("Website resolves to a non-public destination", request=request) from exc
+ except asyncio.TimeoutError as exc:
+ raise httpx.ConnectTimeout("Website DNS resolution timed out", request=request) from exc
+ except OSError as exc:
+ raise httpx.ConnectError("Website DNS resolution failed", request=request) from exc
+
+ headers = request.headers.copy()
+ headers["Host"] = url.netloc.decode("ascii")
+ for index, address in enumerate(addresses):
+ remaining = deadline - monotonic()
+ if remaining <= 0:
+ raise httpx.ConnectTimeout("Website connection budget exhausted", request=request)
+ extensions = {
+ **request.extensions, "sni_hostname": host,
+ "timeout": {**request.extensions.get("timeout", {}), "connect": remaining},
+ }
+ pinned = httpx.Request(
+ method=request.method, url=url.copy_with(host=address),
+ headers=headers, stream=request.stream, extensions=extensions,
+ )
+ try:
+ return await self._transport.handle_async_request(pinned)
+ except (httpx.ConnectError, httpx.ConnectTimeout):
+ # The request stream has not been sent. Retry only connection
+ # establishment, never a read/write failure that could duplicate
+ # an API operation. Every candidate was validated above.
+ if index == len(addresses) - 1:
+ raise
+
+ async def aclose(self) -> None:
+ await self._transport.aclose()
+
+
+def public_http_client(
+ *, timeout: float | httpx.Timeout = 15.0, headers: dict[str, str] | None = None,
+) -> httpx.AsyncClient:
+ """A client whose every connection, redirect and TLS identity is checked."""
+ return httpx.AsyncClient(
+ transport=PublicHTTPTransport(), trust_env=False,
+ timeout=timeout, headers=headers, follow_redirects=True, max_redirects=10,
+ )
diff --git a/harvey/setup.py b/harvey/setup.py
index e6076a6..b6cd0a6 100644
--- a/harvey/setup.py
+++ b/harvey/setup.py
@@ -634,6 +634,10 @@ class SetupWizard:
existing = yaml.safe_load(f) or {}
existing["usage"] = self.config.get("usage", existing.get("usage", {}))
existing["brain"] = self.config["brain"]
+ if "LINKEDIN_EMAIL" in self.env_vars:
+ existing.setdefault("channels", {}).setdefault("linkedin", {})["enabled"] = bool(
+ self.env_vars["LINKEDIN_EMAIL"]
+ )
if "channels" in self.config:
existing.setdefault("channels", {})
if "email" in self.config["channels"]:
diff --git a/harvey/trainer.py b/harvey/trainer.py
index 354be9c..366318a 100644
--- a/harvey/trainer.py
+++ b/harvey/trainer.py
@@ -18,6 +18,7 @@ from dotenv import load_dotenv
from harvey.brain import Brain
from harvey.config import BrainConfig, load_brain_config
+from harvey.public_http import public_http_client
from harvey.state import StateManager
logger = logging.getLogger("harvey.trainer")
@@ -210,9 +211,8 @@ class FallbackCrawler:
# Queue starts with priority paths, then discovered links
queue: list[str] = [urljoin(base_url, p) for p in FALLBACK_PATHS]
- async with httpx.AsyncClient(
+ async with public_http_client(
timeout=15,
- follow_redirects=True,
headers={
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
@@ -762,7 +762,7 @@ What prospects do instead of buying a solution like ours:
"max_daily_sends": 50,
},
"linkedin": {
- "enabled": True,
+ "enabled": False,
"max_daily_connections": 20,
"max_daily_messages": 10,
},
diff --git a/tests/test_codex_e2e.py b/tests/test_codex_e2e.py
index a1f9c17..5c7832c 100644
--- a/tests/test_codex_e2e.py
+++ b/tests/test_codex_e2e.py
@@ -593,7 +593,8 @@ async def test_instantly_reply_survives_an_outage_while_drafting(harvey):
await harvey.state.init_db()
_, convo_id = await _open_thread(harvey.state)
- config = HarveyConfig(**{**BASE, "channels": {"email": {"provider": "instantly"}},
+ config = HarveyConfig(**{**BASE, "channels": {"email": {
+ "provider": "instantly", "require_approval": False}},
"brain": {"provider": "codex", "model": "gpt-5.5"}})
brain = Brain(harvey.state, config.brain)
handler = Handler(brain=brain, state=harvey.state, config=config, env=EnvConfig())
diff --git a/tests/test_public_http.py b/tests/test_public_http.py
new file mode 100644
index 0000000..c7fc95b
--- /dev/null
+++ b/tests/test_public_http.py
@@ -0,0 +1,287 @@
+"""Public website requests must never connect to local/network metadata services."""
+
+import socket
+
+import httpx
+import pytest
+import pytest_asyncio
+
+from harvey import public_http
+
+
+@pytest_asyncio.fixture
+async def wire(monkeypatch):
+ """Replace only the socket transport; leave the SSRF policy in place."""
+ seen = []
+ answers = {}
+ resolutions = []
+
+ async def resolve(host, port, **kwargs):
+ resolutions.append(host)
+ ips = answers.get(host, ["93.184.215.14"])
+ if isinstance(ips, Exception):
+ raise ips
+ return [(socket.AF_INET6 if ":" in ip else socket.AF_INET,
+ socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (ip, port)) for ip in ips]
+
+ import asyncio
+ monkeypatch.setattr(asyncio.get_running_loop(), "getaddrinfo", resolve)
+
+ def respond(request):
+ seen.append(request)
+ return httpx.Response(200, text="public website")
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport",
+ lambda **kwargs: httpx.MockTransport(respond))
+ return seen, answers, resolutions
+
+
+ "http://127.0.0.1/", "http://127.1/", "http://2130706433/",
+ "http://0x7f000001/", "http://0.0.0.0/", "http://10.0.0.1/",
+ "http://172.16.0.1/", "http://192.168.1.1/", "http://169.254.169.254/",
+ "http://100.100.100.200/", "http://224.0.0.1/", "http://255.255.255.255/",
+ "http://[::1]/", "http://[::]/", "http://[fe80::1]/", "http://[fd00::1]/",
+ "http://[fec0::1]/", "http://[feff::1]/",
+ "http://[::ffff:127.0.0.1]/", "http://[ff02::1]/",
+ "http://[64:ff9b::a9fe:a9fe]/", "http://[2002:7f00:1::]/",
+ "http://localhost/", "http://localhost./", "http://x.localhost/",
+ "https://user:[email protected]/", "ftp://public.test/file",
+])
+async def test_unsafe_targets_never_reach_the_network(url, wire):
+ seen, answers, _ = wire
+ # Non-canonical IPv4 forms are canonicalized by the system resolver.
+ answers.update({"127.1": ["127.0.0.1"], "2130706433": ["127.0.0.1"],
+ "0x7f000001": ["127.0.0.1"]})
+ async with public_http.public_http_client() as client:
+ with pytest.raises(httpx.RequestError):
+ await client.get(url)
+ assert seen == []
+
+
+ ["10.0.0.5"], ["93.184.215.14", "::1"], ["::ffff:192.168.0.1"], [],
+ ["93.184.215.14", "fec0::1"], socket.gaierror("name unavailable"),
+])
+async def test_dns_answers_fail_closed_including_mixed_public_private(ips, wire):
+ seen, answers, _ = wire
+ answers["public.test"] = ips
+ async with public_http.public_http_client() as client:
+ with pytest.raises(httpx.RequestError):
+ await client.get("https://public.test/")
+ assert seen == []
+
+
[email protected]("ip", ["93.184.215.14", "2606:4700:4700::1111"])
+async def test_dns_is_pinned_without_losing_host_sni_or_request_url(ip, wire):
+ seen, answers, resolutions = wire
+ answers["public.test"] = [ip]
+ async with public_http.public_http_client() as client:
+ response = await client.get("https://public.test:8443/a?q=1")
+ assert response.text == "public website"
+ assert seen[0].url.host == ip
+ assert seen[0].url.port == 8443 and seen[0].url.raw_path == b"/a?q=1"
+ assert seen[0].headers["host"] == "public.test:8443"
+ assert seen[0].extensions["sni_hostname"] == "public.test"
+ assert str(response.request.url) == "https://public.test:8443/a?q=1"
+ assert resolutions == ["public.test"] # connection uses the IP, no second DNS lookup
+
+
+async def test_redirects_are_revalidated_before_connecting(wire, monkeypatch):
+ seen, answers, resolutions = wire
+ answers["internal.test"] = ["169.254.169.254"]
+
+ def redirect(request):
+ seen.append(request)
+ return httpx.Response(302, headers={"location": "http://internal.test/latest"})
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport",
+ lambda **kwargs: httpx.MockTransport(redirect))
+ async with public_http.public_http_client() as client:
+ with pytest.raises(httpx.RequestError):
+ await client.get("https://public.test/")
+ assert len(seen) == 1
+ assert resolutions == ["public.test", "internal.test"]
+
+
+async def test_same_host_redirect_rechecks_dns_and_blocks_rebinding(wire, monkeypatch):
+ seen, answers, _ = wire
+
+ def rebind(request):
+ seen.append(request)
+ answers["public.test"] = ["127.0.0.1"]
+ return httpx.Response(302, headers={"location": "/private"})
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport",
+ lambda **kwargs: httpx.MockTransport(rebind))
+ async with public_http.public_http_client() as client:
+ with pytest.raises(httpx.RequestError):
+ await client.get("https://public.test/")
+ assert len(seen) == 1
+
+
+async def test_public_redirects_work_and_do_not_forward_authorization(wire, monkeypatch):
+ seen, _, _ = wire
+
+ def redirect(request):
+ seen.append(request)
+ if len(seen) == 1:
+ return httpx.Response(302, headers={"location": "https://other.test/page"})
+ return httpx.Response(200, text="arrived")
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport",
+ lambda **kwargs: httpx.MockTransport(redirect))
+ async with public_http.public_http_client() as client:
+ response = await client.get("https://public.test/", headers={"Authorization": "Bearer test"})
+ assert response.text == "arrived"
+ assert seen[1].headers["host"] == "other.test"
+ assert "authorization" not in seen[1].headers
+ assert str(response.url) == "https://other.test/page"
+
+
+async def test_clients_cannot_bypass_policy_using_environment_proxies(wire, monkeypatch):
+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9999")
+ async with public_http.public_http_client() as client:
+ response = await client.get("https://public.test/")
+ assert response.status_code == 200 and len(wire[0]) == 1
+
+
+async def test_production_transport_disables_cross_host_ip_pool_reuse(monkeypatch):
+ options = {}
+
+ def transport(**kwargs):
+ options.update(kwargs)
+ return httpx.MockTransport(lambda request: httpx.Response(200))
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport", transport)
+ async with public_http.public_http_client():
+ pass
+ assert options["limits"].max_keepalive_connections == 0
+ assert options["trust_env"] is False
+
+
+async def test_ipv4_is_preferred_when_both_address_families_are_published(wire):
+ seen, answers, _ = wire
+ answers["public.test"] = ["2606:4700:4700::1111", "93.184.215.14"]
+ async with public_http.public_http_client() as client:
+ await client.get("https://public.test/")
+ assert seen[0].url.host == "93.184.215.14"
+
+
+async def test_dns_timeout_is_reported_as_connect_timeout(wire):
+ wire[1]["public.test"] = TimeoutError("slow DNS")
+ async with public_http.public_http_client() as client:
+ with pytest.raises(httpx.ConnectTimeout):
+ await client.get("https://public.test/")
+ assert wire[0] == []
+
+
+async def test_connect_failure_tries_other_validated_addresses(wire, monkeypatch):
+ seen, answers, _ = wire
+ answers["public.test"] = ["93.184.215.14", "2606:4700:4700::1111"]
+
+ def respond(request):
+ seen.append(request)
+ if len(seen) == 1:
+ raise httpx.ConnectError("unreachable", request=request)
+ return httpx.Response(200, text="reachable")
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport",
+ lambda **kwargs: httpx.MockTransport(respond))
+ async with public_http.public_http_client() as client:
+ response = await client.get("https://public.test/")
+ assert response.text == "reachable"
+ assert [r.url.host for r in seen] == answers["public.test"]
+
+
[email protected]("error", [httpx.ConnectError, httpx.ConnectTimeout])
+async def test_address_fallback_shares_one_connect_budget(wire, monkeypatch, error):
+ seen, answers, _ = wire
+ answers["public.test"] = ["93.184.215.14", "93.184.215.15"]
+ times = iter([0.0, 0.2, 0.7])
+ monkeypatch.setattr(public_http, "monotonic", lambda: next(times))
+
+ def respond(request):
+ seen.append(request)
+ if len(seen) == 1:
+ raise error("unreachable", request=request)
+ return httpx.Response(200)
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport",
+ lambda **kwargs: httpx.MockTransport(respond))
+ async with public_http.public_http_client(timeout=1.0) as client:
+ assert (await client.get("https://public.test/")).status_code == 200
+ assert seen[0].extensions["timeout"]["connect"] == pytest.approx(0.8)
+ assert seen[1].extensions["timeout"]["connect"] == pytest.approx(0.3)
+
+
+async def test_address_fallback_stops_when_connect_budget_is_spent(wire, monkeypatch):
+ seen, answers, _ = wire
+ answers["public.test"] = ["93.184.215.14", "93.184.215.15"]
+ times = iter([0.0, 0.2, 1.1])
+ monkeypatch.setattr(public_http, "monotonic", lambda: next(times))
+
+ def fail(request):
+ seen.append(request)
+ raise httpx.ConnectTimeout("slow connection", request=request)
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport",
+ lambda **kwargs: httpx.MockTransport(fail))
+ async with public_http.public_http_client(timeout=1.0) as client:
+ with pytest.raises(httpx.ConnectTimeout):
+ await client.get("https://public.test/")
+ assert len(seen) == 1
+
+
+async def test_write_failures_are_never_replayed_to_another_address(wire, monkeypatch):
+ seen, answers, _ = wire
+ answers["public.test"] = ["93.184.215.14", "93.184.215.15"]
+
+ def fail(request):
+ seen.append(request)
+ raise httpx.WriteError("connection lost after sending", request=request)
+
+ monkeypatch.setattr(public_http.httpx, "AsyncHTTPTransport",
+ lambda **kwargs: httpx.MockTransport(fail))
+ async with public_http.public_http_client() as client:
+ with pytest.raises(httpx.WriteError):
+ await client.post("https://public.test/", json={"query": "roofers"})
+ assert len(seen) == 1
+
+
+async def test_public_ip_literal_is_checked_without_dns(wire):
+ async with public_http.public_http_client() as client:
+ assert (await client.get("https://93.184.215.14/")).status_code == 200
+ assert wire[2] == []
+
+
[email protected]("caller", ["scout", "profile", "trainer"])
+async def test_real_website_callers_block_private_targets(caller, wire):
+ if caller == "scout":
+ from harvey.agents.scout import Scout
+ scout = Scout.__new__(Scout)
+ assert await scout._fetch("http://127.0.0.1/", retries=1) is None
+ elif caller == "profile":
+ from harvey.collectors.profile import ProfileCollector
+ async with ProfileCollector(None) as collector:
+ assert await collector._get("http://127.0.0.1/") == ""
+ else:
+ from harvey.trainer import FallbackCrawler
+ assert await FallbackCrawler().crawl("http://127.0.0.1/", max_pages=1) == {}
+ assert wire[0] == []
diff --git a/tests/test_security_defaults.py b/tests/test_security_defaults.py
new file mode 100644
index 0000000..f337e39
--- /dev/null
+++ b/tests/test_security_defaults.py
@@ -0,0 +1,111 @@
+"""Approval requirements apply to legacy providers; LinkedIn needs opt-in."""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+import pytest_asyncio
+import yaml
+
+from harvey.agents.handler import Handler
+from harvey.agents.sender import Sender
+from harvey.config import BrainConfig, EnvConfig, LinkedInChannelConfig
+from harvey.models.campaign import Campaign, EmailStep
+from harvey.models.prospect import Prospect
+from harvey.paths import PROJECT_ROOT
+from harvey.state import StateManager
+from harvey.trainer import Trainer
+
+
+@pytest_asyncio.fixture
+async def state(tmp_path):
+ state = StateManager(str(tmp_path / "test.db"))
+ await state.init_db()
+ return state
+
+
+def legacy_config(require_approval=True):
+ return SimpleNamespace(
+ channels=SimpleNamespace(email=SimpleNamespace(
+ enabled=True, provider="instantly", require_approval=require_approval,
+ max_daily_sends=50, send_to_risky=False)),
+ persona=SimpleNamespace(name="Harvey", role="BDR", company="Acme", tone="direct"),
+ product=SimpleNamespace(name="Widget", description="A widget", objection_responses={}),
+ )
+
+
+async def test_legacy_campaign_requires_explicit_autopilot_even_on_activation_retry(state):
+ sender = Sender(None, state, legacy_config(), EnvConfig())
+ sender.instantly = AsyncMock()
+ campaign = Campaign(id="c", name="Draft", instantly_campaign_id="existing-campaign",
+ sequence=[EmailStep(step=1, subject="a note", body="Would this help?")])
+ await sender._deploy_campaign(campaign)
+ assert sender.instantly.mock_calls == []
+
+
+async def test_legacy_campaign_autopilot_is_still_available(state):
+ sender = Sender(None, state, legacy_config(False), EnvConfig())
+ sender.instantly = AsyncMock()
+ sender.instantly.create_campaign.return_value = None
+ campaign = Campaign(id="c", name="Draft",
+ sequence=[EmailStep(step=1, subject="a note", body="Would this help?")])
+ await sender._deploy_campaign(campaign)
+ sender.instantly.create_campaign.assert_awaited_once_with("Draft")
+
+
[email protected]("require_approval", [True, False])
+async def test_legacy_replies_respect_approval_and_record_inbound_messages(state, require_approval):
+ pid = await state.add_prospect(Prospect(first_name="Jane", last_name="Doe", company="Acme",
+ title="Owner", email="[email protected]"))
+ handler = Handler(None, state, legacy_config(require_approval), EnvConfig())
+ handler.instantly = AsyncMock()
+ handler._classify_intent = AsyncMock(return_value="question")
+ handler._generate_response = AsyncMock(return_value="Happy to help.")
+ await handler._process_reply("[email protected]", "What does it cost?", "reply-id")
+ if require_approval:
+ handler.instantly.send_reply.assert_not_awaited()
+ [convo] = await state.get_conversations_by_status("needs_human")
+ assert convo.prospect_id == pid and convo.thread[-1].content == "What does it cost?"
+ else:
+ handler.instantly.send_reply.assert_awaited_once_with("reply-id", "Happy to help.")
+
+
+async def test_legacy_opt_out_is_honored_even_when_approval_blocks_sending(state):
+ pid = await state.add_prospect(Prospect(first_name="Jane", last_name="Doe", title="Owner",
+ email="[email protected]"))
+ handler = Handler(None, state, legacy_config(), EnvConfig())
+ handler.instantly = AsyncMock()
+ await handler._process_reply("[email protected]", "Please unsubscribe me", "reply-id")
+ assert (await state.get_prospect(pid)).status == "opted_out"
+ handler.instantly.send_reply.assert_not_awaited()
+
+
+def test_linkedin_is_disabled_in_model_and_shipped_template():
+ assert LinkedInChannelConfig().enabled is False
+ template = yaml.safe_load((PROJECT_ROOT / "harvey.yaml").read_text())
+ assert template["channels"]["linkedin"]["enabled"] is False
+ assert LinkedInChannelConfig(enabled=True).enabled is True
+
+
+def test_product_training_does_not_enable_linkedin():
+ trainer = Trainer.__new__(Trainer)
+ trainer.brain_config = BrainConfig()
+ config = trainer._build_config({}, {}, {}, "acme.test")
+ assert config["channels"]["linkedin"]["enabled"] is False
+
+
[email protected]("enabled", [False, True])
+def test_setup_saves_explicit_linkedin_choice_for_existing_config(tmp_path, monkeypatch, enabled):
+ from harvey import setup
+ path = tmp_path / "harvey.yaml"
+ path.write_text(yaml.safe_dump({"channels": {"linkedin": {"enabled": not enabled}}}))
+ monkeypatch.setattr(setup, "CONFIG_FILE", path)
+ wizard = setup.SetupWizard()
+ wizard.env_vars["LINKEDIN_EMAIL"] = "[email protected]" if enabled else ""
+ wizard.config = {"channels": {"linkedin": {"enabled": enabled}}}
+ wizard._write_config()
+ assert yaml.safe_load(path.read_text())["channels"]["linkedin"]["enabled"] is enabled