File size: 5,796 Bytes
56b30f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""The analysis pipeline. Pure orchestration: every external dependency is injected, so the whole
decision logic is unit-testable with fakes (see tests/test_engine.py).

Order of evidence (first definitive answer wins):
  cache -> demo override (explicit opt-in) -> seed allow-list -> OSINT feeds
  -> Tranco top-N trust -> [domain age || VirusTotal || Safe Browsing || AbuseIPDB] -> LLM verdict -> deterministic override rules
"""
from __future__ import annotations

import asyncio
import logging
from dataclasses import dataclass
from typing import Awaitable, Callable

from .config import Settings
from .intel import TRUSTED_AGES, ThreatFeeds
from .privacy import CleanURL, registrable_guess, sanitize_url
from .scanner import Verdict

log = logging.getLogger("wade.engine")

AgeFn = Callable[[str], Awaitable[int]]
VtFn = Callable[[CleanURL], Awaitable[dict]]
SbFn = Callable[[CleanURL], Awaitable[dict]]
AbuseFn = Callable[[str], Awaitable[dict]]
TrustedFn = Callable[[str], bool]
LlmFn = Callable[[CleanURL, int, dict, dict, dict], Awaitable[Verdict | None]]


async def _no_sb(clean):
    return {"threat": "None", "source": "No Key"}


async def _no_abuse(host):
    return {"abuse_confidence": 0, "source": "No Key"}


@dataclass
class Services:
    settings: Settings
    cache: object          # .get(key) / .set(key, value)
    feeds: ThreatFeeds
    age_fn: AgeFn
    vt_fn: VtFn
    llm_fn: LlmFn
    sb_fn: SbFn = _no_sb              # Google Safe Browsing
    abuse_fn: AbuseFn = _no_abuse     # AbuseIPDB (IPv4 hosts only)
    trusted_fn: TrustedFn = lambda host: False  # Tranco top-N membership


def _result(clean: CleanURL, score: int, verdict: str, threat: str, harm: str, effect: str,
            age: int, vt: dict, source: str, degraded: bool = False) -> dict:
    return {"risk_score": score, "verdict": verdict, "threat_type": threat, "harm": harm, "effect": effect,
            "domain_age": age, "vt_data": vt, "url": clean.url, "source": source, "degraded": degraded,
            "cached": False}


async def analyze(raw_url: str, svc: Services) -> dict:
    s = svc.settings
    clean = sanitize_url(raw_url, s.max_url_length)  # ValueError -> HTTP 422 at the edge

    cached = await svc.cache.get(clean.key)
    if cached is not None:
        return {**cached, "cached": True}

    if clean.host in s.demo_hosts:  # explicit, labelled, off by default
        return _result(clean, 85, "MALICIOUS", "Demo override (WADE_DEMO_HOSTS)",
                       "Demo mode: result is configured, not analysed.", "Connection severed by WADE IPS",
                       -1, {"malicious": 0, "total": "N/A"}, "demo-override")

    bare = registrable_guess(clean.host)
    if bare in TRUSTED_AGES:
        res = _result(clean, 0, "SAFE", "Official Trusted Domain", "None", "None", TRUSTED_AGES[bare],
                      {"malicious": 0, "total": "N/A"}, "allow-list")
        await svc.cache.set(clean.key, res)
        return res

    if svc.feeds.contains(clean):
        res = _result(clean, 100, "MALICIOUS", "Confirmed Phishing/Malware (OSINT feed)",
                      "Listed in a public threat feed", "Credential theft or malware delivery",
                      -1, {"malicious": "High", "total": "OSINT"}, "osint-feed")
        await svc.cache.set(clean.key, res)
        return res

    if svc.trusted_fn(clean.host):  # globally popular domain (Tranco top list)
        res = _result(clean, 0, "SAFE", "Global Trusted Domain", "None", "None", -1,
                      {"malicious": 0, "total": "Tranco"}, "tranco")
        await svc.cache.set(clean.key, res)
        return res

    age_r, vt_r, sb_r, abuse_r = await asyncio.gather(
        svc.age_fn(clean.host), svc.vt_fn(clean), svc.sb_fn(clean), svc.abuse_fn(clean.host),
        return_exceptions=True)
    age = age_r if isinstance(age_r, int) else -1
    vt = vt_r if isinstance(vt_r, dict) else {"malicious": 0, "total": "N/A"}
    sb = sb_r if isinstance(sb_r, dict) else {"threat": "None", "source": "Error"}
    abuse = abuse_r if isinstance(abuse_r, dict) else {"abuse_confidence": 0, "source": "Error"}
    sb_threat = str(sb.get("threat", "None"))
    abuse_score = abuse.get("abuse_confidence", 0) if isinstance(abuse.get("abuse_confidence"), int) else 0

    verdict = await svc.llm_fn(clean, age, vt, sb, abuse)
    degraded = verdict is None
    if degraded:
        if s.fail_mode == "closed":
            verdict = Verdict(risk_score=50, verdict="SUSPICIOUS", threat_type="Analysis unavailable",
                              harm="Could not be verified", effect="Proceed with caution")
        else:
            verdict = Verdict(risk_score=0, verdict="SAFE")

    score, label, threat = verdict.risk_score, verdict.verdict, verdict.threat_type

    # Deterministic rules: strong external evidence can never be talked down by the model.
    if isinstance(vt.get("malicious"), int) and vt["malicious"] > 3:
        score, label, threat = max(score, 90), "MALICIOUS", "Security Vendor Flagged"
    if abuse_score > 50:
        score, label, threat = max(score, 85), "MALICIOUS", f"AbuseIPDB Score: {abuse_score}%"
    if sb_threat != "None":  # strongest signal, applied last so it wins
        score, label, threat = max(score, 95), "MALICIOUS", f"Google Safe Browsing: {sb_threat}"
    if age != -1 and age < 3 and score < 40:
        score, threat = 50, "Very Newly Registered Domain"
        if label == "SAFE":
            label = "SUSPICIOUS"

    res = _result(clean, score, label, threat, verdict.harm, verdict.effect, age, vt, "ai+osint", degraded)
    res["safe_browsing"], res["abuse_confidence"] = sb_threat, abuse_score
    if not degraded:  # never cache a degraded answer, so the next request retries the AI
        await svc.cache.set(clean.key, res)
    return res