#!/usr/bin/env python3

import os
import subprocess

from harness.mutation import find_attacker_uid
from harness.daemon_config import write_daemon_conf
from harness.daemon import start_test_daemon
from harness.environment import FROMDIR, SCRATCHDIR
from harness.filesystem import make_tree, makepath, rmtree
from harness.results import test_fail
from harness.rsync import rsync_argv
from harness import metadata

metadata(transports={'pipe', 'tcp'})

DAEMON_PORT = 12910

os.environ['RSYNC_PASSWORD'] = 'env-fallback-wrong'

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

authdir = SCRATCHDIR / 'strictdest'
secrets = SCRATCHDIR / 'rsyncd.strict.secrets'
secrets.write_text('tuser:secretpass\n')
secrets.chmod(0o600)

conf = write_daemon_conf([
    ('strict', {'path': str(authdir), 'read only': 'no',
                'auth users': 'tuser', 'secrets file': str(secrets),
                'strict modes': 'yes'}),
    ('loose',  {'path': str(authdir), 'read only': 'no',
                'auth users': 'tuser', 'secrets file': str(secrets),
                'strict modes': 'no'}),
], name='strict-modes.conf')
url = start_test_daemon(conf, DAEMON_PORT)

def pwfile():
    p = SCRATCHDIR / 'pw.strict'
    p.write_text('secretpass\n')
    p.chmod(0o600)
    return p

PW = pwfile()

def accepted(module):
    rmtree(authdir)
    makepath(authdir)
    userurl = url.replace('rsync://', 'rsync://tuser@', 1)
    proc = subprocess.run(
        rsync_argv('-a', f'--password-file={PW}', f'{src}/', f'{userurl}{module}/'),
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
        stdin=subprocess.DEVNULL)
    return proc.returncode in (0, 23)

MODE_GRID = [
    (0o600, True,  'owner rw only'),
    (0o400, True,  'owner r only'),
    (0o640, True,  'group READ -> still accepted (group bits unchecked)'),
    (0o660, True,  'group rw -> accepted'),
    (0o610, True,  'group exec -> accepted'),
    (0o601, True,  'other EXEC only -> accepted (& 06 ignores the x bit)'),
    (0o604, False, 'other READ -> rejected'),
    (0o602, False, 'other WRITE -> rejected'),
    (0o606, False, 'other rw -> rejected'),
    (0o644, False, 'world-readable -> rejected'),
    (0o666, False, 'world rw -> rejected'),
]

grid, mism = [], []
for mode, want, note in MODE_GRID:
    secrets.chmod(mode)
    got = accepted('strict')
    grid.append(f"strict 0{mode:04o} accepted={int(got)} want={int(want)}  {note}")
    if got != want:
        mism.append(f"strict modes, 0{mode:04o}: accepted={got}, expected={want} ({note})")

secrets.chmod(0o666)
got = accepted('loose')
grid.append(f"loose  00666 accepted={int(got)} want=1  strict modes=no skips the check")
if not got:
    mism.append("strict modes=no still rejected a 0666 secrets file")

ATT = find_attacker_uid() if os.geteuid() == 0 else None
if ATT is not None:
    secrets.chmod(0o600)
    os.chown(secrets, ATT, ATT)
    got = accepted('strict')
    grid.append(f"strict 00600 owner={ATT} accepted={int(got)} want=0  "
                f"non-root owner rejected when daemon is root")
    if got:
        mism.append("strict modes accepted a non-root-owned secrets file under a root daemon")
    os.chown(secrets, 0, 0)
else:
    grid.append("strict owner-mismatch row SKIPPED (needs root daemon + unprivileged uid)")

secrets.chmod(0o600)

if os.environ.get('REPORT_MODES'):
    test_fail("REPORT-MODES grid:\n  " + "\n  ".join(grid))
if mism:
    test_fail("strict-modes contract deviated:\n  " + "\n  ".join(mism))

print('strict modes rejects other-read, other-write and invalid ownership')
