#!/usr/bin/env python3
# /// script
# requires-python = ">=3.6"
# dependencies = []
# ///
"""Query the CIQ Portal CVE API (https://portal.ciq.com/api/v1/cve).

examples:
  ciq-cve.py products
  ciq-cve.py check CVE-2024-6387 CVE-2023-48795 -p lts-9.2
  ciq-cve.py cve CVE-2024-6387 --all
  ciq-cve.py advisory CIQSA-2026:1160
  ciq-cve.py cves -p lts-9.2 --severity critical --since 2026-01-01 -o csv

exit codes:
  check     0 if every CVE is fixed or not affected for every product it has a
            statement for (or every -p product), else 1
            (affected, under investigation, no statement, or unknown CVE)
  cve, advisory   1 if any ID is not found
  all       2 on usage, network or API errors
"""

import argparse
import base64
import csv
import http.client
import json
import os
import re
import sys
import time
import urllib.parse
import urllib.request

__version__ = "2026.11.0"

API = os.environ.get("CIQ_CVE_API", "https://portal.ciq.com/api/v1/cve").rstrip("/")
API_URL = urllib.parse.urlsplit(API)
OK_STATUSES = ("fixed", "known_not_affected")
STATUS_RANK = ("known_not_affected", "fixed", "under_investigation", "known_affected")
CVE_SEVERITIES = ("critical", "high", "medium", "low")
ADVISORY_SEVERITIES = CVE_SEVERITIES + ("unknown",)

connection = [None]
package_cache = {}


def die(msg):
    sys.stderr.write("error: %s\n" % msg)
    sys.exit(2)


def connect():
    cls = http.client.HTTPSConnection if API_URL.scheme == "https" else http.client.HTTPConnection
    proxy = urllib.request.getproxies().get(API_URL.scheme)
    if not proxy or urllib.request.proxy_bypass(API_URL.hostname):
        return cls(API_URL.hostname, API_URL.port, timeout=30)
    proxy = urllib.parse.urlsplit(proxy if "://" in proxy else "http://" + proxy)
    if proxy.scheme != "http":
        die("unsupported proxy scheme %s://; use an http:// proxy URL" % proxy.scheme)
    headers = {}
    if proxy.username:
        auth = "%s:%s" % (urllib.parse.unquote(proxy.username), urllib.parse.unquote(proxy.password or ""))
        headers["Proxy-Authorization"] = "Basic " + base64.b64encode(auth.encode()).decode()
    conn = cls(proxy.hostname, proxy.port or 80, timeout=30)
    conn.set_tunnel(API_URL.hostname, API_URL.port, headers)
    return conn


def get(path, **params):
    query = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
    url = API_URL.path + urllib.parse.quote(path) + ("?" + query if query else "")
    headers = {"User-Agent": "ciq-cve/" + __version__, "Accept": "application/json"}
    failed = False
    for _ in range(6):
        try:
            connection[0] = connection[0] or connect()
            connection[0].request("GET", url, headers=headers)
            resp = connection[0].getresponse()
            body = resp.read().decode("utf-8", "replace")
        except (http.client.HTTPException, OSError) as e:
            connection[0] = None
            if failed:
                die("cannot reach %s: %s" % (API, e))
            failed = True
            continue
        if resp.status == 200:
            try:
                return json.loads(body)
            except ValueError:
                die("non-JSON response from %s%s: %s" % (API_URL.netloc, url, body[:200]))
        if resp.status == 404:
            return None
        if resp.status != 429:
            die("HTTP %d from %s%s: %s" % (resp.status, API_URL.netloc, url, body[:200]))
        retry_after = resp.getheader("Retry-After") or ""
        time.sleep(int(retry_after) if retry_after.isdigit() else 5)
        connection[0] = None
    die("rate limited by %s, try again later" % API)


def paginate(path, **params):
    cursor = None
    while True:
        page = get(path, limit=100, cursor=cursor, **params)
        if page is None:
            die("HTTP 404 from %s%s" % (API_URL.netloc, API_URL.path + path))
        for item in page["items"]:
            yield item
        cursor = page.get("next_cursor")
        if not cursor:
            return


def list_rows(path, args, case, **filters):
    rows = []
    for product in resolve_products(args) or [None]:
        for severity in [case(s) for s in args.severity or []] or [None]:
            for item in paginate(path, product_key=product, severity=severity, **filters):
                rows.append(dict(item, product=product or ""))
                if args.max and len(rows) >= args.max:
                    sys.stderr.write("note: output capped at %d rows (--max)\n" % args.max)
                    return rows
    return rows


