#!/usr/bin/env python3
"""publisher@1 verifier: does <domain> say it publishes these DashRemix boards, agents and themes? Python standard
library only, so a company can run it on its own file before telling DashRemix:

    python3 verify.py <domain> [--id <publisher-id>]          # fetch https://<domain>/.well-known/dashremix.json
    python3 verify.py <domain> --file dashremix.json [--id x]  # check a local copy (no network)
    python3 verify.py <domain> --dns --id <publisher-id>       # the DNS TXT method (needs `dig` on PATH)

The fetch is anonymous: one HTTPS GET to the domain itself, a generic User-Agent, no cookies, no credentials, no
redirects followed (a redirect fails), at most MAX_BYTES read. Nothing about the person running it is sent. The DNS
method asks the system resolver through `dig`; no third-party resolver is ever used.

parse_document(raw, domain, publisher_id) and parse_txt(records, publisher_id) are pure and are what the tests use.
"""
import hashlib, http.client, ipaddress, json, re, shutil, socket, ssl, subprocess, sys

STANDARD = 'publisher@1'
WELL_KNOWN = '/.well-known/dashremix.json'
TXT_NAME = '_dashremix'                    # the TXT record lives at _dashremix.<domain>
TXT_PREFIX = 'dashremix-publisher='
MAX_BYTES = 64 * 1024
MAX_ITEMS = 500                            # per list
TIMEOUT = 10
USER_AGENT = 'DashRemix-publisher-verify/1'
ID_RE = re.compile(r'[a-z][a-z0-9-]{1,63}')
LABEL_RE = re.compile(r'(?!-)[a-z0-9-]{1,63}(?<!-)')
KINDS = ('boards', 'agents', 'themes')
LOCAL_SUFFIXES = ('localhost', 'local', 'internal', 'intranet', 'lan', 'home', 'corp', 'home.arpa', 'localdomain', 'invalid', 'test', 'onion')


class VerifyError(ValueError):
    """The document, record or domain does not verify. str(e) says why, in words a publisher can act on."""


def check_domain(domain):
    """A bare registrable host name: lowercase, at least two labels, no scheme, port, path, user or IP address."""
    d = str(domain or '').strip()
    if d != d.lower():
        raise VerifyError(f'"{domain}": write the domain in lowercase')
    if not d or len(d) > 253 or '/' in d or ':' in d or '@' in d or d.endswith('.'):
        raise VerifyError(f'"{domain}" is not a bare domain name (no https://, port, path or trailing dot)')
    try:
        ipaddress.ip_address(d)
        raise VerifyError(f'"{domain}" is an IP address; verification needs a domain name')
    except ValueError as e:
        if isinstance(e, VerifyError):
            raise
    labels = d.split('.')
    if len(labels) < 2 or not all(LABEL_RE.fullmatch(x) for x in labels) or labels[-1].isdigit():
        raise VerifyError(f'"{domain}" is not a valid domain name')
    if any(d == x or d.endswith('.' + x) for x in LOCAL_SUFFIXES):
        raise VerifyError(f'"{domain}" is a local or reserved name, not a public domain')
    return d


def check_public(domain):
    """Resolve once -> the address to connect to. Every address the domain resolves to must be a public one (no loopback,
    private, link-local or reserved network); the fetch then connects to exactly that address (no second lookup)."""
    try:
        infos = socket.getaddrinfo(domain, 443, type=socket.SOCK_STREAM)
    except (socket.gaierror, OSError, UnicodeError) as e:
        raise VerifyError(f'{domain} does not resolve ({e})') from None
    for info in infos:
        ip = ipaddress.ip_address(info[4][0].split('%')[0])
        if not ip.is_global:
            raise VerifyError(f'{domain} resolves to {ip}, which is not a public address')
    if not infos:
        raise VerifyError(f'{domain} does not resolve')
    return infos[0][4]


def parse_document(raw, domain, publisher_id=None):
    """The bytes of https://<domain>/.well-known/dashremix.json -> {publisher, domain, name, boards, agents, themes,
    sha256}. Raises VerifyError when it is too large, not UTF-8 JSON, not publisher@1, for another domain or publisher,
    or its id lists are malformed. Unknown top-level keys are ignored (a later 1.x minor may add optional ones)."""
    domain = check_domain(domain)
    if not isinstance(raw, (bytes, bytearray)):
        raw = str(raw).encode()
    if len(raw) > MAX_BYTES:
        raise VerifyError(f'the file is larger than {MAX_BYTES // 1024} KB')
    try:
        doc = json.loads(bytes(raw).decode('utf-8'))
    except (UnicodeDecodeError, ValueError, RecursionError) as e:
        raise VerifyError(f'the file is not UTF-8 JSON ({type(e).__name__})') from None
    if not isinstance(doc, dict):
        raise VerifyError('the file must be one JSON object')
    if doc.get('dashremix') != STANDARD:
        raise VerifyError(f'"dashremix" must be "{STANDARD}"')
    pid = doc.get('publisher')
    if not isinstance(pid, str) or not ID_RE.fullmatch(pid):
        raise VerifyError('"publisher" must be your DashRemix publisher id (lowercase letters, digits and hyphens)')
    if publisher_id is not None and pid != publisher_id:
        raise VerifyError(f'the file is for publisher "{pid}", not "{publisher_id}"')
    if doc.get('domain') != domain:
        raise VerifyError(f'the file names domain "{doc.get("domain")}", but it was read from "{domain}"')
    name = doc.get('name')
    if name is not None and (not isinstance(name, str) or not 2 <= len(name) <= 80):
        raise VerifyError('"name", when given, is 2 to 80 characters')
    if not any(k in doc for k in KINDS):
        raise VerifyError('the file lists no ids: give at least one of "boards", "agents", "themes"')
    out = {'publisher': pid, 'domain': domain, 'name': name}
    for k in KINDS:
        ids = doc.get(k, [])
        if not isinstance(ids, list) or not all(isinstance(x, str) and ID_RE.fullmatch(x) for x in ids):
            raise VerifyError(f'"{k}" must be a list of ids (lowercase letters, digits and hyphens)')
        if len(ids) > MAX_ITEMS:
            raise VerifyError(f'"{k}" lists more than {MAX_ITEMS} ids')
        if len(set(ids)) != len(ids):
            raise VerifyError(f'"{k}" lists an id twice')
        out[k] = sorted(ids)
    out['sha256'] = hashlib.sha256(bytes(raw)).hexdigest()
    return out


