Skip to content

Finding

sereto.tui.finding

AddFindingScreen

Bases: ModalScreen[None]

Source code in sereto/tui/finding.py
 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
class AddFindingScreen(ModalScreen[None]):
    BINDINGS = [("escape", "dismiss", "Dismiss finding")]

    def __init__(self, templates: DirectoryPath, finding: FindingMetadata, title: str) -> None:
        super().__init__()
        self.templates = templates
        self.finding = finding
        self.title = title

    def compose(self) -> ComposeResult:
        app: SeretoApp = self.app  # type: ignore[assignment]
        all_targets = [t for v in app.project.config.versions for t in app.project.config.at_version(v).targets]

        with ScrollableContainer(id="add-finding"):
            # Name
            self.input_name = Input(value=self.finding.name)
            yield InputWithLabel(self.input_name, label="Name")
            # Risk
            risks = [r.capitalize() for r in Risk]
            self.select_risk = SelectWithLabel[str](options=[(r, r) for r in risks], label="Risk")
            yield self.select_risk
            # Target
            self.select_target = SelectWithLabel[str](
                options=[(t.uname, t.uname) for t in all_targets],
                label="Target",
                allow_blank=False,
            )
            yield self.select_target

            # Existing finding warning + overwrite switch
            self.overwrite_switch = Switch(value=False, name="overwrite", id="overwrite-switch")
            self.overwrite_warning = Horizontal(
                self.overwrite_switch,
                Static(
                    "[b red]Warning:[/b red] A finding with this name already exists in the selected target.\n"
                    "  [b]Switch OFF:[/b] Keep the original and create a new one with a random suffix.\n"
                    "  [b]Switch ON:[/b] Overwrite the existing finding."
                ),
                id="overwrite-warning",
            )
            self.overwrite_warning.display = False
            yield self.overwrite_warning

            yield Static("[b]Variables", classes="section-header")
            yield Rule()

            for var in self.finding.variables:
                yield Static(f"[b]{var.name}:[/b] {escape(var.type_annotation)}\n  {var.description}", classes="pl-1")
                if var.is_list:
                    match var.type:
                        case "boolean":
                            yield ListWidget(
                                widget_factory=lambda var=var: Select(  # type: ignore[misc]
                                    options=[
                                        ("True", True),
                                        ("False", False),
                                    ],
                                    allow_blank=not var.required,
                                ),
                                id=f"var-{var.name}",
                            )
                        case "integer":
                            yield ListWidget(
                                widget_factory=lambda: Input(type="integer", classes="m-1"),
                                id=f"var-{var.name}",
                            )
                        case _:
                            yield ListWidget(
                                widget_factory=lambda: Input(classes="m-1"),
                                id=f"var-{var.name}",
                            )
                else:
                    match var.type:
                        case "boolean":
                            yield Select(
                                options=[
                                    ("True", True),
                                    ("False", False),
                                ],
                                allow_blank=not var.required,
                                id=f"var-{var.name}",
                            )
                        case "integer":
                            yield Input(id=f"var-{var.name}", type="integer", classes="m-1")
                        case _:
                            yield Input(id=f"var-{var.name}", classes="m-1")
                yield Rule()

            self.btn_save_finding = Button.success("Save", id="save-finding", classes="m-1")
            yield self.btn_save_finding

    def on_mount(self) -> None:
        add_finding = self.query_one("#add-finding")
        add_finding.border_title = self.title
        add_finding.border_subtitle = "Esc to close"

    def on_select_changed(self, event: Select.Changed) -> None:
        if event.select is self.select_target.query_one(Select):
            self.update_overwrite_warning()

    def update_overwrite_warning(self) -> None:
        """Update the overwrite warning and switch dynamically."""
        try:
            target = self._retrieve_target()
        except Exception:
            self.overwrite_warning.display = False
            return

        finding_path = target.findings.get_path(
            name=self.finding.path.name.removesuffix(".md.j2"),
            category=self.finding.category.lower(),
        )
        self.overwrite_warning.display = finding_path.is_file()

    def _load_variables(self) -> dict[str, Any]:
        """Load variables from the inputs.
        Raises:
            SeretoValueError: If a required variable is not set.
        """
        variables: dict[str, Any] = {}

        for var in self.finding.variables:
            if var.is_list:
                widgets = list(self.query_one(f"#var-{var.name}", ListWidget).query(".widget").results())

                match var.type:
                    case "boolean":
                        # get values, filter out NoSelection
                        values = [
                            w.value for w in widgets if isinstance(w, Select) and not isinstance(w.value, NoSelection)
                        ]
                    case "integer":
                        values_str = [
                            w.value.strip() for w in widgets if isinstance(w, Input) and len(w.value.strip()) > 0
                        ]
                        try:
                            values = [int(v) for v in values_str]
                        except ValueError:
                            raise SeretoValueError(f"variable '{var.name}' must be an integer") from None
                    case _:
                        values = [
                            w.value.strip() for w in widgets if isinstance(w, Input) and len(w.value.strip()) > 0
                        ]

                if var.required and len(values) == 0:
                    raise SeretoValueError(f"variable '{var.name}' is required")
                elif len(values) == 0:
                    # don't set the variable if not required and empty
                    continue
                # always set list variables, even if empty
                variables[var.name] = values
                continue
            else:
                match var.type:
                    case "boolean":
                        value_select: Select[bool] = self.query_one(f"#var-{var.name}", Select)
                        value: int | str | None = (
                            value_select.value if not isinstance(value_select.value, NoSelection) else None
                        )
                    case "integer":
                        value_str = self.query_one(f"#var-{var.name}", Input).value.strip()
                        if len(value_str) == 0:
                            if var.required:
                                raise SeretoValueError(f"variable '{var.name}' is required")
                            else:
                                continue
                        try:
                            value = int(value_str)
                        except ValueError:
                            raise SeretoValueError(f"variable '{var.name}' must be an integer") from None
                    case _:
                        value = self.query_one(f"#var-{var.name}", Input).value.strip()
                        if len(value) == 0:
                            if var.required:
                                raise SeretoValueError(f"variable '{var.name}' is required")
                            else:
                                # don't set the variable if not required and empty
                                continue
                variables[var.name] = value

        return variables

    def _retrieve_target(self) -> Target:
        """Retrieve the target from the select input.

        Returns:
            The target object corresponding to the selected value.

        Raises:
            SeretoValueError: If the target is not found.
        """
        app: SeretoApp = self.app  # type: ignore[assignment]

        target_select: Select[str] = self.select_target.query_one(Select)
        all_targets = [t for v in app.project.config.versions for t in app.project.config.at_version(v).targets]

        matching_target = [t for t in all_targets if t.uname == target_select.value]
        if len(matching_target) != 1:
            raise SeretoValueError(f"target with uname {target_select.value!r} not found")

        return matching_target[0]

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Handle Save button press event."""
        if event.button is not self.btn_save_finding:
            return

        app: SeretoApp = self.app  # type: ignore[assignment]

        # Retrieve the values from the inputs
        # - name
        name = self.input_name.value
        # - risk
        risk_select: Select[str] = self.select_risk.query_one(Select)
        risk = Risk(risk_select.value.lower()) if not isinstance(risk_select.value, NoSelection) else None
        # - target
        target = self._retrieve_target()

        # - variables
        try:
            variables = self._load_variables()
        except SeretoValueError as ex:
            self.notify(title="Validation error", message=str(ex), severity="error")
            return

        # Create the sub-finding
        target.findings.add_from_template(
            templates=self.templates,
            template_path=self.finding.path,
            category=self.finding.category.lower(),
            name=name,
            risk=risk,
            variables=variables,
            overwrite=self.overwrite_switch.display and self.overwrite_switch.value,
        )

        # Navigate back, focus on the search input field
        self.dismiss()
        self.notify(message=name, title="Finding successfully added")
        app.action_focus_search()

on_button_pressed(event)

Handle Save button press event.

Source code in sereto/tui/finding.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def on_button_pressed(self, event: Button.Pressed) -> None:
    """Handle Save button press event."""
    if event.button is not self.btn_save_finding:
        return

    app: SeretoApp = self.app  # type: ignore[assignment]

    # Retrieve the values from the inputs
    # - name
    name = self.input_name.value
    # - risk
    risk_select: Select[str] = self.select_risk.query_one(Select)
    risk = Risk(risk_select.value.lower()) if not isinstance(risk_select.value, NoSelection) else None
    # - target
    target = self._retrieve_target()

    # - variables
    try:
        variables = self._load_variables()
    except SeretoValueError as ex:
        self.notify(title="Validation error", message=str(ex), severity="error")
        return

    # Create the sub-finding
    target.findings.add_from_template(
        templates=self.templates,
        template_path=self.finding.path,
        category=self.finding.category.lower(),
        name=name,
        risk=risk,
        variables=variables,
        overwrite=self.overwrite_switch.display and self.overwrite_switch.value,
    )

    # Navigate back, focus on the search input field
    self.dismiss()
    self.notify(message=name, title="Finding successfully added")
    app.action_focus_search()

update_overwrite_warning()

Update the overwrite warning and switch dynamically.

Source code in sereto/tui/finding.py
177
178
179
180
181
182
183
184
185
186
187
188
189
def update_overwrite_warning(self) -> None:
    """Update the overwrite warning and switch dynamically."""
    try:
        target = self._retrieve_target()
    except Exception:
        self.overwrite_warning.display = False
        return

    finding_path = target.findings.get_path(
        name=self.finding.path.name.removesuffix(".md.j2"),
        category=self.finding.category.lower(),
    )
    self.overwrite_warning.display = finding_path.is_file()

SeretoApp

Bases: App[None]

A SeReTo Textual CLI interface.

Source code in sereto/tui/finding.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
class SeretoApp(App[None]):
    """A SeReTo Textual CLI interface."""

    CSS_PATH = "finding.tcss"
    TITLE = "SeReTo"
    SUB_TITLE = "Security Reporting Tool"
    BINDINGS = [("/", "focus_search", "Focus on search")]

    def __init__(
        self,
        project: Project,
        categories: list[str],
    ) -> None:
        super().__init__()
        self.project = project
        self.categories = categories

    def compose(self) -> ComposeResult:
        """Add widgets to the app."""
        # adding findings only works if there is at least one target
        if len(self.project.config.last_config.targets) == 0:
            raise SeretoValueError("no targets found in the configuration")

        yield Header()
        yield SearchWidget(id="search")
        yield ResultsWidget(id="results")
        yield Footer()

    def action_focus_search(self) -> None:
        """Focus on the search input field."""
        self.query_one("#search", SearchWidget).input_field.focus()

Focus on the search input field.

Source code in sereto/tui/finding.py
454
455
456
def action_focus_search(self) -> None:
    """Focus on the search input field."""
    self.query_one("#search", SearchWidget).input_field.focus()

compose()

Add widgets to the app.

Source code in sereto/tui/finding.py
443
444
445
446
447
448
449
450
451
452
def compose(self) -> ComposeResult:
    """Add widgets to the app."""
    # adding findings only works if there is at least one target
    if len(self.project.config.last_config.targets) == 0:
        raise SeretoValueError("no targets found in the configuration")

    yield Header()
    yield SearchWidget(id="search")
    yield ResultsWidget(id="results")
    yield Footer()