#!/usr/bin/env python3
"""Daemon coverage: IDN hosts allow / hosts deny matching (access.c).

A daemon gets its peer's name from DNS as ASCII, so an rsyncd.conf entry
written with non-ASCII characters is folded to its IDNA A-label form before
being matched.  The IDNA mapping also folds some non-ASCII characters onto
ASCII ones (U+FF0A FULLWIDTH ASTERISK becomes '*'), so the checks below cover
both directions: a Unicode name that has to match, and the tokens that must
stay denied rather than turn into a wildcard or an address/mask.  Punycode,
mixed case and an unconvertible name are covered too.

The peer name isn't assumed: a throwaway daemon comes up first to log the name
this host's resolver gives it, and the real config is written around that.
"forward lookup" is off throughout, which pins the match on the reverse-DNS
name and keeps a denied module from waiting out a resolver timeout on a name
that deliberately doesn't exist.

Like daemon-access-ip_test.py this needs a real TCP peer (--use-tcp), and the
config sets no global hosts allow so each module's own patterns decide.
"""

import re
import subprocess

from rsyncfns import (
    FROMDIR, SCRATCHDIR,
    claim_ports, make_tree, require_tcp, rmtree, rsync_argv, start_rsyncd,
    start_test_daemon, test_fail, test_skipped,
)

PROBE_PORT = 12896
DAEMON_PORT = 12898
require_tcp("hosts allow/deny hostname matching needs a real TCP peer")

if '"IDN": true' not in subprocess.run(rsync_argv('-VV'), capture_output=True,
                                       text=True).stdout:
    test_skipped("rsync built without IDN support")

src = FROMDIR
rmtree(src)
make_tree(src, depth=2)


def write_conf(path, modules, log, pidfile):
    lines = [
        '# autogenerated by daemon-access-idn_test.py',
        f'pid file = {pidfile}',
        'use chroot = no',
        'forward lookup = no',
        f'log file = {log}',
        '',
    ]
    for mod, params in modules:
        lines.append(f'[{mod}]')
        lines.append(f'\tpath = {src}')
        lines.append('\tread only = yes')
        lines += [f'\t{k} = {v}' for k, v in params.items()]
        lines.append('')
    # rsyncd.conf is read as UTF-8 by the daemon whatever the test's locale is.
    path.write_text('\n'.join(lines) + '\n', encoding='utf-8')
    return path


# --- find out what this host's resolver calls the loopback peer -------------
# A throwaway daemon with one wide-open module: connect once, read the name it
# logged for us, then shut it down before the real config goes up.
probe_log = SCRATCHDIR / 'rsyncd-idn-probe.log'
probe_conf = write_conf(SCRATCHDIR / 'access-idn-probe.conf', [('probe', {})],
                        probe_log, SCRATCHDIR / 'rsyncd-idn-probe.pid')
