fix(app): collection connects only to the addresses it checked, within 15 s, logging no address

- the fetcher resolves once, requires every address to be public and connects only to those
  (TLS still checks the name), so DNS rebinding cannot reach the local network; redirects too
- 15 s for the whole fetch also against servers that send slowly; no URL in any log line
- a site whose title alone changed is kept again
- target names that differ only in case are refused (one Windows folder)
- the worker always gets the collection file, so results older than the keep days go also
  with no targets or the feature off
- the results screen lists every target with results, not only those in the newest 100

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-13 21:39:04 +09:00
parent b94e9dc112
commit 9185265010
10 changed files with 273 additions and 66 deletions

View File

@@ -8,13 +8,18 @@ and nothing collected reaches the log.
from __future__ import annotations
import http.server
import ipaddress
import json
import socket
import threading
import time
from datetime import datetime, timedelta
from pathlib import Path
import pytest
import voice_worker.collect as collect
from voice_worker.collect import Collector, load_config, safe_get
RSS = """<?xml version="1.0"?><rss version="2.0"><channel><title>feed</title>
@@ -131,6 +136,17 @@ def test_a_site_is_kept_only_when_it_changed(tmp_path):
assert [i["text"] for i in items(tmp_path, "site")] == ["Version 1 is out", "Version 2 is out"]
def test_a_site_whose_title_alone_changed_is_kept_again(tmp_path):
page = "<html><head><title>{t}</title></head><body><p>Same body text</p></body></html>"
fake = Fake({"https://s.example/": page.format(t="Old")})
c = Collector(config(tmp_path, [{"name": "site", "kind": "site", "value": "https://s.example/", "everyMinutes": 15}]),
fetch=fake)
c.run_due(now=0.0)
fake.pages["https://s.example/"] = page.format(t="New")
c.run_due(now=900.0)
assert [i["title"] for i in items(tmp_path, "site")] == ["Old", "New"]
def test_a_target_runs_again_only_after_its_interval_also_after_a_restart(tmp_path):
fake = Fake({"https://s.example/": PAGE.format(v=1)})
targets = [{"name": "site", "kind": "site", "value": "https://s.example/", "everyMinutes": 60}]
@@ -186,3 +202,120 @@ def test_the_thread_collects_on_its_own_and_stops(tmp_path):
time.sleep(0.02)
c.stop()
assert not c.running()
# ---- the real fetcher, against local servers -----------------------------------------------------
def serve(handler):
"""A local HTTP server on 127.0.0.1; returns (port, hits list)."""
hits = []
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
hits.append(self.path)
handler(self)
def log_message(self, *a):
pass
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv.server_address[1], hits
def answer(body, status=200, headers=()):
def h(req):
req.send_response(status)
for k, v in headers:
req.send_header(k, v)
req.send_header("Content-Length", str(len(body)))
req.end_headers()
req.wfile.write(body)
return h
@pytest.fixture
def loopback_is_public(monkeypatch):
"""Lets the fetcher reach the local test servers; every other private address stays refused."""
real = collect._is_public_ip
monkeypatch.setattr(collect, "_is_public_ip", lambda ip: ip == ipaddress.ip_address("127.0.0.1") or real(ip))
def test_the_fetcher_follows_redirects_and_checks_every_hop(loopback_is_public):
def h(req):
if req.path == "/start":
answer(b"", 302, [("Location", "/end?x=1")])(req)
elif req.path == "/private":
answer(b"", 302, [("Location", "http://10.0.0.1/")])(req)
else:
answer(b"the body")(req)
port, hits = serve(h)
assert safe_get(f"http://127.0.0.1:{port}/start") == b"the body"
assert hits == ["/start", "/end?x=1"]
with pytest.raises(ValueError):
safe_get(f"http://127.0.0.1:{port}/private")
def test_the_fetcher_connects_to_the_address_it_checked(monkeypatch):
"""A name that resolves to a public address when checked and to a private one afterwards
(DNS rebinding) never reaches the private one."""
port, hits = serve(answer(b"internal"))
calls = []
def resolve(host, *a, **k):
if host == "rebind.example":
calls.append(host)
ip = "1.1.1.1" if len(calls) == 1 else "127.0.0.1"
else: # an address resolves to itself
ip = host
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port))]
monkeypatch.setattr(socket, "getaddrinfo", resolve)
monkeypatch.setattr(collect, "CONNECT_S", 0.3)
with pytest.raises(Exception):
safe_get(f"http://rebind.example:{port}/")
assert hits == []
def test_the_fetcher_tries_the_next_checked_address_when_one_does_not_connect(loopback_is_public, monkeypatch):
port, hits = serve(answer(b"from the second address"))
real = socket.getaddrinfo
monkeypatch.setattr(socket, "getaddrinfo", lambda host, *a, **k: [
(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("1.1.1.1", port)),
(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))] if host == "two.example" else real(host, *a, **k))
monkeypatch.setattr(collect, "CONNECT_S", 0.3)
assert safe_get(f"http://two.example:{port}/") == b"from the second address"
assert hits == ["/"]
def test_the_fetcher_stops_a_server_that_sends_slowly(loopback_is_public, monkeypatch):
def drip(req):
req.send_response(200)
req.send_header("Content-Length", "100000")
req.end_headers()
try:
for _ in range(100):
req.wfile.write(b"x")
req.wfile.flush()
time.sleep(0.1)
except OSError:
pass
port, _ = serve(drip)
monkeypatch.setattr(collect, "TOTAL_S", 1.0)
monkeypatch.setattr(collect, "READ_S", 0.5)
t0 = time.monotonic()
with pytest.raises(Exception):
safe_get(f"http://127.0.0.1:{port}/")
assert time.monotonic() - t0 < 1.5
def test_the_fetcher_never_logs_the_address(monkeypatch, capfd):
import jarvis.debug
monkeypatch.setattr(jarvis.debug, "_is_debug_enabled", lambda: True)
monkeypatch.setattr(socket, "getaddrinfo",
lambda host, *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 80))])
with pytest.raises(ValueError):
safe_get("http://secret-host.example/private/path?token=abc123")
out = capfd.readouterr()
assert "secret-host" not in out.err + out.out and "abc123" not in out.err + out.out