Skip to content

Finding

sereto.tui.finding

AddFindingScreen

Bases: ModalScreen[None]

Source code in sereto/tui/finding.py
 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
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

            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:
                    yield ListInput(id=f"var-{var.name}")
                else:
                    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 _load_variables(self) -> dict[str, Any]:
        """Load variables from the inputs.

        Returns:
            A dictionary of variables with their values.

        Raises:
            SeretoValueError: If a required variable is not set.
        """
        variables: dict[str, Any] = {}

        for var in self.finding.variables:
            if var.is_list:
                all_inputs = self.query_one(f"#var-{var.name}", ListInput).query(Input).results()
                input_values = [input.value.strip() for input in all_inputs if len(input.value.strip()) > 0]
                if var.required and len(input_values) == 0:
                    raise SeretoValueError(f"variable '{var.name}' is required")
                else:
                    # always set list variables, even if empty
                    variables[var.name] = input_values
            else:
                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
                else:
                    variables[var.name] = value

        return variables

    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  # TODO: check for None, report "Name is required"
        # - 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_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")
        target = matching_target[0]

        # - 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,
        )

        # 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
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
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  # TODO: check for None, report "Name is required"
    # - 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_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")
    target = matching_target[0]

    # - 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,
    )

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

SeretoApp

Bases: App[None]

A SeReTo Textual CLI interface.

Source code in sereto/tui/finding.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
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
336
337
338
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
325
326
327
328
329
330
331
332
333
334
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()