claim_ports(PROBE_PORT)
probe = start_rsyncd(probe_conf, PROBE_PORT)
try:
    subprocess.run(rsync_argv('-r', f'rsync://localhost:{PROBE_PORT}/probe/'),
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
finally:
    probe.terminate()
    probe.wait(timeout=5)

m = re.search(r'connect from (\S+) \(', probe_log.read_text(errors='replace'))
if not m:
    test_fail(f"no 'connect from' line in the probe daemon log {probe_log}")
peer = m.group(1)
print(f"daemon sees its peer as {peer!r}")


def fullwidth(name):
    """The fullwidth-forms spelling of an ASCII name.

    IDNA (UTS #46) maps U+FF01..U+FF5E back onto ASCII, so this gives us a
    genuinely non-ASCII name that folds to a peer name we can predict without
    controlling DNS.  Label separators stay ASCII dots.
    """
    return ''.join(chr(ord(c) - 0x21 + 0xFF01) if '!' <= c <= '~' and c != '.'
                   else c for c in name)


if fullwidth(peer) == peer:
    test_skipped(f"peer name {peer!r} has no ASCII to respell in fullwidth")

ZWSP = '​'         # maps to nothing, leaving no label at all
FW_STAR = '＊'      # FULLWIDTH ASTERISK, which IDNA maps to '*'
FW_SLASH = '／'     # FULLWIDTH SOLIDUS, which IDNA maps to '/'

modules = [
    ('ascii-name',    {'hosts allow': peer}),
    ('ascii-upper',   {'hosts allow': peer.upper()}),
    ('ascii-wild',    {'hosts allow': peer[:1] + '*'}),
    # The same name in fullwidth forms, which only matches once the token has
    # been folded to A-labels.
    ('idn-name',      {'hosts allow': fullwidth(peer)}),
    ('idn-mixedcase', {'hosts allow': fullwidth(peer.upper())}),
    ('idn-deny',      {'hosts deny': fullwidth(peer)}),
    # A real IDN that is not the peer, plus its punycode spelling: both must
    # stay denied, and neither may be mistaken for a wildcard.
    ('idn-other',     {'hosts allow': 'čičku.example'}),
    ('idn-puny',      {'hosts allow': 'xn--iku-eqab.example'}),
    # idn-other's token respelled with combining carons: an equivalent name
    # under Unicode, so it has to be treated the same way.  (A decomposed
    # token that *matches* isn't constructible here -- the peer name comes
    # from DNS and is ASCII -- so idn_test checks the two spellings convert
    # alike, and this checks the daemon agrees they don't match.)
    ('idn-nfd',       {'hosts allow': 'c\u030ci' 'c\u030cku.example'}),
    # Tokens whose IDNA mapping yields ASCII the author never wrote.  Left
    # unconverted they match nothing; converted blindly, the first two would
    # allow every host and the third would read as an address/mask.
    ('wide-star',     {'hosts allow': FW_STAR}),
    ('wide-star-dom', {'hosts allow': FW_STAR + '.example'}),
    ('wide-mask',     {'hosts allow': '127.0.0.0' + FW_SLASH + '8'}),
    # An IDN that can't be converted at all (its label maps to nothing).
    ('bad-idn',       {'hosts allow': ZWSP + '.example'}),
]

conf = write_conf(SCRATCHDIR / 'access-idn.conf', modules,
                  SCRATCHDIR / 'rsyncd.log', SCRATCHDIR / 'rsyncd.pid')
url = start_test_daemon(conf, DAEMON_PORT)


def connect(mod):
    """Return rsync's exit code for listing the module over the daemon."""
    return subprocess.run(rsync_argv('-r', f'{url}{mod}/'),
                          stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
                          text=True).returncode


def allowed(mod, why):
    if connect(mod) != 0:
        test_fail(f"connection to {mod} should be ALLOWED ({why}) but was refused")


def denied(mod, why):
    if connect(mod) == 0:
        test_fail(f"connection to {mod} should be DENIED ({why}) but succeeded")


allowed('ascii-name', "the peer's own name in a hosts allow")
allowed('ascii-upper', "hostname matching is case-insensitive")
allowed('ascii-wild', "an ASCII wildcard still matches")
allowed('idn-name', f"fullwidth {peer!r} folds to the peer's name")
allowed('idn-mixedcase', "IDNA case-folds the token")
denied('idn-deny', "hosts deny sees the folded token too")
denied('idn-other', "a different IDN must not match the peer")
denied('idn-puny', "an A-label for a different host must not match the peer")
denied('idn-nfd', "a decomposed spelling of that name must not match either")
denied('wide-star', "U+FF0A must not become a '*' that allows every host")
denied('wide-star-dom', "U+FF0A must not become a wildcard label")
denied('wide-mask', "U+FF0F must not become an address/mask separator")
denied('bad-idn', "an unconvertible IDN must not match anything")

print("daemon-access-idn: IDN hosts allow/deny matching + no wildcard widening")