def nvr(nevra):
    """name-epoch:version-release.arch[::module:stream] -> name-version-release"""
    nevra = re.sub(r"-\d+:", "-", nevra.split("::")[0], count=1)
    return nevra.rsplit(".", 1)[0]


def advisory_for(src_nvr):
    name = src_nvr.rsplit("-", 2)[0]
    if name not in package_cache:
        found = {}
        for u in (get("/packages/" + name) or {}).get("updates", []):
            found.setdefault(nvr(u["fixed_in_nevra"]), set()).add(u["tracking_id"])
        package_cache[name] = found
    ids = sorted(package_cache[name].get(src_nvr, ()), key=lambda i: (not i.startswith("CIQSA"), i))
    return ids[0] if ids else None


def worse(a, b):
    rank = lambda s: STATUS_RANK.index(s) if s in STATUS_RANK else len(STATUS_RANK)
    return a if rank(a) >= rank(b) else b


def status_row(cve_id, product, status):
    return {"cve_id": cve_id, "product": product, "status": status,
            "advisory_id": [], "fixed_in": [], "packages": []}


def product_statuses(cve_id, products):
    """Per-product status rows for one CVE from its CSAF VEX document, or None if there is none."""
    doc = get("/vex/" + cve_id)
    if doc is None:
        return None
    found = {}
    for status, ids in doc["csaf"]["vulnerabilities"][0].get("product_status", {}).items():
        for pid in ids:
            key, _, nevra = pid.partition(":")
            if products and key not in products:
                continue
            row = found.setdefault(key, status_row(cve_id, key, status))
            row["status"] = worse(row["status"], status)
            if not nevra:
                continue
            row["packages"].append(nevra)
            if status == "fixed" and nevra.split("::")[0].endswith(".src"):
                row["fixed_in"].append(nvr(nevra))
                advisory = advisory_for(nvr(nevra))
                if advisory and advisory not in row["advisory_id"]:
                    row["advisory_id"].append(advisory)
    rows = [found[k] for k in sorted(found)]
    return rows + [status_row(cve_id, k, "no statement") for k in products if k not in found]


def yaml(obj, indent=0):
    pad = " " * indent
    if isinstance(obj, dict) and obj:
        return "\n".join(pad + json.dumps(str(k)) + ":" + block(v, indent) for k, v in obj.items())
    if isinstance(obj, list) and obj:
        return "\n".join(pad + "-" + block(v, indent) for v in obj)
    return pad + ("{}" if obj == {} else "[]" if obj == [] else json.dumps(obj))


def block(value, indent):
    if isinstance(value, (dict, list)) and value:
        return "\n" + yaml(value, indent + 2)
    return " " + yaml(value).strip()


def cell(value):
    if isinstance(value, list):
        return "; ".join(value)
    return "" if value is None else str(value)


def table_cell(column, value, width=70):
    text = cell(value)
    if column.endswith("_at"):
        return text[:10]
    if column == "description" and len(text) > width:
        return text[:width - 3] + "..."
    return text


def table(rows, columns):
    cells = [[table_cell(c, r.get(c)) for c in columns] for r in rows]
    widths = [max([len(c)] + [len(row[i]) for row in cells]) for i, c in enumerate(columns)]
    for row in [[c.upper() for c in columns]] + cells:
        print("  ".join(v.ljust(w) for v, w in zip(row, widths)).rstrip())


def emit(args, rows, columns, full=None):
    if args.output == "json":
        print(json.dumps(full if full is not None else rows, indent=2))
    elif args.output == "yaml":
        print(yaml(full if full is not None else rows))
    elif args.output == "csv":
        writer = csv.DictWriter(sys.stdout, columns, extrasaction="ignore", lineterminator="\n")
        writer.writeheader()
        writer.writerows({c: " ".join(cell(r.get(c)).split()) for c in columns} for r in rows)
    else:
        table(rows, columns)


def resolve_products(args):
    wanted = [p for value in args.product or [] for p in value.split(",") if p]
    if args.product and not wanted:
        die("-p given without a product key")
    if wanted:
        known = [p["repo_key"] for p in paginate("/repositories")]
        unknown = [p for p in wanted if p not in known]
        if unknown:
            die("unknown product %s; valid keys: %s" % (", ".join(unknown), ", ".join(known)))
    return wanted


