From 5b90b4a0861138d630be7b2be20ffce656f49016 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 01:30:46 +0000 Subject: [PATCH 01/18] test: specify Flask route and app metadata Signed-off-by: Flavio Oliva --- tests/flask/test_introspector.py | 71 ++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 tests/flask/test_introspector.py diff --git a/tests/flask/test_introspector.py b/tests/flask/test_introspector.py new file mode 100644 index 000000000..68b166da7 --- /dev/null +++ b/tests/flask/test_introspector.py @@ -0,0 +1,71 @@ +"""Behavioral contract for the Flask route adapter.""" + +from __future__ import annotations + +import importlib +from importlib.metadata import version +from typing import Any + +from flask import Flask +from sharpit.engine.spi import AppInfo, RouteInfo + + +def _introspector(app: Flask) -> Any: + try: + module = importlib.import_module("sharpit.flask.introspector") + except ModuleNotFoundError: + return None + adapter = getattr(module, "FlaskIntrospector", None) + return adapter(app) if adapter is not None else None + + +def test_app_metadata_uses_flask_distribution_version() -> None: + app = Flask("example", static_folder=None) + app.config["DEBUG"] = True + + introspector = _introspector(app) + + assert introspector is not None + assert introspector.app_info() == AppInfo("example", "Flask", version("flask"), None) + + +def test_empty_flask_app_has_no_routes() -> None: + introspector = _introspector(Flask("empty", static_folder=None)) + + assert introspector is not None + assert introspector.routes() == [] + + +def test_routes_keep_registration_order_and_endpoint_without_calling_views() -> None: + app = Flask("routes", static_folder=None) + calls: list[str] = [] + + def first(item_id: int) -> str: + calls.append("first") + return str(item_id) + + def second() -> str: + calls.append("second") + return "second" + + app.add_url_rule("/items/", view_func=first) + app.add_url_rule("/second", view_func=second, methods=["POST"]) + + introspector = _introspector(app) + + assert introspector is not None + assert introspector.routes() == [ + RouteInfo( + ("GET", "HEAD", "OPTIONS"), + "/items/{item_id}", + f"{first.__module__}.{first.__qualname__}", + None, + None, + None, + "first", + ), + RouteInfo( + ("OPTIONS", "POST"), "/second", f"{second.__module__}.{second.__qualname__}", None, None, None, "second" + ), + ] + assert calls == [] From 23ae479befaea5f6423a39a3d2799da5a171d2fd Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 01:34:59 +0000 Subject: [PATCH 02/18] feat: add defensive Flask app introspector Signed-off-by: Flavio Oliva --- pyproject.toml | 2 +- src/sharpit/flask/__init__.py | 5 ++ src/sharpit/flask/introspector.py | 83 +++++++++++++++++++++++++++++++ tests/flask/test_introspector.py | 80 +++++++++++++++++++++++++++++ tests/flask_gate/flask_app.py | 3 +- uv.lock | 2 +- 6 files changed, 172 insertions(+), 3 deletions(-) create mode 100644 src/sharpit/flask/__init__.py create mode 100644 src/sharpit/flask/introspector.py diff --git a/pyproject.toml b/pyproject.toml index cac3ad684..b34a46007 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,7 +48,7 @@ settings = ["pydantic-settings>=2.4"] test = [ "fastapi>=0.115", "pydantic-settings>=2.4", - "flask>=3.0", + "flask>=2.3.3", "flask-sqlalchemy>=3.1", # the Flask gate tests (F2); tests only "uvicorn>=0.30", "httpx>=0.27", diff --git a/src/sharpit/flask/__init__.py b/src/sharpit/flask/__init__.py new file mode 100644 index 000000000..190e5f3bd --- /dev/null +++ b/src/sharpit/flask/__init__.py @@ -0,0 +1,5 @@ +"""Flask framework adapter.""" + +from sharpit.flask.introspector import FlaskIntrospector + +__all__ = ["FlaskIntrospector"] diff --git a/src/sharpit/flask/introspector.py b/src/sharpit/flask/introspector.py new file mode 100644 index 000000000..4c2bd0c85 --- /dev/null +++ b/src/sharpit/flask/introspector.py @@ -0,0 +1,83 @@ +"""Read Flask route metadata without calling application code.""" + +from __future__ import annotations + +import re +from collections.abc import Iterable +from importlib.metadata import PackageNotFoundError, version +from types import FunctionType +from typing import cast + +from flask import Flask +from sharpit.engine.spi import AppInfo, ProviderInfo, RouteInfo + +_PARAMETER = re.compile(r"<(?:(?:[^<>:]+):)?([^<>:]+)>") + + +def _attribute(value: object, name: str) -> object | None: + try: + return getattr(value, name, None) + except Exception: + return None + + +def _handler_name(value: object) -> str | None: + if type(value) is not FunctionType: + return None + module = _attribute(value, "__module__") + qualname = _attribute(value, "__qualname__") + if isinstance(module, str) and isinstance(qualname, str): + return f"{module}.{qualname}" + return None + + +class FlaskIntrospector: + def __init__(self, app: object) -> None: + self.app = app + + def app_info(self) -> AppInfo: + values = vars(self.app) if isinstance(self.app, Flask) else {} + title = values.get("import_name") + try: + flask_version = version("flask") + except PackageNotFoundError: + flask_version = None + return AppInfo(title if isinstance(title, str) else None, "Flask", flask_version, None) + + def routes(self) -> list[RouteInfo]: + values = vars(self.app) if isinstance(self.app, Flask) else {} + url_map = values.get("url_map") + raw_view_functions = values.get("view_functions") + if url_map is None or type(raw_view_functions) is not dict: + return [] + view_functions = cast(dict[str, object], raw_view_functions) + try: + rules = url_map.iter_rules() + result: list[RouteInfo] = [] + for rule in rules: + path = _attribute(rule, "rule") + endpoint = _attribute(rule, "endpoint") + methods = _attribute(rule, "methods") + handler = _handler_name(view_functions.get(endpoint)) if isinstance(endpoint, str) else None + if not isinstance(path, str) or handler is None: + continue + method_values = ( + cast(Iterable[object], methods) if isinstance(methods, (set, frozenset, list, tuple)) else () + ) + result.append( + RouteInfo( + tuple(sorted(method for method in method_values if isinstance(method, str))), + _PARAMETER.sub(r"{\1}", path), + handler, + None, + None, + None, + endpoint if isinstance(endpoint, str) else None, + ) + ) + return result + except Exception: + return [] + + def providers(self) -> list[ProviderInfo]: + return [] diff --git a/tests/flask/test_introspector.py b/tests/flask/test_introspector.py index 68b166da7..61bfca743 100644 --- a/tests/flask/test_introspector.py +++ b/tests/flask/test_introspector.py @@ -6,6 +6,8 @@ from importlib.metadata import version from typing import Any +from werkzeug.routing import BaseConverter + from flask import Flask from sharpit.engine.spi import AppInfo, RouteInfo @@ -69,3 +71,81 @@ def second() -> str: ), ] assert calls == [] + + +def test_converters_render_as_route_parameters_and_preserve_slashes() -> None: + app = Flask("converters", static_folder=None, subdomain_matching=True) + + def endpoint(**_values: object) -> str: + return "ok" + + class CustomConverter(BaseConverter): + regex = r"[a-z]+" + + app.url_map.converters["custom"] = CustomConverter + app.add_url_rule("/path/", view_func=endpoint, endpoint="path") + app.add_url_rule("/uuid/", view_func=endpoint, endpoint="uuid") + app.add_url_rule("/any/", view_func=endpoint, endpoint="any") + app.add_url_rule("/custom//", view_func=endpoint, endpoint="custom", strict_slashes=False) + app.add_url_rule("/tenant", view_func=endpoint, endpoint="tenant", subdomain="api") + + routes = _introspector(app).routes() + + assert [route.path for route in routes] == [ + "/path/{rest}", + "/uuid/{record}", + "/any/{color}", + "/custom/{slug}/", + "/tenant", + ] + assert routes[3].host is None + assert routes[4].host is None + + +def test_static_and_duplicate_blueprint_routes_are_kept() -> None: + app = Flask("blueprints") + first = importlib.import_module(__name__) + from flask import Blueprint + + one = Blueprint("one", first.__name__) + two = Blueprint("two", first.__name__) + + @one.get("/same") + def one_view() -> str: + return "one" + + @two.get("/same") + def two_view() -> str: + return "two" + + app.register_blueprint(one, url_prefix="/one") + app.register_blueprint(two, url_prefix="/two") + + routes = _introspector(app).routes() + endpoints = [route.name for route in routes] + + assert endpoints == ["static", "one.one_view", "two.two_view"] + assert [route.path for route in routes] == ["/static/{filename}", "/one/same", "/two/same"] + + +def test_malformed_url_map_degrades_to_no_routes() -> None: + app = Flask("broken", static_folder=None) + app.url_map = object() # type: ignore[assignment] + + assert _introspector(app).routes() == [] + + +def test_route_introspection_has_no_side_effects(no_side_effects: Any) -> None: + app = Flask("safe", static_folder=None) + + def endpoint() -> str: + return "ok" + + app.add_url_rule("/", view_func=endpoint) + introspector = _introspector(app) + + assert introspector is not None + introspector.app_info() + introspector.routes() + introspector.providers() + no_side_effects.verify() diff --git a/tests/flask_gate/flask_app.py b/tests/flask_gate/flask_app.py index dee7030c8..713d6c5bd 100644 --- a/tests/flask_gate/flask_app.py +++ b/tests/flask_gate/flask_app.py @@ -1,10 +1,11 @@ from __future__ import annotations -from flask import Flask, Response, jsonify from flask_sqlalchemy import SQLAlchemy from sqlalchemy import ForeignKey, select from sqlalchemy.orm import Mapped, mapped_column, relationship, selectinload +from flask import Flask, Response, jsonify + db = SQLAlchemy() diff --git a/uv.lock b/uv.lock index f924f7031..23243a4e4 100644 --- a/uv.lock +++ b/uv.lock @@ -1537,7 +1537,7 @@ requires-dist = [ { name = "apscheduler", marker = "extra == 'test'", specifier = ">=3.10.2,<4" }, { name = "fastapi", marker = "extra == 'fastapi'", specifier = ">=0.115" }, { name = "fastapi", marker = "extra == 'test'", specifier = ">=0.115" }, - { name = "flask", marker = "extra == 'test'", specifier = ">=3.0" }, + { name = "flask", marker = "extra == 'test'", specifier = ">=2.3.3" }, { name = "flask-sqlalchemy", marker = "extra == 'test'", specifier = ">=3.1" }, { name = "httpx", marker = "extra == 'test'", specifier = ">=0.27" }, { name = "hypothesis", marker = "extra == 'test'", specifier = ">=6.100" }, From 444bba748f617dd660602e00c60cda2bb29e374d Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 01:38:15 +0000 Subject: [PATCH 03/18] test: cover Flask app loading and autodetection Signed-off-by: Flavio Oliva --- tests/flask/test_plugin_apps.py | 87 +++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 tests/flask/test_plugin_apps.py diff --git a/tests/flask/test_plugin_apps.py b/tests/flask/test_plugin_apps.py new file mode 100644 index 000000000..fff099669 --- /dev/null +++ b/tests/flask/test_plugin_apps.py @@ -0,0 +1,87 @@ +"""Flask app selection through the already-loaded module table.""" + +from __future__ import annotations + +import builtins +import sys +from types import ModuleType +from typing import Any + + +def test_autodetect_finds_flask_without_importing_it(monkeypatch: Any) -> None: + from sharpit.pytest_plugin.apps import autodetect_apps + + flask_app_module = ModuleType("flask.app") + flask_type = type("Flask", (), {"__module__": "flask.app"}) + flask_app_module.Flask = flask_type # type: ignore[attr-defined] + host_module = ModuleType("flask_autodetect_host") + host_module.app = flask_type() # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "flask.app", flask_app_module) + monkeypatch.setitem(sys.modules, "flask_autodetect_host", host_module) + + original_import = builtins.__import__ + + def guarded_import(name: str, *args: Any, **kwargs: Any) -> Any: + assert not name.startswith("flask") + return original_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", guarded_import) + detected = dict(autodetect_apps()) + + assert detected.get("flask_autodetect_host:app") is host_module.app + + +def test_autodetect_requires_a_unique_flask_app(monkeypatch: Any) -> None: + from sharpit.pytest_plugin.apps import autodetect_apps, select_app + + flask_app_module = ModuleType("flask.app") + flask_type = type("Flask", (), {"__module__": "flask.app"}) + flask_app_module.Flask = flask_type # type: ignore[attr-defined] + host_module = ModuleType("ambiguous_flask_host") + host_module.one = flask_type() # type: ignore[attr-defined] + host_module.two = flask_type() # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "flask.app", flask_app_module) + monkeypatch.setitem(sys.modules, "ambiguous_flask_host", host_module) + + detected = autodetect_apps() + + assert len(detected) == 2 + assert select_app(detected) is None + + +def test_explicit_loader_keeps_flask_instances_and_calls_factories(monkeypatch: Any) -> None: + from flask import Flask + from sharpit.pytest_plugin.apps import load_app + + app = Flask("explicit", static_folder=None) + module = ModuleType("explicit_flask_host") + module.app = app # type: ignore[attr-defined] + module.create_app = lambda: app # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "explicit_flask_host", module) + + try: + loaded = load_app("explicit_flask_host:app")[1] + except Exception: + loaded = None + + assert loaded is app + assert load_app("explicit_flask_host:create_app")[1] is app + + +def test_model_of_exposes_flask_routes_to_the_advisor() -> None: + from flask import Flask + from sharpit.pytest_plugin.apps import model_of + + app = Flask("model", static_folder=None) + + def ready() -> str: + return "ready" + + app.add_url_rule("/ready", view_func=ready) + try: + model = model_of(app) + except Exception: + model = None + + assert model is not None + assert [route.path for route in model.routes] == ["/ready"] From e49069282a27a824decbef3af3f7d513f0ebe09a Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 01:39:51 +0000 Subject: [PATCH 04/18] test: enforce Flask adapter import boundary Signed-off-by: Flavio Oliva --- tests/engine/test_import_boundary.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/engine/test_import_boundary.py b/tests/engine/test_import_boundary.py index 97f92ee85..c89376429 100644 --- a/tests/engine/test_import_boundary.py +++ b/tests/engine/test_import_boundary.py @@ -520,6 +520,21 @@ def test_engine_never_imports_an_adapter(): assert adapter_violations() == [] +def test_flask_import_is_confined_to_its_adapter(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + source = tmp_path / "src" + adapter = source / "sharpit" / "flask" + engine = source / "sharpit" / "engine" + adapter.mkdir(parents=True) + engine.mkdir(parents=True) + (adapter / "__init__.py").write_text("import flask\n", encoding="utf-8") + (adapter / "introspector.py").write_text("import flask\n", encoding="utf-8") + (engine / "tools.py").write_text("import flask\nimport sharpit.flask.introspector\n", encoding="utf-8") + monkeypatch.setattr(sys.modules[__name__], "SRC", source) + + assert adapter_violations(engine) == ["sharpit/engine/tools.py imports sharpit.flask.introspector"] + assert gatekeeper_violations() == ["sharpit/engine/tools.py imports flask: only ['sharpit/flask'] may import flask"] + + def test_the_engine_imports_only_the_version_from_the_package(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: live = package_name_violations() monkeypatch.setitem(globals(), "SRC", tmp_path / "src") From 34d5a6df8c3b57f13740dfdb968e3993288abfd1 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 01:42:02 +0000 Subject: [PATCH 05/18] test: cover malformed Flask app reporting Signed-off-by: Flavio Oliva --- tests/flask/test_plugin_apps.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/flask/test_plugin_apps.py b/tests/flask/test_plugin_apps.py index fff099669..6882fe6fa 100644 --- a/tests/flask/test_plugin_apps.py +++ b/tests/flask/test_plugin_apps.py @@ -85,3 +85,32 @@ def ready() -> str: assert model is not None assert [route.path for route in model.routes] == ["/ready"] + + +def test_malformed_autodetected_flask_map_is_unknown(pytester: Any) -> None: + import json + + pytester.makepyfile( + appmod=""" + from flask import Flask + app = Flask('broken', static_folder=None) + app.url_map = object() + """ + ) + pytester.makepyfile("import appmod\ndef test_empty(): pass") + + pytester.runpytest( + "--sharpit", + "--sharpit-require-app", + "--sharpit-allow-unknown", + "--sharpit-report=report.json", + "-q", + ) + + report = json.loads((pytester.path / "report.json").read_text()) + run = next(item for item in report["advisors"] if item["advisor"] == "rest-api") + + assert run["status"] == "UNKNOWN" + assert ( + run["reason"] == "app appmod:app has no application routes; rest-api skipped (pass --sharpit-app module:attr)" + ) From f96bf04c8798b6247806a444fcdfdcef0c121a56 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 01:42:43 +0000 Subject: [PATCH 06/18] feat: enforce Flask adapter import boundary Signed-off-by: Flavio Oliva --- AGENTS.md | 9 ++++++--- tests/engine/test_import_boundary.py | 13 +++++++------ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2bcc6deb2..64ea24336 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,7 @@ src/sharpit/settings.py SharpitSettings, load_settings (SHARPIT_* env + k src/sharpit/engine/ framework-free core: activation, guard, masking, panels, collectors, paging src/sharpit/engine/sqla/ the SQLAlchemy gatekeeper: listeners, events, orm, inspect, readonly (sharpit's own reads) src/sharpit/fastapi/ the FastAPI/Starlette adapter: routes, introspection, dev-server signals +src/sharpit/flask/ the Flask adapter: route introspection over the public URL map src/sharpit/pytest_plugin/ the pytest adapter: optional plugin entry point and test-session hooks src/sharpit/cli/ the command-line client adapter: talks to a running app over HTTP; standard library only src/sharpit/ui/static/ the built UI (committed; CI checks it matches ui/ when ui/ exists) @@ -107,7 +108,8 @@ these on every run (a planted violation proves each rule still bites); a failing to loosen. Change a rule only in that test and here, in the same PR, with the reason in the PR body. 1. **Framework-free engine.** `engine/` never imports `fastapi` or `starlette` (a `TYPE_CHECKING` block is allowed). -2. **Dependencies point inward.** `engine/` never imports `sharpit.fastapi`, `sharpit.pytest_plugin` or `sharpit.ui`, +2. **Dependencies point inward.** `engine/` never imports `sharpit.fastapi`, `sharpit.flask`, `sharpit.pytest_plugin` + or `sharpit.ui`, not even for a type. No module under `src/sharpit/` outside `sharpit/cli/` imports `sharpit.cli`; modules under `sharpit/cli/` import only the standard-library modules named in `CLI_STDLIB` in `tests/engine/test_import_boundary.py`, `sharpit.cli`, and `__version__` from `sharpit`, not even for a type. When @@ -117,8 +119,9 @@ to loosen. Change a rule only in that test and here, in the same PR, with the re 3. **One module per collector.** A collector under `engine/collectors/` never imports another. Shared code moves to the engine (`context`, `paging`, `spi`, `singleflight`, ...). Inside `engine/collectors/insights/` the rule holds per kind: a module under `kinds/` never imports another kind; shared code goes in the insights package. -4. **Gatekeepers.** One named file (or package) per optional or network library: SQLAlchemy only in the - `engine/sqla/` package, `sqlite3` only in `engine/sources/sqlite.py`, `pydantic_settings` and `dotenv` only in +4. **Gatekeepers.** One named file (or package) per optional or network library: Flask only in `sharpit/flask/`, + SQLAlchemy only in the `engine/sqla/` package, `sqlite3` only in `engine/sources/sqlite.py`, `pydantic_settings` + and `dotenv` only in `engine/collectors/config/settings_source.py`, OpenTelemetry only in `engine/otel.py`, `prometheus_client` only in `engine/collectors/metrics/prometheus.py`, `urllib.request` only in `engine/collectors/vulns/osv.py`, `engine/collectors/vulns/epss.py`, `engine/collectors/github/client.py` and `sharpit/cli/client.py`; diff --git a/tests/engine/test_import_boundary.py b/tests/engine/test_import_boundary.py index c89376429..e3931e4c2 100644 --- a/tests/engine/test_import_boundary.py +++ b/tests/engine/test_import_boundary.py @@ -1,14 +1,14 @@ """Module boundaries, checked on every run (Spring Modulith style). AGENTS.md "Architecture rules" lists the same rules. 1. The engine is framework-free: no FastAPI or Starlette import (a ``TYPE_CHECKING`` block is allowed). -2. Dependencies point inward: the engine never imports the adapters (``sharpit.fastapi``, ``sharpit.pytest_plugin`` - or ``sharpit.ui``); no module outside ``sharpit/cli/`` imports ``sharpit.cli``; modules under ``sharpit/cli/`` - import only the standard library and ``sharpit.cli``, not even for a type. +2. Dependencies point inward: the engine never imports the adapters (``sharpit.fastapi``, ``sharpit.flask``, + ``sharpit.pytest_plugin`` or ``sharpit.ui``); no module outside ``sharpit/cli/`` imports ``sharpit.cli``; modules + under ``sharpit/cli/`` import only the standard library and ``sharpit.cli``, not even for a type. 3. Each collector under ``engine/collectors/`` is a module of its own and never imports another collector. Shared code goes in the engine (``context``, ``paging``, ``spi``, ...), not in a sibling collector. Inside the Runtime Insights collector the same holds per kind: a module under ``insights/kinds/`` never imports another kind. -4. Gatekeepers: an optional dependency or a network client is imported only by its named gatekeeper file or package, - so the rest of the package works without it (CI's ``no-sqlalchemy`` job). ``urllib.request`` is limited to +4. Gatekeepers: Flask, an optional dependency or a network client is imported only by its named gatekeeper file or + package, so the rest of the package works without it (CI's ``no-sqlalchemy`` job). ``urllib.request`` is limited to ``engine/collectors/vulns/osv.py``, ``engine/collectors/vulns/epss.py``, ``engine/collectors/github/client.py`` and ``cli/client.py``; ``http.client`` is limited to the same files except EPSS. The CLI imports only the named standard-library modules in ``CLI_STDLIB`` below. @@ -34,12 +34,13 @@ ENGINE = SRC / "sharpit" / "engine" COLLECTORS = ENGINE / "collectors" FRAMEWORKS = ("fastapi", "starlette") -ADAPTERS = ("sharpit.fastapi", "sharpit.pytest_plugin", "sharpit.ui") +ADAPTERS = ("sharpit.fastapi", "sharpit.flask", "sharpit.pytest_plugin", "sharpit.ui") GATEKEEPERS: dict[str, set[str]] = { "sqlalchemy": {"sharpit/engine/sqla"}, # a package: every module under engine/sqla/ (0.5.0 spec §4.1) "sqlite3": {"sharpit/engine/sources/sqlite.py"}, "alembic": set(), "pydantic_settings": {"sharpit/engine/collectors/config/settings_source.py"}, + "flask": {"sharpit/flask"}, "dotenv": {"sharpit/engine/collectors/config/settings_source.py"}, "opentelemetry": {"sharpit/engine/otel.py"}, "prometheus_client": {"sharpit/engine/collectors/metrics/prometheus.py"}, From 922b1c6bde399a6e6ebecd8aa6fde9fcdbd92d76 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 01:44:13 +0000 Subject: [PATCH 07/18] docs: record Flask route model limits Signed-off-by: Flavio Oliva --- docs/README.md | 1 + docs/reference/FLASK-ROUTE-MODEL.md | 15 ++++++++++ .../2026-11-21-0.8.0-f1-flask-route-model.md | 29 +++++++++++++++++++ website/docs/how-it-works.md | 6 ++-- 4 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 docs/reference/FLASK-ROUTE-MODEL.md create mode 100644 docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md diff --git a/docs/README.md b/docs/README.md index dea4c6218..c3b365eac 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ | [development/overhead-budgets.md](development/overhead-budgets.md) | How the overhead budget tests measure and how to read a failure | | [reference/BOOTUI-CONTRACT-MVP.md](reference/BOOTUI-CONTRACT-MVP.md) | The BootUI HTTP contract the MVP must match: DTOs, error strings, activation reasons | | [reference/BOOTUI-PYTHON-MAPPING.md](reference/BOOTUI-PYTHON-MAPPING.md) | How BootUI's Spring concepts map to Python/FastAPI | +| [reference/FLASK-ROUTE-MODEL.md](reference/FLASK-ROUTE-MODEL.md) | Flask route introspection scope and route facts unavailable in `RouteInfo` | | [superpowers/specs/2026-10-30-sharpit-mvp-design.md](superpowers/specs/2026-10-30-sharpit-mvp-design.md) | MVP design spec; §14 deviation log, §15 coordinator's calls for the owner | | [superpowers/specs/council/](superpowers/specs/council/) | Spec reviews by Claude, Codex and Gemini, and the round-1 synthesis | | [superpowers/plans/2026-10-30-sharpit-mvp.md](superpowers/plans/2026-10-30-sharpit-mvp.md) | MVP implementation plan: Global Constraints, Review Focus, tasks | diff --git a/docs/reference/FLASK-ROUTE-MODEL.md b/docs/reference/FLASK-ROUTE-MODEL.md new file mode 100644 index 000000000..f9ca63efe --- /dev/null +++ b/docs/reference/FLASK-ROUTE-MODEL.md @@ -0,0 +1,15 @@ +# Flask route introspection + +sharpit's pytest adapter can inspect Flask routes from Flask 2.3.3 onward. Flask stays in the `test` extra; it is not a +runtime dependency. Route discovery uses registered `url_map` rules and does not execute view functions. Blueprint +rules appear as Flask registers them, including static routes and distinct registrations of the same view. + +Werkzeug paths such as `/items/` appear as `/items/{item_id}`. The adapter reports effective rule methods, +including automatically added `HEAD` and `OPTIONS`, and preserves the rule's slash spelling. + +The route model has no fields for `strict_slashes`, subdomain or host constraints, converter semantics, blueprint +provenance, declared-versus-automatic methods, response metadata, or produced and consumed media types. These facts are +not inferred; host is `null`, and unavailable response and media metadata are `null`. A malformed or unreadable URL map +produces no routes, allowing the pytest advisor to report `UNKNOWN` when route presence is required. + +Flask route introspection does not mount the sharpit console in Flask applications. diff --git a/docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md b/docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md new file mode 100644 index 000000000..9d5e7cc7d --- /dev/null +++ b/docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md @@ -0,0 +1,29 @@ +# Flask route model + +The F1 adapter exposes Flask route metadata to sharpit's pytest advisor. Flask remains a test-only dependency, with +2.3.3 as the supported floor and Flask 3.x as the current test target. The adapter reads the public `url_map` and +registered rules; it does not call views or inspect blueprint internals. + +## Mapping + +| Flask source | sharpit representation | +|---|---| +| `app.import_name` | `AppInfo.title` | +| Flask distribution metadata | `AppInfo.framework_version`; `docs_url=None` | +| Each `app.url_map.iter_rules()` rule | One `RouteInfo`, in registration order | +| `Rule.methods` | Sorted effective methods, including Werkzeug-added `HEAD` and `OPTIONS` | +| `Rule.rule` | Path with `` and `` rendered as `{name}`; slash spelling is preserved | +| Registered view callable | `module:qualname` handler identity, read without calling it | +| `Rule.endpoint` | Route name | +| No dependency-provider graph | `providers() == []` | + +`RouteInfo` cannot carry `strict_slashes`, subdomain or host constraints, converter validation semantics, blueprint +provenance, explicit-versus-automatic methods, response metadata, or media types. The adapter preserves the written +path, reports `host=None`, and reports unavailable response and media metadata as `None`. It does not infer semantic +equivalence between routes with different slash or host behavior. + +An unreadable URL map or malformed rule degrades to an empty route list. The pytest adapter reports the app as +`UNKNOWN` when `--sharpit-require-app` is active and no routes can be confirmed. Flask discovery checks already-loaded +`sys.modules` entries; it does not import Flask. The Flask adapter is loaded only after a Flask app is selected. + +BootUI 2.5.0 has no Flask route model, so F1 introduces no BootUI parity deviation or shared contract key. diff --git a/website/docs/how-it-works.md b/website/docs/how-it-works.md index c7b540aef..ba3fe220e 100644 --- a/website/docs/how-it-works.md +++ b/website/docs/how-it-works.md @@ -36,9 +36,9 @@ There are two layers: - **The engine** (`src/sharpit/engine/`) knows nothing about FastAPI or Starlette. It holds the rules: activation, the guard, masking, collectors, live streams, and the MCP server. Each collector takes plain data and returns BootUI's JSON shapes. -- **The FastAPI adapter** (`src/sharpit/fastapi/`) is the only code that touches the web framework. It reads your - app's routes, dependencies and lifespan (`introspector.py`), mounts the sub-app, attaches runtime capture hooks, and turns - HTTP requests into engine calls. A Django or Flask adapter would replace only this layer. +- **The FastAPI adapter** (`src/sharpit/fastapi/`) mounts the console, reads app routes, dependencies and lifespan + (`introspector.py`), attaches runtime capture hooks, and turns HTTP requests into engine calls. The Flask adapter + (`src/sharpit/flask/`) reads route metadata for the pytest advisor; it does not mount the console. ## When it turns on From 29272cbaa886f4e0ea3697f40a7eada57585ad8d Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:04:57 +0000 Subject: [PATCH 08/18] feat: select Flask introspector in pytest plugin Signed-off-by: Flavio Oliva --- src/sharpit/flask/introspector.py | 2 +- src/sharpit/pytest_plugin/apps.py | 31 ++++++++++++++----- ...ugin_apps.py => test_flask_plugin_apps.py} | 0 tests/flask/test_introspector.py | 18 +++-------- 4 files changed, 30 insertions(+), 21 deletions(-) rename tests/flask/{test_plugin_apps.py => test_flask_plugin_apps.py} (100%) diff --git a/src/sharpit/flask/introspector.py b/src/sharpit/flask/introspector.py index 4c2bd0c85..792ba800a 100644 --- a/src/sharpit/flask/introspector.py +++ b/src/sharpit/flask/introspector.py @@ -27,7 +27,7 @@ def _handler_name(value: object) -> str | None: module = _attribute(value, "__module__") qualname = _attribute(value, "__qualname__") if isinstance(module, str) and isinstance(qualname, str): - return f"{module}.{qualname}" + return f"{module}:{qualname}" return None diff --git a/src/sharpit/pytest_plugin/apps.py b/src/sharpit/pytest_plugin/apps.py index a112423d7..d3d521310 100644 --- a/src/sharpit/pytest_plugin/apps.py +++ b/src/sharpit/pytest_plugin/apps.py @@ -17,7 +17,7 @@ from sharpit.engine.advisors.registry import ADVISORS from sharpit.engine.advisors.rules import Severity from sharpit.engine.collectors.restapi.rules import application_routes -from sharpit.engine.spi import ApiModel +from sharpit.engine.spi import ApiModel, ApiRouteInfo from sharpit.engine.testsession.outcome import AUTODETECT, NO_APPLICATION from sharpit.fastapi.introspector import FastApiIntrospector @@ -109,8 +109,12 @@ def _mounted(app: object, mounts: frozenset[type]) -> list[int]: def autodetect_apps(test_files: Sequence[str] = TEST_FILES) -> tuple[tuple[str, object], ...]: - """FastAPI/Starlette instances in loaded project-module globals; imports nothing, runs no module hook.""" - apps = _classes("starlette.applications", "Starlette") | _classes("fastapi.applications", "FastAPI") + """Flask/FastAPI/Starlette instances in loaded project-module globals; imports nothing, runs no module hook.""" + apps = ( + _classes("starlette.applications", "Starlette") + | _classes("fastapi.applications", "FastAPI") + | _classes("flask.app", "Flask") + ) if not apps: return () paths = sysconfig.get_paths() @@ -190,19 +194,32 @@ def load_app(spec: str) -> tuple[str, object]: if not separator: raise ValueError("--sharpit-app must be MOD:ATTR") app = getattr(importlib.import_module(module_name), attr) - return spec, app() if callable(app) and not hasattr(app, "router") else app + return spec, app() if callable(app) and not hasattr(app, "router") and not _is_flask_app(app) else app -def model_of(app: object) -> ApiModel: +def _is_flask_app(app: object) -> bool: + return not _classes("flask.app", "Flask").isdisjoint(type(app).__mro__) + + +def _app_model(app: object) -> ApiModel: + if _is_flask_app(app): + from sharpit.flask import FlaskIntrospector + + routes = FlaskIntrospector(app).routes() + return ApiModel(tuple(ApiRouteInfo(route.methods, route.path, route.handler) for route in routes), (), ()) return FastApiIntrospector(app).api_model() +def model_of(app: object) -> ApiModel: + return _app_model(app) + + def _configured_models( state: Any, load_app: Callable[[str], tuple[str, object]] | None ) -> list[tuple[str, ApiModel]] | None: try: name, app = (load_app or _load_app)(state.options.app) - return [(name, FastApiIntrospector(app).api_model())] + return [(name, _app_model(app))] except Exception as exc: # noqa: BLE001 state.sink.facts.advisor_runs.append( AdvisorRun( @@ -225,7 +242,7 @@ def _discovered_models(state: Any) -> list[tuple[str, ApiModel]] | None: if (run := no_app_run(state.autodetected, state.options.require_app)) is not None: state.sink.facts.advisor_runs.append(run) return None - model = FastApiIntrospector(chosen[1]).api_model() + model = _app_model(chosen[1]) if not application_routes(model.routes): state.sink.facts.advisor_runs.append(bare_app_run(chosen[0], state.options.require_app)) return None diff --git a/tests/flask/test_plugin_apps.py b/tests/flask/test_flask_plugin_apps.py similarity index 100% rename from tests/flask/test_plugin_apps.py rename to tests/flask/test_flask_plugin_apps.py diff --git a/tests/flask/test_introspector.py b/tests/flask/test_introspector.py index 61bfca743..412510e29 100644 --- a/tests/flask/test_introspector.py +++ b/tests/flask/test_introspector.py @@ -10,15 +10,11 @@ from flask import Flask from sharpit.engine.spi import AppInfo, RouteInfo +from sharpit.flask import FlaskIntrospector -def _introspector(app: Flask) -> Any: - try: - module = importlib.import_module("sharpit.flask.introspector") - except ModuleNotFoundError: - return None - adapter = getattr(module, "FlaskIntrospector", None) - return adapter(app) if adapter is not None else None +def _introspector(app: Flask) -> FlaskIntrospector: + return FlaskIntrospector(app) def test_app_metadata_uses_flask_distribution_version() -> None: @@ -27,14 +23,12 @@ def test_app_metadata_uses_flask_distribution_version() -> None: introspector = _introspector(app) - assert introspector is not None assert introspector.app_info() == AppInfo("example", "Flask", version("flask"), None) def test_empty_flask_app_has_no_routes() -> None: introspector = _introspector(Flask("empty", static_folder=None)) - assert introspector is not None assert introspector.routes() == [] @@ -55,19 +49,18 @@ def second() -> str: introspector = _introspector(app) - assert introspector is not None assert introspector.routes() == [ RouteInfo( ("GET", "HEAD", "OPTIONS"), "/items/{item_id}", - f"{first.__module__}.{first.__qualname__}", + f"{first.__module__}:{first.__qualname__}", None, None, None, "first", ), RouteInfo( - ("OPTIONS", "POST"), "/second", f"{second.__module__}.{second.__qualname__}", None, None, None, "second" + ("OPTIONS", "POST"), "/second", f"{second.__module__}:{second.__qualname__}", None, None, None, "second" ), ] assert calls == [] @@ -144,7 +137,6 @@ def endpoint() -> str: app.add_url_rule("/", view_func=endpoint) introspector = _introspector(app) - assert introspector is not None introspector.app_info() introspector.routes() introspector.providers() From 3c9c212b421019bf0d1e0f88982d8911bdac94de Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:20:19 +0000 Subject: [PATCH 09/18] test: cover static Flask introspection Signed-off-by: Flavio Oliva --- tests/flask/test_introspector.py | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/flask/test_introspector.py b/tests/flask/test_introspector.py index 412510e29..2e695bc14 100644 --- a/tests/flask/test_introspector.py +++ b/tests/flask/test_introspector.py @@ -141,3 +141,43 @@ def endpoint() -> str: introspector.routes() introspector.providers() no_side_effects.verify() + + +def test_routes_and_app_metadata_do_not_read_dynamic_flask_attributes() -> None: + class RecordingFlask(Flask): + accesses: list[str] = [] + + def __getattribute__(self, name: str) -> object: + if name != "accesses": + object.__getattribute__(self, "accesses").append(name) + return object.__getattribute__(self, name) + + app = RecordingFlask("safe-static", static_folder=None) + RecordingFlask.accesses.clear() + + introspector = _introspector(app) + introspector.routes() + introspector.app_info() + + assert RecordingFlask.accesses == [] + + +def test_routes_do_not_evaluate_rule_properties() -> None: + accesses: list[str] = [] + + class Rule: + @property + def rule(self) -> str: + accesses.append("rule") + return "/unsafe" + + endpoint = "unsafe" + methods = {"GET"} + + app = Flask("unsafe-rule", static_folder=None) + app.url_map = type("Map", (), {"iter_rules": lambda _self: [Rule()]})() # type: ignore[assignment] + app.view_functions["unsafe"] = lambda: "unsafe" + + _introspector(app).routes() + + assert accesses == [] From 5953d2466ba13a786a751329e6c7fe76b17ff5aa Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:21:49 +0000 Subject: [PATCH 10/18] fix: read Flask metadata without host code Signed-off-by: Flavio Oliva --- src/sharpit/flask/introspector.py | 44 ++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/src/sharpit/flask/introspector.py b/src/sharpit/flask/introspector.py index 792ba800a..913e16420 100644 --- a/src/sharpit/flask/introspector.py +++ b/src/sharpit/flask/introspector.py @@ -2,6 +2,7 @@ from __future__ import annotations +import inspect import re from collections.abc import Iterable from importlib.metadata import PackageNotFoundError, version @@ -9,23 +10,40 @@ from typing import cast from flask import Flask +from werkzeug.routing import Map from sharpit.engine.spi import AppInfo, ProviderInfo, RouteInfo _PARAMETER = re.compile(r"<(?:(?:[^<>:]+):)?([^<>:]+)>") +_MISSING = object() def _attribute(value: object, name: str) -> object | None: - try: - return getattr(value, name, None) - except Exception: + result = inspect.getattr_static(value, name, _MISSING) + if result is _MISSING or inspect.isdatadescriptor(result): return None + return result + + +def _app_values(app: object) -> dict[str, object]: + if not issubclass(type(app), Flask): + return {} + try: + values = object.__getattribute__(app, "__dict__") + except Exception: # noqa: BLE001 - a slotted or unusual Flask subclass has no readable instance data + return {} + return cast(dict[str, object], values) if isinstance(values, dict) else {} def _handler_name(value: object) -> str | None: - if type(value) is not FunctionType: + if not callable(value): return None - module = _attribute(value, "__module__") - qualname = _attribute(value, "__qualname__") + if type(value) is FunctionType: + module = object.__getattribute__(value, "__module__") + qualname = object.__getattribute__(value, "__qualname__") + return f"{module}:{qualname}" if isinstance(module, str) and isinstance(qualname, str) else None + target = type(value) + module = _attribute(target, "__module__") + qualname = _attribute(target, "__qualname__") if isinstance(module, str) and isinstance(qualname, str): return f"{module}:{qualname}" return None @@ -36,7 +54,7 @@ def __init__(self, app: object) -> None: self.app = app def app_info(self) -> AppInfo: - values = vars(self.app) if isinstance(self.app, Flask) else {} + values = _app_values(self.app) title = values.get("import_name") try: flask_version = version("flask") @@ -44,15 +62,15 @@ def app_info(self) -> AppInfo: flask_version = None return AppInfo(title if isinstance(title, str) else None, "Flask", flask_version, None) - def routes(self) -> list[RouteInfo]: - values = vars(self.app) if isinstance(self.app, Flask) else {} + def routes(self) -> list[RouteInfo] | None: + values = _app_values(self.app) url_map = values.get("url_map") raw_view_functions = values.get("view_functions") - if url_map is None or type(raw_view_functions) is not dict: - return [] + if type(url_map) is not Map or type(raw_view_functions) is not dict: + return None view_functions = cast(dict[str, object], raw_view_functions) try: - rules = url_map.iter_rules() + rules = Map.iter_rules(url_map) result: list[RouteInfo] = [] for rule in rules: path = _attribute(rule, "rule") @@ -77,7 +95,7 @@ def routes(self) -> list[RouteInfo]: ) return result except Exception: - return [] + return None def providers(self) -> list[ProviderInfo]: return [] From 43141a6a4f5f4e921eb9cceda5bdb270e0272e81 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:23:17 +0000 Subject: [PATCH 11/18] test: cover unreadable Flask route maps Signed-off-by: Flavio Oliva --- tests/flask/test_introspector.py | 4 ++-- tests/pytest_plugin/test_plugin_apps.py | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/tests/flask/test_introspector.py b/tests/flask/test_introspector.py index 2e695bc14..15303c0b8 100644 --- a/tests/flask/test_introspector.py +++ b/tests/flask/test_introspector.py @@ -121,11 +121,11 @@ def two_view() -> str: assert [route.path for route in routes] == ["/static/{filename}", "/one/same", "/two/same"] -def test_malformed_url_map_degrades_to_no_routes() -> None: +def test_malformed_url_map_is_unreadable() -> None: app = Flask("broken", static_folder=None) app.url_map = object() # type: ignore[assignment] - assert _introspector(app).routes() == [] + assert _introspector(app).routes() is None def test_route_introspection_has_no_side_effects(no_side_effects: Any) -> None: diff --git a/tests/pytest_plugin/test_plugin_apps.py b/tests/pytest_plugin/test_plugin_apps.py index 4385fc9eb..d3a57e39e 100644 --- a/tests/pytest_plugin/test_plugin_apps.py +++ b/tests/pytest_plugin/test_plugin_apps.py @@ -96,6 +96,25 @@ def owners(): return [] assert "detected from" not in result.stdout.str() +def test_explicit_flask_app_with_unreadable_map_is_unknown(pytester: pytest.Pytester) -> None: + pytester.makepyfile( + app=""" + from flask import Flask + app = Flask('broken', static_folder=None) + app.url_map = object() + """ + ) + pytester.makepyfile("def test_empty(): pass") + + pytester.runpytest( + "--sharpit", "--sharpit-app=app:app", "--sharpit-allow-unknown", "--sharpit-report=report.json", "-q" + ) + + run = _rest_run(pytester) + assert run["status"] == "UNKNOWN" + assert run["reason"] == "application routes cannot be inspected (Flask URL map)" + + def test_single_process_assesses_routes_added_after_the_last_test(pytester: pytest.Pytester) -> None: pytester.makeconftest( """ From 43318fe977e536bdd6a40b6973ed20a778e33b61 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:23:41 +0000 Subject: [PATCH 12/18] test: cover callable Flask views Signed-off-by: Flavio Oliva --- tests/flask/test_introspector.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/flask/test_introspector.py b/tests/flask/test_introspector.py index 15303c0b8..c865ae5ec 100644 --- a/tests/flask/test_introspector.py +++ b/tests/flask/test_introspector.py @@ -181,3 +181,20 @@ def rule(self) -> str: _introspector(app).routes() assert accesses == [] + + +def test_callable_view_with_explicit_endpoint_is_kept_without_calling_it() -> None: + class CallableView: + calls = 0 + + def __call__(self) -> str: + CallableView.calls += 1 + return "called" + + app = Flask("callable-view", static_folder=None) + app.add_url_rule("/callable", endpoint="callable", view_func=CallableView()) + + routes = _introspector(app).routes() + + assert [route.path for route in routes or []] == ["/callable"] + assert CallableView.calls == 0 From 85946d91b380b4a10f42b9a8019e777f9e888f4e Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:25:25 +0000 Subject: [PATCH 13/18] fix: keep callable Flask views in route model Signed-off-by: Flavio Oliva --- src/sharpit/flask/introspector.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/sharpit/flask/introspector.py b/src/sharpit/flask/introspector.py index 913e16420..fa7013688 100644 --- a/src/sharpit/flask/introspector.py +++ b/src/sharpit/flask/introspector.py @@ -41,9 +41,9 @@ def _handler_name(value: object) -> str | None: module = object.__getattribute__(value, "__module__") qualname = object.__getattribute__(value, "__qualname__") return f"{module}:{qualname}" if isinstance(module, str) and isinstance(qualname, str) else None - target = type(value) - module = _attribute(target, "__module__") - qualname = _attribute(target, "__qualname__") + attributes = type.__getattribute__(type(value), "__dict__") + module = attributes.get("__module__") + qualname = attributes.get("__qualname__") if isinstance(module, str) and isinstance(qualname, str): return f"{module}:{qualname}" return None From f8a0128c3d6dc3cc2647093d08888ddbde961edb Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:25:54 +0000 Subject: [PATCH 14/18] fix: derive callable view names from their class Signed-off-by: Flavio Oliva --- src/sharpit/flask/introspector.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/sharpit/flask/introspector.py b/src/sharpit/flask/introspector.py index fa7013688..749c3bcda 100644 --- a/src/sharpit/flask/introspector.py +++ b/src/sharpit/flask/introspector.py @@ -41,9 +41,9 @@ def _handler_name(value: object) -> str | None: module = object.__getattribute__(value, "__module__") qualname = object.__getattribute__(value, "__qualname__") return f"{module}:{qualname}" if isinstance(module, str) and isinstance(qualname, str) else None - attributes = type.__getattribute__(type(value), "__dict__") - module = attributes.get("__module__") - qualname = attributes.get("__qualname__") + target = type(value) + module = type.__getattribute__(target, "__module__") + qualname = type.__getattribute__(target, "__qualname__") if isinstance(module, str) and isinstance(qualname, str): return f"{module}:{qualname}" return None From bc9de648d760733165333a241d0b88a67c995015 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:29:00 +0000 Subject: [PATCH 15/18] fix: report unreadable Flask maps as unknown Signed-off-by: Flavio Oliva --- docs/reference/FLASK-ROUTE-MODEL.md | 8 +++- docs/reference/matrix-updates/0.8.0-f1.tsv | 1 + .../2026-11-21-0.8.0-f1-flask-route-model.md | 10 +++-- src/sharpit/pytest_plugin/apps.py | 44 ++++++++++++++++--- tests/flask/test_flask_plugin_apps.py | 4 +- 5 files changed, 53 insertions(+), 14 deletions(-) create mode 100644 docs/reference/matrix-updates/0.8.0-f1.tsv diff --git a/docs/reference/FLASK-ROUTE-MODEL.md b/docs/reference/FLASK-ROUTE-MODEL.md index f9ca63efe..b638802eb 100644 --- a/docs/reference/FLASK-ROUTE-MODEL.md +++ b/docs/reference/FLASK-ROUTE-MODEL.md @@ -9,7 +9,11 @@ including automatically added `HEAD` and `OPTIONS`, and preserves the rule's sla The route model has no fields for `strict_slashes`, subdomain or host constraints, converter semantics, blueprint provenance, declared-versus-automatic methods, response metadata, or produced and consumed media types. These facts are -not inferred; host is `null`, and unavailable response and media metadata are `null`. A malformed or unreadable URL map -produces no routes, allowing the pytest advisor to report `UNKNOWN` when route presence is required. +not inferred; host is `null`, and unavailable response and media metadata are `null`. An unreadable URL map is +distinct from a confirmed empty map: route inspection returns `None` when the map cannot be read, and an explicitly +selected app is reported as `UNKNOWN`. Unreadable rule fields are skipped without evaluating descriptors. Callable +views are represented by their class identity and are never called. Flask route introspection does not mount the sharpit console in Flask applications. + +BootUI 2.5.0 has no Flask route model, so these framework-specific behaviors have no BootUI parity counterpart. diff --git a/docs/reference/matrix-updates/0.8.0-f1.tsv b/docs/reference/matrix-updates/0.8.0-f1.tsv new file mode 100644 index 000000000..e177081ec --- /dev/null +++ b/docs/reference/matrix-updates/0.8.0-f1.tsv @@ -0,0 +1 @@ +adapter:flask-route-metadata adapted BootUI 2.5.0 has no Flask route model; Flask route metadata is read statically, unreadable maps report UNKNOWN, and callable views are identified by class without invocation; docs/reference/FLASK-ROUTE-MODEL.md \ No newline at end of file diff --git a/docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md b/docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md index 9d5e7cc7d..cdc4aa2be 100644 --- a/docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md +++ b/docs/superpowers/plans/2026-11-21-0.8.0-f1-flask-route-model.md @@ -22,8 +22,10 @@ provenance, explicit-versus-automatic methods, response metadata, or media types path, reports `host=None`, and reports unavailable response and media metadata as `None`. It does not infer semantic equivalence between routes with different slash or host behavior. -An unreadable URL map or malformed rule degrades to an empty route list. The pytest adapter reports the app as -`UNKNOWN` when `--sharpit-require-app` is active and no routes can be confirmed. Flask discovery checks already-loaded -`sys.modules` entries; it does not import Flask. The Flask adapter is loaded only after a Flask app is selected. +An unreadable URL map is distinct from a confirmed empty map: route inspection returns `None` when the map cannot be +read, and an explicitly selected app is reported as `UNKNOWN`. Unreadable rule fields are skipped without evaluating +descriptors. Flask discovery checks already-loaded `sys.modules` entries; it does not import Flask. The Flask adapter +is loaded only after a Flask app is selected. -BootUI 2.5.0 has no Flask route model, so F1 introduces no BootUI parity deviation or shared contract key. +BootUI 2.5.0 has no Flask route model. Flask-specific route metadata and safe static reads have no BootUI parity +counterpart or shared contract key. diff --git a/src/sharpit/pytest_plugin/apps.py b/src/sharpit/pytest_plugin/apps.py index d3d521310..e62d36bc2 100644 --- a/src/sharpit/pytest_plugin/apps.py +++ b/src/sharpit/pytest_plugin/apps.py @@ -3,6 +3,7 @@ from __future__ import annotations import importlib +import inspect import os import sys import sysconfig @@ -43,6 +44,7 @@ _HINT = "pass --sharpit-app module:attr" +_MISSING = object() _NOT_FOUND = ( "no application found among the modules the tests imported " "(conftest, test modules and installed packages are not searched)" @@ -114,6 +116,7 @@ def autodetect_apps(test_files: Sequence[str] = TEST_FILES) -> tuple[tuple[str, _classes("starlette.applications", "Starlette") | _classes("fastapi.applications", "FastAPI") | _classes("flask.app", "Flask") + | _classes("flask.sansio.app", "Flask") ) if not apps: return () @@ -194,24 +197,30 @@ def load_app(spec: str) -> tuple[str, object]: if not separator: raise ValueError("--sharpit-app must be MOD:ATTR") app = getattr(importlib.import_module(module_name), attr) - return spec, app() if callable(app) and not hasattr(app, "router") and not _is_flask_app(app) else app + has_router = inspect.getattr_static(app, "router", _MISSING) is not _MISSING + return spec, app() if callable(app) and not has_router and not _is_flask_app(app) else app def _is_flask_app(app: object) -> bool: - return not _classes("flask.app", "Flask").isdisjoint(type(app).__mro__) + return not ( + _classes("flask.app", "Flask") | _classes("flask.sansio.app", "Flask") + ).isdisjoint(type(app).__mro__) -def _app_model(app: object) -> ApiModel: +def _app_model(app: object) -> ApiModel | None: if _is_flask_app(app): from sharpit.flask import FlaskIntrospector routes = FlaskIntrospector(app).routes() + if routes is None: + return None return ApiModel(tuple(ApiRouteInfo(route.methods, route.path, route.handler) for route in routes), (), ()) return FastApiIntrospector(app).api_model() def model_of(app: object) -> ApiModel: - return _app_model(app) + model = _app_model(app) + return model if model is not None else ApiModel((), (), ()) def _configured_models( @@ -219,7 +228,20 @@ def _configured_models( ) -> list[tuple[str, ApiModel]] | None: try: name, app = (load_app or _load_app)(state.options.app) - return [(name, _app_model(app))] + model = _app_model(app) + if model is None: + state.sink.facts.advisor_runs.append( + AdvisorRun( + "rest-api", + "UNKNOWN", + (), + {}, + "application routes cannot be inspected (Flask URL map)", + name, + ) + ) + return None + return [(name, model)] except Exception as exc: # noqa: BLE001 state.sink.facts.advisor_runs.append( AdvisorRun( @@ -243,6 +265,18 @@ def _discovered_models(state: Any) -> list[tuple[str, ApiModel]] | None: state.sink.facts.advisor_runs.append(run) return None model = _app_model(chosen[1]) + if model is None: + state.sink.facts.advisor_runs.append( + AdvisorRun( + "rest-api", + "UNKNOWN", + (), + {}, + "application routes cannot be inspected (Flask URL map)", + chosen[0], + ) + ) + return None if not application_routes(model.routes): state.sink.facts.advisor_runs.append(bare_app_run(chosen[0], state.options.require_app)) return None diff --git a/tests/flask/test_flask_plugin_apps.py b/tests/flask/test_flask_plugin_apps.py index 6882fe6fa..4309799e3 100644 --- a/tests/flask/test_flask_plugin_apps.py +++ b/tests/flask/test_flask_plugin_apps.py @@ -111,6 +111,4 @@ def test_malformed_autodetected_flask_map_is_unknown(pytester: Any) -> None: run = next(item for item in report["advisors"] if item["advisor"] == "rest-api") assert run["status"] == "UNKNOWN" - assert ( - run["reason"] == "app appmod:app has no application routes; rest-api skipped (pass --sharpit-app module:attr)" - ) + assert run["reason"] == "application routes cannot be inspected (Flask URL map)" From 0138887455b58eeecf8329c27156568d6a933c08 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:34:45 +0000 Subject: [PATCH 16/18] fix: reject Flask descriptors during introspection Signed-off-by: Flavio Oliva --- src/sharpit/flask/introspector.py | 6 ++++-- src/sharpit/pytest_plugin/apps.py | 4 +--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/sharpit/flask/introspector.py b/src/sharpit/flask/introspector.py index 749c3bcda..af5846bbb 100644 --- a/src/sharpit/flask/introspector.py +++ b/src/sharpit/flask/introspector.py @@ -9,8 +9,9 @@ from types import FunctionType from typing import cast -from flask import Flask from werkzeug.routing import Map + +from flask import Flask from sharpit.engine.spi import AppInfo, ProviderInfo, RouteInfo _PARAMETER = re.compile(r"<(?:(?:[^<>:]+):)?([^<>:]+)>") @@ -19,7 +20,8 @@ def _attribute(value: object, name: str) -> object | None: result = inspect.getattr_static(value, name, _MISSING) - if result is _MISSING or inspect.isdatadescriptor(result): + result_type = cast(type[object], type(result)) + if result is _MISSING or inspect.getattr_static(result_type, "__get__", _MISSING) is not _MISSING: return None return result diff --git a/src/sharpit/pytest_plugin/apps.py b/src/sharpit/pytest_plugin/apps.py index e62d36bc2..a1836fc80 100644 --- a/src/sharpit/pytest_plugin/apps.py +++ b/src/sharpit/pytest_plugin/apps.py @@ -202,9 +202,7 @@ def load_app(spec: str) -> tuple[str, object]: def _is_flask_app(app: object) -> bool: - return not ( - _classes("flask.app", "Flask") | _classes("flask.sansio.app", "Flask") - ).isdisjoint(type(app).__mro__) + return not (_classes("flask.app", "Flask") | _classes("flask.sansio.app", "Flask")).isdisjoint(type(app).__mro__) def _app_model(app: object) -> ApiModel | None: From 0bf1688cf6563931a844694e6498c714ce4fca6e Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 02:50:08 +0000 Subject: [PATCH 17/18] refactor: drop a redundant group from the Flask parameter pattern Signed-off-by: Flavio Oliva --- src/sharpit/flask/introspector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sharpit/flask/introspector.py b/src/sharpit/flask/introspector.py index af5846bbb..9b630b79c 100644 --- a/src/sharpit/flask/introspector.py +++ b/src/sharpit/flask/introspector.py @@ -14,7 +14,7 @@ from flask import Flask from sharpit.engine.spi import AppInfo, ProviderInfo, RouteInfo -_PARAMETER = re.compile(r"<(?:(?:[^<>:]+):)?([^<>:]+)>") +_PARAMETER = re.compile(r"<(?:[^<>:]+:)?([^<>:]+)>") _MISSING = object() From f15d47018594ee203fc30c3bd3bbaa1a0f02a7e8 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Sat, 21 Nov 2026 03:36:00 +0000 Subject: [PATCH 18/18] test: exercise Flask rule descriptors with Werkzeug Map Signed-off-by: Flavio Oliva --- tests/flask/test_introspector.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/flask/test_introspector.py b/tests/flask/test_introspector.py index c865ae5ec..a361a4e3e 100644 --- a/tests/flask/test_introspector.py +++ b/tests/flask/test_introspector.py @@ -6,7 +6,8 @@ from importlib.metadata import version from typing import Any -from werkzeug.routing import BaseConverter +from werkzeug.routing import BaseConverter, Map +from werkzeug.routing import Rule as WerkzeugRule from flask import Flask from sharpit.engine.spi import AppInfo, RouteInfo @@ -165,17 +166,21 @@ def __getattribute__(self, name: str) -> object: def test_routes_do_not_evaluate_rule_properties() -> None: accesses: list[str] = [] - class Rule: + class Rule(WerkzeugRule): + def __init__(self) -> None: + super().__init__("/unsafe", endpoint="unsafe") + @property - def rule(self) -> str: - accesses.append("rule") - return "/unsafe" + def methods(self) -> set[str]: + accesses.append("methods") + return {"GET"} - endpoint = "unsafe" - methods = {"GET"} + @methods.setter + def methods(self, value: set[str] | None) -> None: + object.__setattr__(self, "_methods", value) app = Flask("unsafe-rule", static_folder=None) - app.url_map = type("Map", (), {"iter_rules": lambda _self: [Rule()]})() # type: ignore[assignment] + app.url_map = Map([Rule()]) app.view_functions["unsafe"] = lambda: "unsafe" _introspector(app).routes()