#!/usr/bin/env python3
"Read-only AWS Glue permission probes. Standalone Python Shell 3.9/boto3 script.\n\nRun in a separate Glue Job to test its actual execution Role. No role assumption, resource mutations, history APIs or S3 writes."

import argparse
from collections import Counter
from dataclasses import dataclass
import sys
from typing import Any, Callable, Dict, List, Optional, Tuple


VERSION = "1.0.8"
DEFAULT_REGION = "ap-northeast-1"
DENIED_CODES = {
    "AccessDenied", "AccessDeniedException", "UnauthorizedOperation",
    "UnauthorizedException", "AuthorizationError", "AuthorizationErrorException",
    "NotAuthorized", "NotAuthorizedException", "Forbidden", "ForbiddenException",
}
# This is the complete network-operation allowlist, not a name-prefix filter.
READ_OPERATIONS = {
    ("sts", "get_caller_identity"),
    ("glue", "list_workflows"), ("glue", "get_workflow"),
    ("glue", "list_jobs"), ("glue", "get_job"),
    ("glue", "list_triggers"), ("glue", "get_trigger"),
    ("glue", "get_jobs"),
}
CORE_LABELS = (
    "STS GetCallerIdentity", "Glue ListWorkflows", "Glue GetWorkflow",
    "Glue ListJobs", "Glue GetJob",
)


def safe_text(value: Any, limit: int = 700) -> str:
    "Keep logs bounded and on one line without rewriting string contents."
    value = "".join(char if char.isprintable() else " " for char in str(value))
    return value if len(value) <= limit else value[:limit] + "..."


@dataclass
class Result:
    label: str
    status: str
    detail: str = ""


class ReadOnlyAWS:
    "Lazy clients share the Job session and isolate client-creation failures."

    def __init__(self, session: Any, region: str, config: Any):
        self.session = session
        self.region = region
        self.config = config
        self.clients = {}  # type: Dict[str, Any]

    def call(self, service: str, operation: str, **kwargs: Any) -> Dict[str, Any]:
        if (service, operation) not in READ_OPERATIONS:
            raise ValueError("Operation is outside the read-only allowlist")
        if service not in self.clients:
            self.clients[service] = self.session.client(
                service, region_name=self.region, config=self.config,
            )
        return getattr(self.clients[service], operation)(**kwargs)