def parse_txt(records, publisher_id):
    """The TXT strings at _dashremix.<domain> -> True when exactly one says dashremix-publisher=<publisher_id>.
    Raises VerifyError when none does, or when they name another publisher (two claims on one domain never verify)."""
    vals = [join_txt(r) for r in records]
    claims = sorted({v[len(TXT_PREFIX):] for v in vals if v.startswith(TXT_PREFIX)})
    if not claims:
        raise VerifyError(f'no TXT record "{TXT_PREFIX}<id>" at {TXT_NAME}.<domain>')
    if claims != [publisher_id]:
        raise VerifyError(f'the TXT records name {", ".join(claims)}, not only "{publisher_id}"')
    return True


def join_txt(record):
    """One TXT record as dig prints it ("part1" "part2", or bare) -> its value: the strings joined with nothing between."""
    parts = re.findall(r'"((?:[^"\\]|\\.)*)"', record)
    return ''.join(parts) if parts else record.strip()


def fetch(domain):
    """GET https://<domain>/.well-known/dashremix.json anonymously -> the raw bytes (at most MAX_BYTES + 1). The name is
    resolved once and checked (check_public); the connection goes to that exact address, with TLS verified for the domain
    (SNI and certificate host name), so a second DNS answer can never point it elsewhere. Any redirect fails."""
    domain = check_domain(domain)
    url = f'https://{domain}{WELL_KNOWN}'
    addr = check_public(domain)
    ctx = ssl.create_default_context()
    try:
        # addr is the numeric IP check_public approved: create_connection does no DNS lookup for a literal address
        sock = ctx.wrap_socket(socket.create_connection(addr[:2], timeout=TIMEOUT), server_hostname=domain)
    except (OSError, ssl.SSLError) as e:
        raise VerifyError(f'could not connect to {url} ({e})') from None
    conn = http.client.HTTPSConnection(domain, 443, timeout=TIMEOUT, context=ctx)
    conn.sock = sock                                   # the pinned, verified connection: no second lookup
    try:
        conn.request('GET', WELL_KNOWN, headers={'User-Agent': USER_AGENT, 'Accept': 'application/json'})
        r = conn.getresponse()
        if r.status != 200:
            raise VerifyError(f'{url} answered HTTP {r.status}' + (' (redirects are not followed)' if 300 <= r.status < 400 else ''))
        return r.read(MAX_BYTES + 1)
    except (OSError, http.client.HTTPException) as e:
        raise VerifyError(f'could not read {url} ({e})') from None
    finally:
        conn.close()


def lookup_txt(domain):
    """TXT strings at _dashremix.<domain> through the system resolver (`dig +short`). No dig: VerifyError."""
    dig = shutil.which('dig')
    if not dig:
        raise VerifyError('the DNS method needs `dig` (bind tools); use the .well-known file instead')
    try:
        r = subprocess.run([dig, '+short', 'TXT', f'{TXT_NAME}.{check_domain(domain)}'], capture_output=True, text=True, timeout=TIMEOUT + 5)
    except (subprocess.TimeoutExpired, OSError) as e:
        raise VerifyError(f'the DNS lookup did not finish ({type(e).__name__})') from None
    if r.returncode:
        raise VerifyError(f'the DNS lookup failed (dig exit {r.returncode})')
    return [line for line in r.stdout.splitlines() if line.strip()]


def verify(domain, publisher_id=None, method='well-known', raw=None, fetcher=fetch, txt=lookup_txt):
    """One verification -> {method, domain, publisher, boards, agents, themes, sha256}. `raw` checks a local copy;
    `fetcher` and `txt` are injectable so tests never reach the network."""
    domain = check_domain(domain)
    if method == 'dns':
        if not publisher_id:
            raise VerifyError('the DNS method needs the publisher id (--id)')
        parse_txt(txt(domain), publisher_id)
        return {'method': 'dns', 'domain': domain, 'publisher': publisher_id, 'name': None, 'boards': None, 'agents': None,
                'themes': None, 'sha256': None}
    doc = parse_document(fetcher(domain) if raw is None else raw, domain, publisher_id)
    return {'method': 'well-known', **doc}


def main(argv):
    import argparse
    ap = argparse.ArgumentParser(prog='verify.py', description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('domain'); ap.add_argument('--id'); ap.add_argument('--file'); ap.add_argument('--dns', action='store_true')
    a = ap.parse_args(argv)
    try:
        if a.file:
            with open(a.file, 'rb') as fh:
                raw = fh.read(MAX_BYTES + 1)
        else:
            raw = None
        res = verify(a.domain, a.id, 'dns' if a.dns else 'well-known', raw)
    except VerifyError as e:
        print(f'NOT VERIFIED  {a.domain}: {e}')
        return 1
    print(json.dumps(res, indent=1))
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