def cve_ids(values):
    ids = []
    for value in values:
        ids += sys.stdin.read().split() if value == "-" else [value]
    if not ids:
        die("no CVE IDs given")
    bad = [i for i in ids if not re.match(r"^CVE-\d{4}-\d{4,}$", i, re.I)]
    if bad:
        die("not a CVE ID: %s" % ", ".join(bad))
    return [i.upper() for i in ids]


def slug(text):
    return re.sub(r"\W+", "_", text).lower()


def cmd_products(args):
    rows = list(paginate("/repositories"))
    columns = ["repo_key", "name", "version", "channel", "lifecycle_status"]
    emit(args, rows, columns + (["variant", "cpe_product"] if args.all else []))


def cmd_cves(args):
    rows = list_rows("/cves", args, str.upper,
                     released_after=args.since, released_before=args.until)
    columns = ["cve_id"] + (["product"] if args.product else []) + ["severity", "impact", "score", "published_at"]
    if args.all:
        columns += ["updated_at", "canonical_source", "cwe"]
        sources = sorted({source for r in rows for source in r.get("scores") or {}})
        for r in rows:
            for source, score in (r.get("scores") or {}).items():
                r[slug(source) + "_score"] = score.get("base_score")
                r[slug(source) + "_vector"] = score.get("scoring_vector")
        columns += [slug(s) + suffix for s in sources for suffix in ("_score", "_vector")]
    emit(args, rows, columns + ["description"])


def cmd_advisories(args):
    rows = list_rows("/advisories", args, str.capitalize,
                     released_after=args.since, released_before=args.until)
    for r in rows:
        r["advisory_id"] = r["tracking_id"]
    columns = ["advisory_id"] + (["product"] if args.product else []) + ["advisory_type", "severity", "published_at"]
    emit(args, rows, columns + (["updated_at", "track", "version"] if args.all else []))


def cmd_check(args):
    products = resolve_products(args)
    rows = []
    for cve_id in cve_ids(args.cve):
        statuses = product_statuses(cve_id, products)
        rows += statuses or [status_row(cve_id, p, "not found") for p in products or [""]]
    emit(args, rows, ["cve_id", "product", "status", "advisory_id", "fixed_in"])
    return 0 if all(r["status"] in OK_STATUSES for r in rows) else 1


def cmd_cve(args):
    products = resolve_products(args)
    results, missing = [], []
    for cve_id in cve_ids(args.cve):
        detail = get("/cves/" + cve_id)
        if detail is None:
            missing.append(cve_id)
            continue
        detail["products"] = product_statuses(cve_id, products) or []
        results.append(detail)
    columns = ["cve_id", "product", "status", "advisory_id", "fixed_in"] + (["packages"] if args.all else [])
    if args.output != "table":
        emit(args, [r for d in results for r in d["products"]], columns, full=results)
    for d in results if args.output == "table" else []:
        print("%s  %s  %s  %s (%s)  published %s  updated %s" % (
            d["cve_id"], d["severity"], d.get("impact") or "", d["score"], d.get("canonical_source") or "",
            d["published_at"][:10], d["updated_at"][:10]))
        description = d.get("description") or ""
        print(description if args.all else description[:160] + ("..." if len(description) > 160 else ""))
        if args.all:
            print("CWE: %s" % (d.get("cwe") or "n/a"))
            for source, s in sorted(d.get("scores", {}).items()):
                print("%s: %s %s  %s" % (source, s.get("base_score"), s.get("impact"), s.get("scoring_vector") or ""))
                print("  %s" % (s.get("source_link") or ""))
        print()
        table(d["products"], columns[:5])
        if args.all:
            for r in d["products"]:
                if r["packages"]:
                    print("\n%s packages:\n  %s" % (r["product"], "\n  ".join(sorted(r["packages"]))))
        print()
    for cve_id in missing:
        sys.stderr.write("%s: not found\n" % cve_id)
    return 1 if missing else 0