class PermissionCheck:
    def __init__(self, aws: ReadOnlyAWS, emit: Callable[[str], None] = print):
        self.aws = aws
        self.emit = emit
        self.results = []  # type: List[Result]

    def record(self, label: str, status: str, detail: str = "") -> None:
        detail = safe_text(detail)
        self.results.append(Result(label, status, detail))
        suffix = " | " + detail if detail else ""
        self.emit("[{:<7}] {}{}".format(status, label, suffix))

    def probe(self, label: str, action: Callable[[], Any]) -> Any:
        try:
            value = action()
        except Exception as exc:
            # ClientError exposes .response; never log the full exception/response.
            response = getattr(exc, "response", None)
            error = response.get("Error", {}) if isinstance(response, dict) else {}
            if isinstance(error, dict) and error.get("Code"):
                code = str(error["Code"])
                status = "DENIED" if code in DENIED_CODES else "ERROR"
                message = safe_text(error.get("Message", "No AWS error description"))
                self.record(label, status, "{}: {}".format(code, message))
            elif type(exc).__name__ == "ParamValidationError":
                self.record(label, "ERROR", "ParamValidationError: local request validation failed; "
                            "request was not sent to AWS. Check API parameter names/types.")
            else:
                # Network/credential/SDK exceptions may embed URLs or request data.
                self.record(label, "ERROR", "{} (details suppressed; check credentials, "
                            "network, Region and SDK)".format(type(exc).__name__))
            return None
        self.record(label, "OK")
        return value

    def sample(self, operation: str, key: str) -> Tuple[Optional[str], int]:
        "Read only enough pages to find one real sample, without listing values."
        token = None
        seen_tokens = set()
        pages = 0
        while True:
            kwargs = {"MaxResults": 25 if operation == "list_workflows" else 100}
            if token:
                kwargs["NextToken"] = token
            response = self.aws.call("glue", operation, **kwargs)
            pages += 1
            for name in response.get(key, []):
                if isinstance(name, str) and name:
                    return name, pages
            token = response.get("NextToken")
            if not token:
                return None, pages
            if token in seen_tokens:
                raise RuntimeError("RepeatedPaginationToken")
            seen_tokens.add(token)

    def get_sample_resource(
        self, label: str, operation: str, name: Optional[str], **kwargs: Any
    ) -> Optional[Dict[str, Any]]:
        if not name:
            self.record(label, "SKIPPED", "No sample; discovery failed or returned no names. "
                        "Supply the matching --SAMPLE_*_NAME parameter. Not permission approval.")
            return None
        # Resource names are not logged: they can contain operational information.
        request = dict(kwargs)
        request["JobName" if operation == "get_job" else "Name"] = name
        return self.probe(label, lambda: self.aws.call("glue", operation, **request))

    @staticmethod
    def graph_samples(response: Optional[Dict[str, Any]]) -> Tuple[Optional[str], Optional[str]]:
        job, trigger = None, None
        nodes = (response or {}).get("Workflow", {}).get("Graph", {}).get("Nodes", [])
        for node in nodes:
            if node.get("Type") == "JOB" and not job:
                job = node.get("Name")
            if node.get("Type") == "TRIGGER" and not trigger:
                trigger = node.get("Name") or node.get("TriggerDetails", {}).get("Trigger", {}).get("Name")
        return job, trigger

    def run(self, args: argparse.Namespace) -> List[Result]:
        self.emit("========== AWS Glue Permission Check ==========")
        self.emit("")
        self.emit("Region: " + safe_text(args.REGION))
        self.emit("Script version: " + VERSION)
        # The same default Session is used for STS and every Glue operation.
        identity = self.probe("STS GetCallerIdentity", lambda: self.aws.call("sts", "get_caller_identity"))
        arn = (identity or {}).get("Arn")
        self.emit("IAM Role: " + (safe_text(arn) if arn else "UNKNOWN (STS identity not verified)"))
        if arn and ":assumed-role/" not in arn:
            self.emit("[WARNING] Identity is not an assumed-role ARN. Run inside the intended Glue job.")
        self.emit("")

        workflows = self.probe("Glue ListWorkflows", lambda: self.sample("list_workflows", "Workflows"))
        workflow_name = args.SAMPLE_WORKFLOW_NAME or (workflows[0] if workflows else None)
        workflow = self.get_sample_resource(
            "Glue GetWorkflow", "get_workflow", workflow_name, IncludeGraph=True,
        )
        graph_job, graph_trigger = self.graph_samples(workflow)

        jobs = self.probe("Glue ListJobs", lambda: self.sample("list_jobs", "JobNames"))
        job_name = args.SAMPLE_JOB_NAME or (jobs[0] if jobs else None) or graph_job
        self.get_sample_resource("Glue GetJob", "get_job", job_name)

        # Always test ListTriggers, even when the graph or an override supplies a name.
        triggers = self.probe("Glue ListTriggers", lambda: self.sample("list_triggers", "TriggerNames"))
        trigger_name = args.SAMPLE_TRIGGER_NAME or graph_trigger or (triggers[0] if triggers else None)
        self.get_sample_resource("Glue GetTrigger", "get_trigger", trigger_name)

        if args.TEST_GET_JOBS:
            self.probe("Glue GetJobs", lambda: self.aws.call("glue", "get_jobs", MaxResults=1))
        else:
            self.record("Glue GetJobs", "SKIPPED", "Optional probe disabled; planned baseline uses "
                        "ListJobs + GetJob. Enable with --TEST_GET_JOBS true.")

        counts = Counter(result.status for result in self.results)
        self.emit("")
        self.emit("========== Result ==========")
        self.emit(" ".join("{}={}".format(status, counts[status])
                           for status in ("OK", "DENIED", "SKIPPED", "ERROR")))
        core_ok = all(any(r.label == label and r.status == "OK" for r in self.results)
                      for label in CORE_LABELS)
        self.emit("Required API sample checks: " + ("PASS" if core_ok else "INCOMPLETE"))
        self.emit("Only successful calls to tested samples are verified; account-wide coverage is NOT verified.")
        self.emit("SKIPPED is never a permission pass. Check the IAM Role ARN in this Glue job's logs.")
        self.emit("No resource changes, S3 output, or execution-history calls were requested by this script.")
        return self.results


def boolean(value: str) -> bool:
    if value.lower() in ("true", "1", "yes"):
        return True
    if value.lower() in ("false", "0", "no"):
        return False
    raise argparse.ArgumentTypeError("Use true or false")


def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
    parser.add_argument("--REGION", default=DEFAULT_REGION)
    parser.add_argument("--SAMPLE_WORKFLOW_NAME")
    parser.add_argument("--SAMPLE_JOB_NAME")
    parser.add_argument("--SAMPLE_TRIGGER_NAME")
    parser.add_argument("--TEST_GET_JOBS", type=boolean, default=False)
    parser.add_argument("--FAIL_ON_INCOMPLETE", type=boolean, default=False)
    # Glue injects parameters such as --JOB_NAME. Do not log or treat them as samples.
    args, _unknown = parser.parse_known_args(argv)
    return args


def exit_code(results: List[Result], strict: bool) -> int:
    if not strict:
        return 0
    return 2 if any(r.status != "OK" for r in results
                    if not (r.label == "Glue GetJobs" and r.status == "SKIPPED")) else 0


def main(argv: Optional[List[str]] = None) -> int:
    args = parse_args(argv)
    try:
        import boto3
        from botocore.config import Config
    except ImportError:
        print("[ERROR] boto3/botocore unavailable. Use Python Shell 3.9 with library-set=analytics.")
        return 1
    try:
        # No profile, static credentials or assume_role: use the Glue execution environment.
        session = boto3.session.Session()
        config = Config(
            connect_timeout=5, read_timeout=15,
            retries={"mode": "standard", "total_max_attempts": 3},
        )
    except Exception as exc:
        print("[ERROR] SDK initialization failed: " + safe_text(type(exc).__name__))
        return 1
    results = PermissionCheck(ReadOnlyAWS(session, args.REGION, config)).run(args)
    return exit_code(results, args.FAIL_ON_INCOMPLETE)


if __name__ == "__main__":
    sys.exit(main())
