#!/usr/bin/python3 -I
"""Forced command behind every SSH and SFTP session of a website user (see panelcp/access.py).

sshd runs it through sudo, so it is root, but it does only one thing: it starts a container session as the hosting
account's user, with the rights the panel wrote for this login. The login name comes from sudo, not from the client.
"""
import json
import os
import re
import subprocess
import sys
import time

ACCESS = "/etc/panelcp/access"
DENY = {"download": ["read", "copy-data"], "rename": ["rename", "posix-rename"], "delete": ["remove", "rmdir"],
        "mkdir": ["mkdir"]}
ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "HOME": "/root", "LANG": "C.UTF-8", "DOCKER_CLI_HINTS": "false"}


def stop(text):
    sys.stderr.write(text + "\n")
    sys.exit(1)


def main():
    user = os.environ.get("SUDO_USER", "")
    if os.geteuid() != 0 or not re.match(r"^[a-z_][a-z0-9_-]{1,31}$", user):
        stop("This command is used by SSH logins only.")
    try:
        with open("%s/%s.json" % (ACCESS, user)) as f:
            a = json.load(f)
    except OSError:
        stop("This login no longer exists.")
    if not a["active"] or (a["expires"] and a["expires"] < time.time()):
        stop("This login is turned off.")
    who = "%d:%d" % (a["uid"], a["gid"])
    cmd = os.environ.get("SSH_ORIGINAL_COMMAND", "")

    if re.match(r"^(internal-sftp|(/usr)?/lib(exec)?/(openssh/)?sftp-server)(\s|$)", cmd):
        if not a["sftp"]:
            stop("SFTP is turned off for this login.")
        path = os.path.join(a["root"], a["folder"]) if a["folder"] else a["root"]
        # the folder may have been replaced by a link since the rights were saved
        if os.path.realpath(path) != path or not os.path.isdir(path):
            stop("The folder of this login no longer exists.")
        server = ["/usr/lib/openssh/sftp-server", "-d", "/files"]
        if "upload" not in a["rights"]:
            server.append("-R")
        deny = ["symlink", "hardlink"]
        for right, requests in DENY.items():
            if right not in a["rights"]:
                deny += requests
        server += ["-P", ",".join(deny)]
        args = ["docker", "run", "--rm", "-i", "--label", "panelcp.login=" + user, "--network", "none", "--user", who,
                "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--read-only", "--tmpfs", "/tmp:size=16m",
                "--memory", "128m", "--pids-limit", "16", "--log-driver", "none",
                "-v", a["passwd"] + ":/etc/passwd:ro", "--mount", "type=bind,source=%s,target=/files" % path,
                "-w", "/files", a["image"]] + server
        os.execve("/usr/bin/docker", args, ENV)

    if not a["ssh"]:
        stop("This login has no shell. Use SFTP or FTP.")
    state = subprocess.run(["/usr/bin/docker", "inspect", "-f", "{{.State.Status}}", a["container"]], env=ENV,
                           capture_output=True, text=True).stdout.strip()
    if state != "running":
        stop("The website is %s. Start it in the panel to use the shell. SFTP and FTP work meanwhile."
             % {"paused": "paused", "exited": "stopped"}.get(state, "not running"))
    args = ["docker", "exec", "-i"]
    if os.isatty(0):
        args += ["-t", "-e", "TERM=" + re.sub(r"[^\w.-]", "", os.environ.get("TERM", "xterm"))[:32]]
    args += ["--user", who, "-w", "/var/www/public", "-e", "HOME=/tmp", a["container"], "bash"]
    args += ["-c", cmd] if cmd else ["-l"]
    os.execve("/usr/bin/docker", args, ENV)


main()
