from pypanther import LogType, Rule, RuleTest, Severity, panther_managed
from pypanther.helpers.github import github_alert_context


@panther_managed
class GithubRepoVulnerabilityDismissed(Rule):
    display_name = "GitHub Dependabot Vulnerability Dismissed"
    id = "Github.Repo.VulnerabilityDismissed-prototype"
    default_severity = Severity.HIGH
    default_description = "Creates an alert if a dependabot alert is dismissed without being fixed.\n"
    log_types = [LogType.GITHUB_AUDIT]

    def rule(self, event):
        if event.get("action") == "repository_vulnerability_alert.dismiss":
            return True
        return False

    def title(self, event):
        return f"GitHub Dependabot Vulnerability Dismissed by {event.get('actor')}: {event.get('repo')}"

    def alert_context(self, event):
        context = github_alert_context(event)
        alert_url = f"https://github.com/{event.get('repo')}/security/dependabot/{event.get('alert_number')}"
        return context | {"alert_url": alert_url}

    tests = [
        RuleTest(
            name="Not GitHub Dependabot Vulnerability Dismissed",
            expected_result=False,
            log={"action": "not_repository_vulnerability_alert.dismiss"},
        ),
        RuleTest(
            name="GitHub Dependabot Vulnerability Dismissed",
            expected_result=True,
            log={
                "_document_id": "Z7JUOWzi2wKeWsZcOhbS9w",
                "action": "repository_vulnerability_alert.dismiss",
                "active": True,
                "actor": "badger",
                "actor_id": "1234567",
                "actor_is_bot": False,
                "alert_number": 8,
                "at_sign_timestamp": "2024-04-09 06:17:55.186000000",
                "business": "acme",
                "business_id": "11244",
                "created_at": "2024-03-13 22:36:27.788000000",
                "external_identity_nameid": "badger@acme.com",
                "ghsa_id": "GHSA-1234-5678-9090",
                "operation_type": "modify",
                "org": "acme",
                "org_id": 42053323,
                "public_repo": True,
                "repo": "acme/repo",
                "repo_id": 6532371245,
                "user": "badger",
                "user_agent": "Mozilla/5.0 (Macintosh Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
                "user_id": "1270063",
            },
        ),
    ]