def cmd_advisory(args):
    results, missing = [], []
    for advisory_id in args.advisory:
        adv = get("/advisories/" + advisory_id.upper())
        if adv is None:
            missing.append(advisory_id)
            continue
        adv["cves"] = []
        for cve_id in sorted({c for p in adv["packages"] for c in p["cve_ids"]}):
            c = get("/cves/" + cve_id) or {}
            fixes = [p for p in adv["packages"] if cve_id in p["cve_ids"]]
            adv["cves"].append({"advisory_id": adv["tracking_id"], "cve_id": cve_id, "severity": c.get("severity"),
                                "impact": c.get("impact"), "score": c.get("score"),
                                "fixed_in": sorted({nvr(p["fixed_in_nevra"]) for p in fixes if p["arch"] == "src"}),
                                "packages": sorted({re.sub(r"-\d+:", "-", p["fixed_in_nevra"], count=1) for p in fixes})})
        results.append(adv)
    columns = ["advisory_id", "cve_id", "severity", "impact", "score", "fixed_in"] + (["packages"] if args.all else [])
    if args.output != "table":
        emit(args, [r for a in results for r in a["cves"]], columns, full=results)
    for a in results if args.output == "table" else []:
        print("%s  %s  %s  %s  [%s]\n" % (a["tracking_id"], a["severity"], a["published_at"][:10],
                                         a.get("title") or "", ", ".join(a.get("affected_product_keys", []))))
        table(a["cves"], columns[1:6])
        if args.all:
            print("\npackages:\n  " + "\n  ".join(sorted({re.sub(r"-\d+:", "-", p["fixed_in_nevra"], count=1) for p in a["packages"]})))
            print("\nreferences:\n  " + "\n  ".join(r["url"] for r in a.get("references", [])))
        print()
    for advisory_id in missing:
        sys.stderr.write("%s: not found\n" % advisory_id)
    return 1 if missing else 0


def date(value):
    if re.match(r"^\d{4}-\d{2}-\d{2}$", value):
        return value + "T00:00:00Z"
    if re.match(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$", value):
        return value
    raise argparse.ArgumentTypeError("use YYYY-MM-DD or YYYY-MM-DDThh:mm:ssZ")


def severity_list(choices):
    def parse(value):
        wanted = [s.lower() for s in value.split(",") if s]
        bad = [s for s in wanted if s not in choices]
        if bad or not wanted:
            raise argparse.ArgumentTypeError("invalid severity %s (choose from %s)" % (",".join(bad) or "''", ", ".join(choices)))
        return list(dict.fromkeys(wanted))
    return parse


def positive(value):
    if not value.isdigit() or int(value) < 1:
        raise argparse.ArgumentTypeError("must be a whole number of 1 or more")
    return int(value)


def parse_args():
    parser = argparse.ArgumentParser(prog="ciq-cve.py", description=__doc__,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--version", action="version", version=__version__)
    sub = parser.add_subparsers(dest="command", metavar="command")

    def command(name, func, help, product=False, detail=None, severities=None):
        p = sub.add_parser(name, help=help, description=help)
        p.add_argument("-o", "--output", choices=["table", "csv", "json", "yaml"], default="table")
        if product:
            p.add_argument("-p", "--product", action="append", metavar="KEY",
                           help="product key, repeatable or comma separated (see 'products')")
        if detail:
            p.add_argument("-a", "--all", action="store_true", help=detail)
        if severities:
            p.add_argument("--severity", type=severity_list(severities), metavar="S",
                           help="one or more of %s, comma separated" % ", ".join(severities))
            p.add_argument("--since", type=date, metavar="DATE", help="released on or after (YYYY-MM-DD)")
            p.add_argument("--until", type=date, metavar="DATE", help="released before (YYYY-MM-DD)")
            p.add_argument("--max", type=positive, metavar="N", help="stop after N rows in total")
        p.set_defaults(func=func)
        return p

    command("products", cmd_products, "list product keys", detail="add variant and CPE columns")
    command("cves", cmd_cves, "list CVEs", product=True, severities=CVE_SEVERITIES,
            detail="add updated date, CWE and per-source score columns")
    command("advisories", cmd_advisories, "list advisories", product=True, severities=ADVISORY_SEVERITIES,
            detail="add updated date, track and version columns")
    p = command("cve", cmd_cve, "show CVEs with per-product status", product=True,
                detail="add full description, CWE, per-source scores and binary packages")
    p.add_argument("cve", nargs="+", help="CVE IDs, or - to read from stdin")
    p = command("check", cmd_check, "exit 0 if every CVE is fixed or not affected, else 1", product=True)
    p.add_argument("cve", nargs="+", help="CVE IDs, or - to read from stdin")
    p = command("advisory", cmd_advisory, "show advisories with the CVEs they fix",
                detail="add binary packages and references")
    p.add_argument("advisory", nargs="+", help="advisory IDs, e.g. CIQSA-2026:1160")

    args = parser.parse_args()
    if not args.command:
        parser.print_help()
        sys.exit(2)
    return args


def main():
    args = parse_args()
    try:
        status = args.func(args) or 0
        sys.stdout.flush()
        return status
    except KeyboardInterrupt:
        return 130
    except BrokenPipeError:
        os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
        return 1 if args.command == "check" else 0


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