Skip to content

src/genro_asgi/middleware/wellknown.py

Source from this local checkout, regenerated when the reader rebuilds. Line links use #L<number>; a GitHub line range opens its first line.

1 # Copyright 2025 Softwell S.r.l.2 #3 # Licensed under the Apache License, Version 2.0 (the "License");4 # you may not use this file except in compliance with the License.5 # You may obtain a copy of the License at6 #7 #     https://www.apache.org/licenses/LICENSE-2.08 #9 # Unless required by applicable law or agreed to in writing, software10 # distributed under the License is distributed on an "AS IS" BASIS,11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12 # See the License for the specific language governing permissions and13 # limitations under the License.14 15 """Well-known / probe path filter.16 17 Browsers and bots probe a handful of conventional paths on every site18 (``/.well-known/*`` per RFC 8615, ``/robots.txt``, ``/sitemap.xml``). When19 the site does not expose them, this middleware answers with a clean 40420 instead of letting the probe reach the mounted application.21 """22 23 from __future__ import annotations24 25 from typing import TYPE_CHECKING26 27 from ..exceptions import HTTPNotFound28 from .base import BaseMiddleware29 30 if TYPE_CHECKING:31     from ..types import Receive, Scope, Send32 33 __all__ = ["WellKnownMiddleware"]34 35 36 class WellKnownMiddleware(BaseMiddleware):37     """Raise 404 for well-known/probe paths; delegate everything else."""38 39     middleware_order = 15040     middleware_default = False41 42     PROBE_PATHS = frozenset({"/robots.txt", "/sitemap.xml"})43     WELL_KNOWN_PREFIX = "/.well-known/"44 45     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:46         """Raise ``HTTPNotFound`` for a probe path; otherwise delegate to the wrapped app."""47         path = scope.get("path", "/")48         if self._is_probe(path):49             raise HTTPNotFound(f"Not found: {path}")50         await self.app(scope, receive, send)51 52     def _is_probe(self, path: str) -> bool:53         return path in self.PROBE_PATHS or path.startswith(self.WELL_KNOWN_PREFIX)