# SPDX-License-Identifier: MIT
"""A SOAR action: enrich a URL with urlquery and print one JSON decision.

    pip install urlquery-api
    export URLQUERY_APIKEY=<urlquery API key>
    python urlquery_enrich_url.py 'https://login.example.com/verify'
    echo '{"url": "https://login.example.com/verify", "case": "1234"}' | python urlquery_enrich_url.py -

It reuses a report of the URL from the last 7 days, or analyzes it as a
restricted report, and prints:

    {"decision": "block" | "review" | "no_evidence", "verdict": ..., "report_id": ...,
     "report_url": ..., "final_url": ..., "title": ..., "ip": ..., "asn": ..., "as": ...,
     "alerts": [...], "tags": [...]}

"no_evidence" is not "safe": urlquery saw nothing malicious in one visit.
When the analysis can't finish in time, it prints {"decision": "pending", ...}
with the queue and report IDs and exits with status 3: run it again later
with --report <report_id>; don't submit the URL again. Other failures,
network errors included, print {"error": ...} and exit with status 2.
"""

from __future__ import annotations

import argparse
import json
import sys

import httpx
from urlquery_api import Client, URLQueryError, WaitError

REPORT_URL = "https://urlquery.net/report/{}"
BLOCK_ALERTS = {"phishing", "malware"}  # urlquery alert verdicts that block on their own


def find_or_analyze(client: Client, url: str, case: str | None, max_age: int, timeout: float) -> str:
    addr = url.split("://", 1)[-1]
    found = client.search_reports(f'url.addr:"{addr}" AND date:[now-{max_age}d TO now]', limit=1)
    if found.items:
        return found.items[0].report_id
    tags = [f"case_{case}"] if case else None
    s = client.submit(url, access="restricted", tags=tags, wait=True, wait_timeout=timeout)
    if s.status != "done":
        raise URLQueryError(f"the analysis {s.status}")
    return s.report_id


def decide(client: Client, report_id: str) -> dict:
    o = client.report_overview(report_id)
    verdict = client.lookup_reputation(f"{o.url.schema_}://{o.url.addr}").verdict
    alerts = [{"severity": a.severity, "verdict": a.verdict, "alert": a.alert, "host": a.trigger}
              for a in o.detection.urlquery]
    if verdict == "malicious" or any(a["verdict"] in BLOCK_ALERTS for a in alerts):
        decision = "block"
    elif verdict == "suspicious" or alerts:
        decision = "review"
    else:
        decision = "no_evidence"
    return {
        "decision": decision, "verdict": verdict, "report_id": report_id,
        "report_url": REPORT_URL.format(report_id), "date": o.date.isoformat(),
        "final_url": f"{o.final.url.schema_}://{o.final.url.addr}", "title": o.final.title,
        "ip": o.ip.addr, "asn": o.ip.asn, "as": o.ip.as_, "country": o.ip.country_code,
        "alerts": alerts, "tags": o.tags,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("url", nargs="?", help='the URL, or "-" for JSON {"url": ..., "case": ...} on standard input')
    parser.add_argument("--report", help="decide on an existing report instead")
    parser.add_argument("--case", help="a case ID to tag a new analysis with")
    parser.add_argument("--max-age", type=int, default=7, help="reuse reports up to this many days old")
    parser.add_argument("--timeout", type=float, default=240, help="seconds to wait for a new analysis")
    args = parser.parse_args()

    url, case = args.url, args.case
    if url == "-":
        task = json.load(sys.stdin)
        url, case = task["url"], task.get("case", case)
    if bool(url) == bool(args.report):
        parser.error("give a URL or --report")

    try:
        with Client(user_agent="urlquery-soar") as client:
            report_id = args.report or find_or_analyze(client, url, case, args.max_age, args.timeout)
            result = decide(client, report_id)
    except WaitError as e:
        print(json.dumps({"decision": "pending", "error": str(e), "queue_id": e.submission.queue_id,
                          "report_id": e.submission.report_id}))
        return 3
    except (URLQueryError, httpx.HTTPError, ValueError) as e:
        print(json.dumps({"error": str(e)}))
        return 2
    print(json.dumps(result))
    return 0


if __name__ == "__main__":
    sys.exit(main())
