#!/usr/bin/env python3

import os
import stat
import subprocess
import time

from fixtures.rrsync import patched_rrsync
from harness.environment import SCRATCHDIR
from harness.filesystem import makepath, proc_self_fd_pins, rmtree
from harness.results import test_fail, test_skipped
from harness import metadata

metadata(features={'proc_fd'}, transports={'pipe'})

if not proc_self_fd_pins():
    test_skipped("rrsync's inode pin needs /proc/self/fd (Linux); the "
                 "unhardened fallback elsewhere is by design", capability='proc_fd')

MARKER = 'AUDIT_PARENT_PIN_MARKER_DO_NOT_DISCLOSE'

base = SCRATCHDIR / 'rrsync-parent-pin'
rmtree(base)
restricted = base / 'restricted'
outside = base / 'outside'
makepath(restricted, outside)

outdir = outside / 'dir'
makepath(outdir)
(outdir / 'target').write_text(MARKER + '\n')
(outdir / 'afifo').write_text(MARKER + '\n')

realdir = restricted / 'dir'
makepath(realdir)
os.symlink('missing-sibling', realdir / 'target')
os.mkfifo(realdir / 'afifo')

ready = base / 'stub-ready'
go = base / 'stub-go'
report = base / 'stub-report'

stub = base / 'rsync-stub'
stub.write_text(f'''#!/usr/bin/env python3
import os, stat, sys, time
arg = sys.argv[-1]
open({str(ready)!r}, 'w').close()
for _ in range(600):
    if os.path.exists({str(go)!r}):
        break
    time.sleep(0.05)
try:
    st = os.lstat(arg)
except OSError as e:
    out = 'error %s' % e.strerror
else:
    if stat.S_ISLNK(st.st_mode):
        out = 'symlink %s' % os.readlink(arg)
    elif stat.S_ISFIFO(st.st_mode):
        out = 'fifo'
    elif stat.S_ISREG(st.st_mode):
        out = 'regular %s' % open(arg).read().strip()
    elif stat.S_ISDIR(st.st_mode):
        out = 'directory'
    else:
        out = 'other'
with open({str(report)!r}, 'w') as f:
    f.write('%s\\n%s\\n' % (arg, out))
''')
stub.chmod(0o755)

rrsync = patched_rrsync(base, rsync_path=str(stub))

evil = restricted / 'evil'
os.symlink(str(outdir), evil)

def resolve_with_parent_swapped(source):
    for p in (ready, go, report):
        if p.exists():
            p.unlink()

    cmd = ('rsync --server --sender -logDtpre.iLsfxC . %s' % source)
    proc = subprocess.Popen(
        [str(rrsync), '-ro', str(restricted)],
        env={**os.environ, 'SSH_ORIGINAL_COMMAND': cmd},
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)

    deadline = time.monotonic() + 30
    while time.monotonic() < deadline and not ready.exists():
        if proc.poll() is not None:
            break
        time.sleep(0.02)
    if not ready.exists():
        out = proc.communicate()[0]
        test_fail(f'the stub never ran for {source!r}, so nothing was tested '
                  f'(rc={proc.returncode}, output={out.strip()[:300]!r})')

    os.rename(realdir, base / 'stash')
    os.rename(evil, realdir)

    go.touch()
    out = proc.communicate(timeout=60)[0]

    os.rename(realdir, evil)
    os.rename(base / 'stash', realdir)

    if not report.exists():
        test_fail(f'the stub produced no report for {source!r} '
                  f'(rc={proc.returncode}, output={out.strip()[:300]!r})')
    handed, saw = report.read_text().splitlines()
    return handed, saw

os.rename(realdir, base / 'stash')
os.rename(evil, realdir)
try:
    probe = os.path.join(str(restricted), 'dir/target')
    st = os.lstat(probe)
    if not stat.S_ISREG(st.st_mode) or MARKER not in open(probe).read():
        test_fail('control failed: with "dir" swapped, the bare name '
                  'dir/target does not reach the outside file, so this test '
                  'cannot tell a pinned resolution from an unpinned one')
finally:
    os.rename(realdir, evil)
    os.rename(base / 'stash', realdir)

handed, saw = resolve_with_parent_swapped('dir/target')
if saw != 'symlink missing-sibling':
    test_fail(f'a dangling-symlink leaf resolved to {saw!r} after its parent '
              f'was swapped for a symlink out of the tree; expected the '
              f'in-tree "symlink missing-sibling".  rsync was handed '
              f'{handed!r} -- an unpinned name puts every component back in '
              'play, which is CVE-2026-53783')

handed, saw = resolve_with_parent_swapped('dir/afifo')
if saw != 'fifo':
    test_fail(f'a FIFO leaf resolved to {saw!r} after its parent was swapped '
              f'for a symlink out of the tree; expected the in-tree "fifo".  '
              f'rsync was handed {handed!r}')

print('a sender leaf rrsync never opens still resolves beneath its pinned '
      'parent when the parent is swapped out from under it')
