aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Doc/tools/extensions/audit_events.py
blob: 23d82c0f4414bff9fbee69484138bcba2cea52c5 (plain) (blame)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
"""Support for documenting audit events."""

from __future__ import annotations

import re
from typing import TYPE_CHECKING

from docutils import nodes
from sphinx.errors import NoUri
from sphinx.locale import _ as sphinx_gettext
from sphinx.transforms.post_transforms import SphinxPostTransform
from sphinx.util import logging
from sphinx.util.docutils import SphinxDirective

if TYPE_CHECKING:
    from collections.abc import Iterator

    from sphinx.application import Sphinx
    from sphinx.builders import Builder
    from sphinx.environment import BuildEnvironment

logger = logging.getLogger(__name__)

# This list of sets are allowable synonyms for event argument names.
# If two names are in the same set, they are treated as equal for the
# purposes of warning. This won't help if the number of arguments is
# different!
_SYNONYMS = [
    frozenset({"file", "path", "fd"}),
]


class AuditEvents:
    def __init__(self) -> None:
        self.events: dict[str, list[str]] = {}
        self.sources: dict[str, list[tuple[str, str]]] = {}

    def __iter__(self) -> Iterator[tuple[str, list[str], tuple[str, str]]]:
        for name, args in self.events.items():
            for source in self.sources[name]:
                yield name, args, source

    def add_event(
        self, name, args: list[str], source: tuple[str, str]
    ) -> None:
        if name in self.events:
            self._check_args_match(name, args)
        else:
            self.events[name] = args
        self.sources.setdefault(name, []).append(source)

    def _check_args_match(self, name: str, args: list[str]) -> None:
        current_args = self.events[name]
        msg = (
            f"Mismatched arguments for audit-event {name}: "
            f"{current_args!r} != {args!r}"
        )
        if current_args == args:
            return
        if len(current_args) != len(args):
            logger.warning(msg)
            return
        for a1, a2 in zip(current_args, args, strict=False):
            if a1 == a2:
                continue
            if any(a1 in s and a2 in s for s in _SYNONYMS):
                continue
            logger.warning(msg)
            return

    def id_for(self, name) -> str:
        source_count = len(self.sources.get(name, ()))
        name_clean = re.sub(r"\W", "_", name)
        return f"audit_event_{name_clean}_{source_count}"

    def rows(self) -> Iterator[tuple[str, list[str], list[tuple[str, str]]]]:
        for name in sorted(self.events.keys()):
            yield name, self.events[name], self.sources[name]


def initialise_audit_events(app: Sphinx) -> None:
    """Initialise the audit_events attribute on the environment."""
    if not hasattr(app.env, "audit_events"):
        app.env.audit_events = AuditEvents()


def audit_events_purge(
    app: Sphinx, env: BuildEnvironment, docname: str
) -> None:
    """This is to remove traces of removed documents from env.audit_events."""
    fresh_audit_events = AuditEvents()
    for name, args, (doc, target) in env.audit_events:
        if doc != docname:
            fresh_audit_events.add_event(name, args, (doc, target))


def audit_events_merge(
    app: Sphinx,
    env: BuildEnvironment,
    docnames: list[str],
    other: BuildEnvironment,
) -> None:
    """In Sphinx parallel builds, this merges audit_events from subprocesses."""
    for name, args, source in other.audit_events:
        env.audit_events.add_event(name, args, source)


