"""AdGuard-backed endpoints, against a fake AdGuard Home.""" import asyncio import json from datetime import UTC, datetime, timedelta import httpx import pytest from app.hub import adguard, dns from app.hub.db import db NOW = datetime.now(UTC) def row(i, client, domain, blocked=False): t = (NOW - timedelta(minutes=i)).isoformat().replace("+00:00", "123Z") # nanosecond-ish like AdGuard return { "time": t, "client": client, "client_info": {"name": f"host-{client.split('.')[-1]}"}, "question": {"name": domain, "type": "A", "class": "IN"}, "status": "NOERROR", "reason": "FilteredBlackList" if blocked else "NotFilteredNotFound", "elapsedMs": "1.5", "rules": [{"text": f"||{domain}^", "filter_list_id": 1}] if blocked else [], "upstream": "https://1.1.1.1/dns-query", } LOG = ( [row(i, "192.168.1.5", "api.example.com") for i in range(0, 600)] + [row(i, "192.168.1.50", "www.example.com") for i in range(600, 700)] + [row(i, "192.168.1.5", "ads.tracker.net", blocked=True) for i in range(700, 760)] + [row(i, "192.168.1.51", "cdn.example.co.uk") for i in range(760, 770)] ) def handler(request: httpx.Request) -> httpx.Response: assert request.headers.get("authorization", "").startswith("Basic ") p = request.url.path q = request.url.params if p == "/control/status": return httpx.Response(200, json={"version": "v0.107.99", "running": True, "protection_enabled": True}) if p == "/control/querylog": rows = LOG if q.get("search"): rows = [r for r in rows if q["search"] in r["question"]["name"] or q["search"] in r["client"]] if q.get("response_status") == "blocked": rows = [r for r in rows if r["reason"] == "FilteredBlackList"] if q.get("older_than"): cut = adguard.parse_time(q["older_than"]) rows = [r for r in rows if adguard.parse_time(r["time"]) < cut] page = rows[: int(q.get("limit", 500))] return httpx.Response(200, json={"data": page, "oldest": page[-1]["time"] if page else ""}) if p == "/control/stats": return httpx.Response(200, json={ "num_dns_queries": 770, "num_blocked_filtering": 60, "time_units": "hours", "top_queried_domains": [{"api.example.com": 600}, {"www.example.com": 100}], "top_blocked_domains": [{"ads.tracker.net": 60}], "top_clients": [{"192.168.1.5": 660}, {"192.168.1.50": 100}], }) if p == "/control/clients": return httpx.Response(200, json={ "clients": [{"name": "Test laptop", "ids": ["192.168.1.5", "AA:BB:CC:DD:EE:01"]}], "auto_clients": [{"ip": "192.168.1.50", "name": "tv.lan", "source": "rDNS"}], }) if p == "/control/dhcp/status": return httpx.Response(200, json={"enabled": True, "leases": [{"mac": "aa:bb:cc:dd:ee:02", "ip": "192.168.1.51", "hostname": "plug"}]}) return httpx.Response(404, json={}) @pytest.fixture def ag(monkeypatch): monkeypatch.setenv("ADGUARD_URL", "http://adguard.test") monkeypatch.setenv("ADGUARD_USERNAME", "admin") monkeypatch.setenv("ADGUARD_PASSWORD", "pw") monkeypatch.setattr(adguard, "TRANSPORT", httpx.MockTransport(handler)) def test_not_configured(hub): assert hub.get("/api/dns/status").json()["configured"] is False r = hub.get("/api/dns/queries") assert r.status_code == 503 and "ADGUARD_URL" in r.json()["detail"] def test_status_and_unreachable(hub, ag, monkeypatch): assert hub.get("/api/dns/status").json()["version"] == "v0.107.99" monkeypatch.setattr(adguard, "TRANSPORT", httpx.MockTransport(lambda r: httpx.Response(401))) j = hub.get("/api/dns/status").json() assert j["ok"] is False and "rejected the login" in j["message"] def test_discovery_merges_sources(hub, ag): asyncio.run(dns.discover_once()) clients = {c["key"]: c for c in hub.get("/api/clients").json()["clients"]} laptop = clients["aa:bb:cc:dd:ee:01"] assert laptop["ip"] == "192.168.1.5" and laptop["hostname"] in ("Test laptop", "host-5") assert laptop["online"] and laptop["queries"] == 660 and "adguard" in laptop["sources"] assert not laptop["new"] # found on the first day: not flagged as new assert clients["aa:bb:cc:dd:ee:02"]["hostname"] == "plug" assert "ip:192.168.1.50" in clients # no MAC known for the TV assert "ip:192.168.1.5" not in clients # folded into the MAC entry def test_ip_entry_folds_into_mac_and_keeps_labels(hub, ag): asyncio.run(dns.discover_once()) hub.put("/api/clients/ip:192.168.1.50", json={"name": "Living room TV", "category": "Media", "suspicious": True}) with db() as con: from app.hub import devices devices.sighting(con, ip="192.168.1.50", mac="aa:bb:cc:dd:ee:50", source="arp") c = hub.get("/api/clients/aa:bb:cc:dd:ee:50").json() assert c["name"] == "Living room TV" and c["category"] == "Media" and c["suspicious"] assert hub.get("/api/clients/ip:192.168.1.50").status_code == 404 def test_queries_filters_and_paging(hub, ag): asyncio.run(dns.discover_once()) r = hub.get("/api/dns/queries", params={"client": "aa:bb:cc:dd:ee:01", "limit": 50}).json() assert len(r["rows"]) == 50 and {x["client"] for x in r["rows"]} == {"192.168.1.5"} assert r["rows"][0]["device"]["key"] == "aa:bb:cc:dd:ee:01" more = hub.get("/api/dns/queries", params={"client": "aa:bb:cc:dd:ee:01", "limit": 50, "older_than": r["oldest"]}).json() assert more["rows"][0]["ts"] < r["rows"][-1]["ts"] blocked = hub.get("/api/dns/queries", params={"status": "blocked"}).json()["rows"] assert blocked and all(x["blocked"] for x in blocked) allowed = hub.get("/api/dns/queries", params={"status": "allowed", "search": "tracker"}).json() assert allowed["rows"] == [] and allowed["done"] def test_client_summary(hub, ag): asyncio.run(dns.discover_once()) s = hub.get("/api/clients/aa:bb:cc:dd:ee:01/summary").json() assert s["top"][0]["domain"] == "api.example.com" and s["blocked"] == 60 def test_domain_detail(hub, ag): d = hub.get("/api/domains/www.example.com").json() assert d["base"] == "example.com" and d["count"] == 100 assert d["clients"][0]["ip"] == "192.168.1.50" assert {"domain": "api.example.com", "count": 600, "blocked": 0} in d["related"] assert d["stats_count"] == 100 uk = hub.get("/api/domains/cdn.example.co.uk").json() assert uk["base"] == "example.co.uk" and uk["count"] == 10 def test_blocked_and_top(hub, ag): b = hub.get("/api/dns/blocked").json() assert b["top"] == [{"domain": "ads.tracker.net", "count": 60}] assert b["recent"][0]["domain"] == "ads.tracker.net" and b["recent"][0]["rule"] == "||ads.tracker.net^" t = hub.get("/api/domains").json() assert t["top_queried"][0] == {"domain": "api.example.com", "count": 600} def test_base_domain(): assert adguard.base_domain("a.b.c.example.com") == "example.com" assert adguard.base_domain("x.bbc.co.uk") == "bbc.co.uk" assert adguard.base_domain("localhost") == "localhost" assert adguard.base_domain("1.2.3.4") == "1.2.3.4" def test_parse_time_nanoseconds(): assert adguard.parse_time("2026-11-04T10:00:00.123456789+02:00") == datetime(2026, 11, 4, 8, 0, 0, 123456, UTC).timestamp()