#!/usr/bin/python3
"""Check packaged authorization defaults and permissions without running helpers."""

from pathlib import Path
import stat
import xml.etree.ElementTree as ET


POLICY = Path("/usr/share/polkit-1/actions/org.zulucrypt.zulupolkit.policy")
HELPER = Path("/usr/bin/zuluPolkit")
CLI_PROGRAMS = (Path("/usr/bin/zuluCrypt-cli"), Path("/usr/bin/zuluMount-cli"))


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def check_policy(path):
    root = ET.parse(path).getroot()
    require(root.tag == "policyconfig", "Unexpected policy document root")
    actions = root.findall("action")
    require(len(actions) == 1, "Expected exactly one zuluPolkit action")
    action = actions[0]
    require(action.get("id") == "org.zulucrypt.zulupolkit", "Wrong action ID")
    defaults = action.findall("defaults")
    require(len(defaults) == 1, "Expected exactly one defaults block")
    entries = list(defaults[0])
    expected = {"allow_any", "allow_inactive", "allow_active"}
    require(len(entries) == 3 and {entry.tag for entry in entries} == expected,
            "Missing, duplicated or unexpected authorization defaults")
    for entry in entries:
        require((entry.text or "").strip() == "auth_admin",
                f"{entry.tag} must require administrator authentication")
    annotations = action.findall("annotate")
    require(len(annotations) == 1, "Unexpected policy annotations")
    require(annotations[0].get("key") == "org.freedesktop.policykit.exec.path",
            "Wrong executable annotation key")
    require((annotations[0].text or "").strip() == str(HELPER),
            "Policy must authorize the installed zuluPolkit executable")


def check_permissions(path, executable=False):
    info = path.stat()
    require(stat.S_ISREG(info.st_mode), f"{path} must resolve to a regular file")
    require(info.st_uid == 0, f"{path} must be owned by root")
    require(not info.st_mode & (stat.S_IWGRP | stat.S_IWOTH),
            f"{path} must not be writable by group or others")
    require(not info.st_mode & (stat.S_ISUID | stat.S_ISGID),
            f"{path} must not have setuid/setgid permissions")
    if executable:
        require(info.st_mode & stat.S_IXUSR, f"{path} must be executable")


def main():
    check_policy(POLICY)
    check_permissions(POLICY)
    for executable in (HELPER, *CLI_PROGRAMS):
        check_permissions(executable, executable=True)
    print("PASS: administrator authentication required; no setuid/setgid helpers")


if __name__ == "__main__":
    main()
