summaryrefslogtreecommitdiff
path: root/plugins/claude-security/scripts/lib/cwe.py
blob: 1f7a38bea81365180f95d04d5fd03de81eb9facd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""CWE data the plugin ships: the weaknesses, and the Simplified Mapping entry each belongs to."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import TypedDict, cast

from . import strictjson

UNCATEGORIZED = "Uncategorized"


class CategoryNames(TypedDict):
    """One entry's names in cwe-categories.json."""

    name: str
    title: str


class CatalogFile(TypedDict):
    """The shape of cwe-categories.json."""

    cwe_version: str
    categories: dict[str, CategoryNames]
    category_of: dict[str, int | None]


@dataclass(frozen=True)
class Category:
    """One entry of the view: its CWE number, its common name, its full catalog title."""

    number: int
    name: str
    title: str

    @property
    def id(self) -> str:
        """The entry's CWE id, `CWE-<number>`."""
        return f"CWE-{self.number}"


@dataclass(frozen=True)
class Catalog:
    """One CWE release: the view's entries, and for every weakness the entry it rolls up to."""

    version: str
    categories: dict[int, Category]
    category_of: dict[int, int | None]

    @classmethod
    def load(cls, path: Path) -> Catalog:
        """The catalog stored at `path`."""
        raw = cast("CatalogFile", strictjson.load(path))
        return cls(
            raw["cwe_version"],
            {
                int(number): Category(int(number), names["name"], names["title"])
                for number, names in raw["categories"].items()
            },
            {int(number): category for number, category in raw["category_of"].items()},
        )

    def category(self, cwe: int) -> Category | None:
        """The entry `cwe` rolls up to; None when it reaches none or is not a known weakness."""
        number = self.category_of.get(cwe)
        return self.categories[number] if number is not None else None

    def defines(self, cwe: int) -> bool:
        """Whether the release defines weakness `cwe` at all; category() is None either way."""
        return cwe in self.category_of


def id_number(cwe_id: str) -> int:
    """The number of a canonical `CWE-<number>` id, the spelling every validated finding carries."""
    return int(cwe_id.removeprefix("CWE-"))


catalog = Catalog.load(Path(__file__).resolve().with_name("cwe-categories.json"))