class AuditEvent(SphinxDirective):
    has_content = True
    required_arguments = 1
    optional_arguments = 2
    final_argument_whitespace = True

    _label = [
        sphinx_gettext(
            "Raises an :ref:`auditing event <auditing>` "
            "{name} with no arguments."
        ),
        sphinx_gettext(
            "Raises an :ref:`auditing event <auditing>` "
            "{name} with argument {args}."
        ),
        sphinx_gettext(
            "Raises an :ref:`auditing event <auditing>` "
            "{name} with arguments {args}."
        ),
    ]

    def run(self) -> list[nodes.paragraph]:
        name = self.arguments[0]
        if len(self.arguments) >= 2 and self.arguments[1]:
            args = [
                arg
                for argument in self.arguments[1].strip("'\"").split(",")
                if (arg := argument.strip())
            ]
        else:
            args = []
        ids = []
        try:
            target = self.arguments[2].strip("\"'")
        except (IndexError, TypeError):
            target = None
        if not target:
            target = self.env.audit_events.id_for(name)
            ids.append(target)
        self.env.audit_events.add_event(name, args, (self.env.docname, target))

        node = nodes.paragraph("", classes=["audit-hook"], ids=ids)
        self.set_source_info(node)
        if self.content:
            node.rawsource = '\n'.join(self.content)  # for gettext
            self.state.nested_parse(self.content, self.content_offset, node)
        else:
            num_args = min(2, len(args))
            text = self._label[num_args].format(
                name=f"``{name}``",
                args=", ".join(f"``{a}``" for a in args),
            )
            node.rawsource = text  # for gettext
            parsed, messages = self.state.inline_text(text, self.lineno)
            node += parsed
            node += messages
        return [node]


class audit_event_list(nodes.General, nodes.Element):  # noqa: N801
    pass


class AuditEventListDirective(SphinxDirective):
    def run(self) -> list[audit_event_list]:
        return [audit_event_list()]


class AuditEventListTransform(SphinxPostTransform):
    default_priority = 500

    def run(self) -> None:
        if self.document.next_node(audit_event_list) is None:
            return

        table = self._make_table(self.app.builder, self.env.docname)
        for node in self.document.findall(audit_event_list):
            node.replace_self(table)

    def _make_table(self, builder: Builder, docname: str) -> nodes.table:
        table = nodes.table(cols=3)
        group = nodes.tgroup(
            "",
            nodes.colspec(colwidth=30),
            nodes.colspec(colwidth=55),
            nodes.colspec(colwidth=15),
            cols=3,
        )
        head = nodes.thead()
        body = nodes.tbody()

        table += group
        group += head
        group += body

        head += nodes.row(
            "",
            nodes.entry("", nodes.paragraph("", "Audit event")),
            nodes.entry("", nodes.paragraph("", "Arguments")),
            nodes.entry("", nodes.paragraph("", "References")),
        )

        for name, args, sources in builder.env.audit_events.rows():
            body += self._make_row(builder, docname, name, args, sources)

        return table

    @staticmethod
    def _make_row(
        builder: Builder,
        docname: str,
        name: str,
        args: list[str],
        sources: list[tuple[str, str]],
    ) -> nodes.row:
        row = nodes.row()
        name_node = nodes.paragraph("", nodes.Text(name))
        row += nodes.entry("", name_node)

        args_node = nodes.paragraph()
        for arg in args:
            args_node += nodes.literal(arg, arg)
            args_node += nodes.Text(", ")
        if len(args_node.children) > 0:
            args_node.children.pop()  # remove trailing comma
        row += nodes.entry("", args_node)

        backlinks_node = nodes.paragraph()
        backlinks = enumerate(sorted(set(sources)), start=1)
        for i, (doc, label) in backlinks:
            if isinstance(label, str):
                ref = nodes.reference("", f"[{i}]", internal=True)
                try:
                    target = (
                        f"{builder.get_relative_uri(docname, doc)}#{label}"
                    )
                except NoUri:
                    continue
                else:
                    ref["refuri"] = target
                    backlinks_node += ref
        row += nodes.entry("", backlinks_node)
        return row


def setup(app: Sphinx):
    app.add_directive("audit-event", AuditEvent)
    app.add_directive("audit-event-table", AuditEventListDirective)
    app.add_post_transform(AuditEventListTransform)
    app.connect("builder-inited", initialise_audit_events)
    app.connect("env-purge-doc", audit_events_purge)
    app.connect("env-merge-info", audit_events_merge)
    return {
        "version": "1.0",
        "parallel_read_safe": True,
        "parallel_write_safe": True,
    }