diff --git a/src/ciberwebscan/cli/output.py b/src/ciberwebscan/cli/output.py index 88b3a6e..411686a 100644 --- a/src/ciberwebscan/cli/output.py +++ b/src/ciberwebscan/cli/output.py @@ -119,6 +119,54 @@ def format_size(bytes_count: int | float) -> str: # ============================================================================ +def _get(obj: Any, key: str, default: Any = None) -> Any: + """Read a field from a form/field that may be a dict or an attribute object.""" + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + +def _format_form_line(form: Any, index: int) -> str: + """Format a single extracted form for CLI display. + + Renders the form's action and method, then one line per field showing + type, label, and brief markers for required/readonly/hidden/CSRF state. + Sensitive field values (e.g. tokens) are intentionally not printed. + """ + method = _get(form, "method", "GET") or "GET" + action = _get(form, "action", "") or "" + name = _get(form, "name", "") or "" + label = f" [{index}] {method} {action}" + if name: + label += f' (name="{name}")' + + lines = [label] + for field in _get(form, "fields", []) or []: + if not isinstance(field, dict): + continue + fname = field.get("name", "") or "?" + ftype = field.get("type", "text") + markers = [] + if field.get("required"): + markers.append("*") + if field.get("readonly"): + markers.append("RO") + if field.get("is_hidden"): + markers.append("HIDDEN") + if field.get("is_csrf_token"): + markers.append("CSRF") + marker_str = f" [{' '.join(markers)}]" if markers else "" + field_line = f" - {fname} ({ftype}){marker_str}" + flabel = field.get("label") + if flabel: + field_line += f' "{flabel}"' + options = field.get("options") + if options: + field_line += f" options={list(options)}" + lines.append(field_line) + return "\n".join(lines) + + def format_scrape_result(result: Any) -> None: """Format and print scrape result.""" if hasattr(result, "url"): @@ -134,6 +182,13 @@ def format_scrape_result(result: Any) -> None: if len(result.text_content) > 200: preview += "..." print_key_value("Content Preview", preview) + + # Forms (only when extraction was requested and forms were found) + forms = getattr(result, "forms", None) + if forms: + print_subheader(f"Forms ({len(forms)})") + for i, form in enumerate(forms, 1): + print(_format_form_line(form, i)) elif isinstance(result, list): print_header(f"Extracted Data ({len(result)} items)") for i, item in enumerate(result[:10], 1): diff --git a/src/ciberwebscan/core/scraping/extractor.py b/src/ciberwebscan/core/scraping/extractor.py index 9408f03..290d69b 100644 --- a/src/ciberwebscan/core/scraping/extractor.py +++ b/src/ciberwebscan/core/scraping/extractor.py @@ -405,6 +405,7 @@ def extract_images( def extract_forms( soup: BeautifulSoup, *, + base_url: str | None = None, selector: str = "form", ) -> list[dict[str, Any]]: """ @@ -412,21 +413,35 @@ def extract_forms( Args: soup: BeautifulSoup object. + base_url: Base URL for resolving relative form actions. selector: CSS selector for form elements. Returns: List of form dictionaries with 'action', 'method', 'fields', etc. Examples: - >>> forms = extract_forms(soup) + >>> forms = extract_forms(soup, base_url='https://example.com') >>> forms[0] - {'action': '/login', 'method': 'POST', 'fields': [...]} + {'action': 'https://example.com/login', 'method': 'POST', 'fields': [...]} """ + # Imported lazily to avoid coupling core.scraping to the attacks subsystem + # (core.attacks.__init__ eagerly loads every attacker + PayloadLoader). + from urllib.parse import urljoin + + from ciberwebscan.core.attacks.csrf import CSRF_TOKEN_NAMES + forms = [] for form in soup.select(selector): + # Resolve relative action URLs against the base URL, mirroring + # extract_links()/extract_images(). A missing action resolves to the + # page URL (per HTML spec) only when a base_url is provided. + action = str(form.get("action", "") or "") + if base_url: + action = urljoin(base_url, action) + form_data: dict[str, Any] = { - "action": form.get("action", ""), + "action": action, "method": str(form.get("method", "GET")).upper(), "enctype": form.get("enctype", ""), "id": form.get("id", ""), @@ -440,9 +455,13 @@ def extract_forms( if inp.name == "button" and not inp.get("name"): continue + # Preserve the raw type value (case included) to avoid changing + # existing observable data; lowercase only for the hidden check. + field_type = inp.get("type", "text") if inp.name == "input" else inp.name + field_data: dict[str, Any] = { "tag": inp.name, - "type": inp.get("type", "text") if inp.name == "input" else inp.name, + "type": field_type, "name": inp.get("name", ""), "value": inp.get("value", ""), "id": inp.get("id", ""), @@ -460,6 +479,16 @@ def extract_forms( field_data["readonly"] = inp.has_attr("readonly") field_data["disabled"] = inp.has_attr("disabled") + # Security metadata: a hidden field is any + # (case-insensitive per HTML spec). is_csrf_token is a name-based + # heuristic (single source: core.attacks.csrf.CSRF_TOKEN_NAMES) and + # does NOT prove the token is valid or protects the form. + is_hidden = str(field_type).lower() == "hidden" + field_data["is_hidden"] = is_hidden + field_data["is_csrf_token"] = is_hidden and ( + str(inp.get("name", "")).lower() in CSRF_TOKEN_NAMES + ) + # Extract select options if inp.name == "select": field_data["options"] = [ diff --git a/tests/unit/cli/test_output.py b/tests/unit/cli/test_output.py index 2310dc3..81dd4bf 100644 --- a/tests/unit/cli/test_output.py +++ b/tests/unit/cli/test_output.py @@ -3,11 +3,13 @@ from __future__ import annotations from datetime import datetime +from types import SimpleNamespace import pytest from ciberwebscan.cli.output import ( format_duration, + format_scrape_result, format_size, format_timestamp, print_dict, @@ -19,6 +21,7 @@ print_success, print_warning, ) +from ciberwebscan.export.models import FormInfo pytestmark = pytest.mark.unit @@ -131,3 +134,126 @@ def test_format_size_kilobytes(self): def test_format_size_megabytes(self): """Test size formatting in MB.""" assert format_size(1048576) == "1.0 MB" + + +class TestFormatScrapeResultForms: + """Tests for displaying extracted forms in scrape output.""" + + def _result(self, forms): + """Build a minimal object exposing the scrape-result attributes used.""" + return SimpleNamespace( + url="https://example.com", + status_code=200, + title="Page", + elapsed_ms=12.0, + text_content="body", + forms=forms, + ) + + def test_forms_section_displayed(self, capsys): + """Forms are shown with action and method.""" + forms = [{"action": "/login", "method": "POST", "fields": []}] + format_scrape_result(self._result(forms)) + out = capsys.readouterr().out + assert "Forms (1)" in out + assert "POST /login" in out + + def test_field_markers_displayed(self, capsys): + """Required, readonly, hidden and CSRF markers are shown.""" + forms = [ + { + "action": "/x", + "method": "POST", + "name": "f", + "fields": [ + {"name": "user", "type": "text", "required": True}, + {"name": "code", "type": "text", "readonly": True}, + { + "name": "csrfmiddlewaretoken", + "type": "hidden", + "is_hidden": True, + "is_csrf_token": True, + }, + ], + } + ] + format_scrape_result(self._result(forms)) + out = capsys.readouterr().out + assert "user (text) [*]" in out + assert "code (text) [RO]" in out + assert "csrfmiddlewaretoken (hidden) [HIDDEN CSRF]" in out + + def test_label_and_options_displayed(self, capsys): + """Labels and select options are rendered when present.""" + forms = [ + { + "action": "/x", + "method": "GET", + "fields": [ + { + "name": "plan", + "type": "select", + "label": "Plan", + "options": ["free", "pro"], + } + ], + } + ] + format_scrape_result(self._result(forms)) + out = capsys.readouterr().out + assert '"Plan"' in out + assert "options=['free', 'pro']" in out + + def test_token_value_not_printed(self, capsys): + """Sensitive token values are not echoed by default.""" + forms = [ + { + "action": "/x", + "method": "POST", + "fields": [ + { + "name": "csrf_token", + "type": "hidden", + "value": "SUPERSECRET", + "is_hidden": True, + "is_csrf_token": True, + } + ], + } + ] + format_scrape_result(self._result(forms)) + assert "SUPERSECRET" not in capsys.readouterr().out + + def test_empty_forms_list_no_section(self, capsys): + """An empty forms list renders no Forms section.""" + format_scrape_result(self._result([])) + out = capsys.readouterr().out + assert "Forms" not in out + + def test_missing_forms_attribute_no_crash(self, capsys): + """An object without a forms attribute renders without crashing.""" + result = SimpleNamespace( + url="https://example.com", + status_code=200, + title="Page", + elapsed_ms=1.0, + text_content="body", + ) + format_scrape_result(result) + out = capsys.readouterr().out + assert "Scrape Result" in out + assert "Forms" not in out + + def test_forminfo_objects_displayed(self, capsys): + """FormInfo model instances (attribute access) render correctly.""" + form = FormInfo( + action="/login", + method="POST", + name="login", + fields=[{"name": "user", "type": "text", "required": True}], + ) + format_scrape_result(self._result([form])) + out = capsys.readouterr().out + assert "POST /login" in out + assert '(name="login")' in out + assert "user (text) [*]" in out diff --git a/tests/unit/core/scraping/test_extract_forms.py b/tests/unit/core/scraping/test_extract_forms.py new file mode 100644 index 0000000..6fb3b4d --- /dev/null +++ b/tests/unit/core/scraping/test_extract_forms.py @@ -0,0 +1,364 @@ +""" +Unit tests for extract_forms. + +Covers form action resolution (absolute/relative/root/missing + base_url), +field metadata (labels, required, readonly, disabled), hidden-field and +CSRF-token detection (via the shared core.attacks.csrf.CSRF_TOKEN_NAMES +source), select options, buttons, and malformed/empty HTML. +""" + +from __future__ import annotations + +import pytest +from bs4 import BeautifulSoup + +from ciberwebscan.core.attacks.csrf import CSRF_TOKEN_NAMES +from ciberwebscan.core.scraping.extractor import extract_forms +from ciberwebscan.export.models import FormInfo + +pytestmark = pytest.mark.unit + + +def _soup(html: str) -> BeautifulSoup: + """Build a BeautifulSoup object from a controlled HTML fragment.""" + return BeautifulSoup(html, "html.parser") + + +def _field(form: dict, name: str) -> dict: + """Return the field dict with the given name from a form.""" + for f in form["fields"]: + if f["name"] == name: + return f + raise AssertionError(f"field {name!r} not found in form") + + +class TestActionResolution: + """Tests for form action URL resolution.""" + + def test_absolute_action_preserved(self): + """Absolute actions are left untouched.""" + soup = _soup('
') + result = extract_forms(soup, base_url="https://example.com") + assert result[0]["action"] == "https://other.com/submit" + + def test_root_relative_action(self): + """Root-relative actions resolve against the base domain.""" + soup = _soup('') + result = extract_forms(soup, base_url="https://example.com/dir/page") + assert result[0]["action"] == "https://example.com/login" + + def test_relative_action_with_base_url(self): + """Relative actions resolve against the base URL directory.""" + soup = _soup('') + result = extract_forms(soup, base_url="https://example.com/dir/page") + assert result[0]["action"] == "https://example.com/dir/submit.php" + + def test_missing_action_without_base_url(self): + """A missing action stays an empty string when no base_url is given.""" + soup = _soup("") + result = extract_forms(soup) + assert result[0]["action"] == "" + + def test_missing_action_with_base_url_resolves_to_base(self): + """With a base_url, a missing action resolves to the page URL (HTML spec).""" + soup = _soup("") + result = extract_forms(soup, base_url="https://example.com/dir/page") + assert result[0]["action"] == "https://example.com/dir/page" + + def test_no_base_url_keeps_raw_action(self): + """Without base_url the current raw semantics are preserved.""" + soup = _soup('') + result = extract_forms(soup) + assert result[0]["action"] == "/rel/path" + + def test_base_url_does_not_alter_absolute_scheme_relative(self): + """Protocol-relative actions resolve using the base scheme.""" + soup = _soup('') + result = extract_forms(soup, base_url="https://example.com/dir/page") + assert result[0]["action"] == "https://cdn.example.com/x" + + +class TestFormMetadata: + """Tests for method, enctype, id and name extraction.""" + + def test_method_defaults_to_get_and_uppercased(self): + soup = _soup("") + assert extract_forms(soup)[0]["method"] == "GET" + + def test_method_preserves_and_uppercases(self): + soup = _soup('') + assert extract_forms(soup)[0]["method"] == "POST" + + def test_enctype_id_name_extracted(self): + soup = _soup('') + form = extract_forms(soup)[0] + assert form["enctype"] == "multipart/form-data" + assert form["id"] == "f1" + assert form["name"] == "login" + + def test_multiple_forms(self): + soup = _soup('') + result = extract_forms(soup) + assert len(result) == 2 + assert result[0]["action"] == "/a" + assert result[1]["action"] == "/b" + + +class TestFieldTypes: + """Tests for input, textarea, select and button extraction.""" + + def test_input_type_defaults_to_text(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "q")["type"] == "text" + + def test_input_explicit_type(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "e")["type"] == "email" + + def test_input_type_case_preserved(self): + """The raw type value keeps its original case (observable data).""" + soup = _soup('') + assert _field(extract_forms(soup)[0], "q")["type"] == "TEXT" + + def test_tag_reflects_element(self): + soup = _soup( + '' + ) + form = extract_forms(soup)[0] + assert _field(form, "i")["tag"] == "input" + assert _field(form, "t")["tag"] == "textarea" + assert _field(form, "s")["tag"] == "select" + + def test_button_without_name_skipped(self): + soup = _soup('') + form = extract_forms(soup) + assert len(form[0]["fields"]) == 1 + + def test_button_with_name_included(self): + soup = _soup('') + field = _field(extract_forms(soup)[0], "action") + assert field["tag"] == "button" + assert field["value"] == "save" + + def test_placeholder_and_id_extracted(self): + soup = _soup('') + field = _field(extract_forms(soup)[0], "q") + assert field["id"] == "qid" + assert field["placeholder"] == "Search" + + def test_value_extracted(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "t")["value"] == "abc" + + +class TestLabelsAndValidation: + """Tests for label association and validation attributes.""" + + def test_label_by_for_attribute(self): + soup = _soup( + '' + ) + assert _field(extract_forms(soup)[0], "u")["label"] == "Username" + + def test_label_wrapping_field(self): + soup = _soup("") + assert _field(extract_forms(soup)[0], "e")["label"] == "Email" + + def test_no_label_is_empty_string(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "q")["label"] == "" + + def test_required_flag(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "q")["required"] is True + + def test_not_required_by_default(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "q")["required"] is False + + def test_readonly_flag(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "q")["readonly"] is True + + def test_disabled_flag(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "q")["disabled"] is True + + def test_pattern_maxlength_minlength(self): + soup = _soup( + '" + ) + field = _field(extract_forms(soup)[0], "q") + assert field["pattern"] == "[A-Z]+" + assert field["maxlength"] == "10" + assert field["minlength"] == "2" + + +class TestHiddenAndCsrf: + """Tests for hidden-field and CSRF-token detection.""" + + def test_hidden_input_detected(self): + soup = _soup('') + field = _field(extract_forms(soup)[0], "h") + assert field["is_hidden"] is True + assert field["is_csrf_token"] is False + + def test_hidden_detection_case_insensitive(self): + """type='HIDDEN' (uppercase) is still recognized as hidden.""" + soup = _soup('') + assert _field(extract_forms(soup)[0], "h")["is_hidden"] is True + + def test_visible_input_not_hidden(self): + soup = _soup('') + field = _field(extract_forms(soup)[0], "q") + assert field["is_hidden"] is False + assert field["is_csrf_token"] is False + + @pytest.mark.parametrize("token_name", sorted(CSRF_TOKEN_NAMES)) + def test_known_csrf_names_detected(self, token_name): + """Every name in the shared CSRF source is recognized when hidden.""" + soup = _soup(f'') + field = _field(extract_forms(soup)[0], token_name) + assert field["is_csrf_token"] is True + + def test_csrf_detection_case_insensitive_name(self): + """Field-name matching is case-insensitive.""" + soup = _soup('') + assert _field(extract_forms(soup)[0], "CSRFToken")["is_csrf_token"] is True + + def test_csrf_requires_hidden_type(self): + """A CSRF-named field that is NOT hidden is not flagged as a token.""" + soup = _soup('') + field = _field(extract_forms(soup)[0], "csrf_token") + assert field["is_csrf_token"] is False + assert field["is_hidden"] is False + + def test_hidden_non_csrf_not_flagged(self): + """A hidden field with an unrelated name is hidden but not CSRF.""" + soup = _soup('') + field = _field(extract_forms(soup)[0], "return_to") + assert field["is_hidden"] is True + assert field["is_csrf_token"] is False + + def test_single_shared_csrf_source(self): + """The detection uses the shared CSRF_TOKEN_NAMES set (no duplicate list).""" + assert "csrfmiddlewaretoken" in CSRF_TOKEN_NAMES + assert "csrf_token" in CSRF_TOKEN_NAMES + assert "xsrf" in CSRF_TOKEN_NAMES + + +class TestSelectOptions: + """Tests for select option extraction.""" + + def test_options_with_value(self): + soup = _soup( + '' + ) + assert _field(extract_forms(soup)[0], "c")["options"] == ["1"] + + def test_option_without_value_uses_text(self): + soup = _soup('') + assert _field(extract_forms(soup)[0], "c")["options"] == ["Two"] + + def test_multiple_options_order_preserved(self): + soup = _soup( + '' + ) + assert _field(extract_forms(soup)[0], "c")["options"] == ["a", "b"] + + def test_empty_select_yields_empty_options_list(self): + """An empty select yields an empty options list.""" + soup = _soup('') + assert _field(extract_forms(soup)[0], "c")["options"] == [] + + def test_non_select_fields_have_no_options(self): + """Only select elements carry an 'options' key.""" + soup = _soup('') + assert "options" not in _field(extract_forms(soup)[0], "q") + + +class TestEdgeCases: + """Tests for empty, malformed or attribute-less HTML.""" + + def test_empty_html_returns_no_forms(self): + assert extract_forms(_soup("")) == [] + + def test_html_without_forms(self): + assert extract_forms(_soup("No forms here