Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/ciberwebscan/cli/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand All @@ -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):
Expand Down
37 changes: 33 additions & 4 deletions src/ciberwebscan/core/scraping/extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,28 +405,43 @@ def extract_images(
def extract_forms(
soup: BeautifulSoup,
*,
base_url: str | None = None,
selector: str = "form",
) -> list[dict[str, Any]]:
"""
Extract all forms from HTML.

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", ""),
Expand All @@ -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", ""),
Expand All @@ -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 <input type="hidden">
# (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"] = [
Expand Down
126 changes: 126 additions & 0 deletions tests/unit/cli/test_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -19,6 +21,7 @@
print_success,
print_warning,
)
from ciberwebscan.export.models import FormInfo

pytestmark = pytest.mark.unit

Expand Down Expand Up @@ -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
Loading
Loading