Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /terrene-foundation_kailash-py /src /kailash /utils /proxy_guard.py
| # Copyright 2026 Terrene Foundation | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """Fail-closed registration guard for reverse-proxy workflow routes. | |
| Issue #2025. Two independent surfaces registered an **unauthenticated** | |
| catch-all reverse proxy: | |
| * ``kailash.servers.WorkflowServer.proxy_workflow`` -> ``/workflows/{name}/{path:path}`` | |
| * ``kailash.api.WorkflowAPIGateway.proxy_workflow`` -> ``/{name}/{path:path}`` | |
| Both forwarded an arbitrary method, path, and query string to a proxied backend | |
| and returned the body to the caller. Where the backend is an internal service -- | |
| the usual reason to configure a proxy at all -- that is an authentication bypass | |
| onto the backend's entire surface, and ``WorkflowServer`` compounded it by | |
| stripping ``Authorization`` on forward so the backend could not re-authorize | |
| either. | |
| CodeQL surfaced this as ``py/partial-ssrf`` and the alert was **right**. An | |
| earlier version of this docstring argued that no authority pivot was | |
| constructible because the scheme, host and port come from the developer-supplied | |
| ``proxy_url``. That claim was false twice over, and both refutations are worth | |
| carrying because each was reasoned-about rather than measured: | |
| 1. The handlers captured ``proxy_url`` as a **default argument** | |
| (``_url=proxy_url``). FastAPI treats any non-path parameter carrying a plain | |
| default as a QUERY parameter, so the destination was caller-writable: | |
| ``?_url=http://attacker/`` redirected the proxy outright. Fixed by capturing | |
| from the enclosing scope. | |
| 2. Even with the destination fixed, the claim holds **only for hop 1**. All the | |
| controls below stop where a redirect begins: a backend with any open redirect | |
| (an SSO ``?next=`` bounce is ubiquitous) hands the caller an authority pivot | |
| on hop 2, and the response-header allowlist hides ``location`` so the caller | |
| cannot even tell it happened. Redirect-following is therefore DISABLED | |
| explicitly at both call sites, and the no-authority-pivot property is | |
| conditional on that: **it holds only while redirects are not followed.** | |
| The severity was right and, if anything, under-rated -- ``partial-ssrf`` on what | |
| was a full SSRF. The mechanism named in the issue, the **missing auth gate**, is | |
| real but was not the whole of it. | |
| Per ``rules/security.md`` § Enforcement-Surface Parity both surfaces MUST learn | |
| the gate together, through ONE shared implementation -- hence this module rather | |
| than a fix in either server. Per ``rules/security.md`` § Secure-Default the gate | |
| **fails closed**: registration raises unless the caller supplies a real | |
| authentication control, matching the precedent set for | |
| ``Nexus(enable_auth=True)`` (#2013 / PR #2054) and ``APIGateway(enable_auth=True)`` | |
| (#636), both of which now refuse to construct rather than silently serve an open | |
| API. | |
| The four registration-time controls: | |
| 1. **Authentication** -- :func:`resolve_proxy_auth_dependency` returns the | |
| FastAPI dependency to attach to the route, or raises | |
| :class:`ProxyAuthNotConfiguredError`. | |
| 2. **Path allowlist** -- :func:`compile_path_allowlist` + | |
| :func:`path_matches_allowlist` replace the unbounded ``{path:path}`` | |
| catch-all. ``["*"]`` restores the old behaviour, but only when written | |
| down explicitly. | |
| 3. **Method allowlist** -- :func:`normalize_allowed_methods` defaults to | |
| ``["GET"]`` rather than every verb. | |
| 4. **Traversal rejection** -- :func:`reject_unsafe_proxy_path` refuses ``..`` | |
| segments and encoded separators before the target URL is built, rather | |
| than relying on the HTTP client's URL normalization. | |
| Segment-parameter collapse (#2087) and what this guard does NOT close | |
| --------------------------------------------------------------------- | |
| The ``..`` segment check above is correct for the RFC 3986 shape and was | |
| BYPASSABLE for the servlet-class one. Tomcat, Jetty and others strip | |
| everything from ``;`` to the end of a path segment while resolving it, so a | |
| segment of ``..;`` is not equal to ``..`` at this proxy, passes the check, | |
| and is then normalised BY THE BACKEND to ``..`` -- restoring the traversal | |
| the guard exists to prevent. ``..;foo``, ``..%3B`` and the double-encoded | |
| ``..%253B`` are the same defect under different spellings. | |
| The approach taken is deliberately the NARROW one of the three the issue | |
| weighed: :func:`_collapse_segment_parameters` models the servlet path- | |
| parameter rule for ONE purpose -- deciding whether a segment would BECOME a | |
| dot-segment -- and the refusal fires only when it would. A segment carrying a | |
| legitimate matrix parameter (``products;color=blue``, ``a;jsessionid=xyz``) | |
| is untouched, because a blanket ban on ``;`` would be a regression: ``;`` is | |
| an RFC 3986 sub-delimiter and valid in paths. | |
| **This closes one MEMBER of the family, not the class**, and that is stated | |
| here rather than implied. The guard models the ``;`` convention because it is | |
| the one with known backends behind it. A backend that collapses a DIFFERENT | |
| character, or that applies a different normalisation before path resolution, | |
| reintroduces the same class under a new spelling and would need its own | |
| clause here. The alternative -- carrying a full normalisation model of "the | |
| strictest plausible backend" in core -- was rejected: it is a maintenance | |
| surface whose divergence from what the real backend does is itself a source | |
| of bypasses, and it would claim a completeness this cannot deliver. | |
| Also NOT closed, and worth naming so it is not assumed: this is a check on | |
| the path THIS process forwards. It does not constrain how the backend | |
| resolves the result, and it is not a substitute for the backend refusing to | |
| serve paths outside its own root. | |
| """ | |
| from __future__ import annotations | |
| import ipaddress | |
| import logging | |
| import re | |
| from typing import Any, Callable, Iterable, Optional, Sequence, Union | |
| from .network_guard import BlockedDestinationError | |
| from .network_guard import check_url as _check_destination_url | |
| logger = logging.getLogger(__name__) | |
| __all__ = [ | |
| "DEFAULT_MAX_RESPONSE_BYTES", | |
| "BlockedDestinationError", | |
| "ProxyResponseTooLargeError", | |
| "normalize_max_response_bytes", | |
| "reject_unsafe_proxy_destination", | |
| "DEFAULT_ALLOWED_METHODS", | |
| "PROXY_CREDENTIAL_HEADERS", | |
| "PROXY_HOP_BY_HOP_HEADERS", | |
| "PROXY_SAFE_RESPONSE_HEADERS", | |
| "PROXY_SUPPORTED_METHODS", | |
| "SAFE_FORWARD_PATH_RE", | |
| "PathPattern", | |
| "ProxyAuthNotConfiguredError", | |
| "compile_path_allowlist", | |
| "normalize_allowed_methods", | |
| "path_matches_allowlist", | |
| "reject_unsafe_proxy_path", | |
| "resolve_proxy_auth_dependency", | |
| ] | |
| #: Characters a forwarded path may contain, as a positive allowlist. | |
| #: | |
| #: RFC 3986 ``pchar`` (unreserved + sub-delims + ``:`` ``@`` ``%``) plus ``/``, | |
| #: plus every non-ASCII codepoint so internationalized paths still forward. | |
| #: Everything else is refused -- notably SPACE, CR, LF, TAB, every other C0 | |
| #: control, the C1 block (U+0080-U+009F, which includes U+0085 NEL), the | |
| #: Unicode line/paragraph separators U+2028/U+2029, and ``? # \ < > " { } | ^ ` ``. | |
| #: | |
| #: The C1 block and U+2028/U+2029 are excluded EXPLICITLY. An earlier version of | |
| #: this range ran from U+0080 and so admitted all of them while this comment | |
| #: claimed they were refused -- and no test carried a C1 character, so the suite | |
| #: could not have detected the gap. They matter because several parsers treat | |
| #: NEL and U+2028/U+2029 as line terminators. | |
| #: | |
| #: This is a **barrier**, not decoration. The captured group -- never the raw | |
| #: parameter -- is what the target URL is built from, so no un-validated byte | |
| #: can reach the wire. It settles a concern the #2025 analysis recorded as | |
| #: UNVERIFIED: whether a decoded CR/LF in the path could reach the wire as | |
| #: request-line injection. With this allowlist it cannot, regardless of how | |
| #: the HTTP client happens to re-encode. | |
| SAFE_FORWARD_PATH_RE: re.Pattern = re.compile( | |
| r"[/A-Za-z0-9._~!$&'()*+,;=:@%\u00a0-\u2027\u202a-\U0010FFFF-]*" | |
| ) | |
| #: Every HTTP method a proxy registration may forward. | |
| PROXY_SUPPORTED_METHODS: tuple[str, ...] = ( | |
| "GET", | |
| "POST", | |
| "PUT", | |
| "DELETE", | |
| "PATCH", | |
| "HEAD", | |
| "OPTIONS", | |
| ) | |
| #: Methods forwarded when a registration does not name any. Read-only by | |
| #: default -- a proxy that also writes to the backend must say so. | |
| DEFAULT_ALLOWED_METHODS: tuple[str, ...] = ("GET",) | |
| #: A compiled allowlist entry accepts either a string pattern or a regex. | |
| PathPattern = Union[str, re.Pattern] | |
| #: Request headers carrying the CALLER's credentials, stripped before a proxy | |
| #: forward unless the registration explicitly opts into pass-through. | |
| #: | |
| #: The two surfaces disagreed before #2025 and both were wrong in opposite | |
| #: directions: ``WorkflowServer`` stripped ``Authorization`` unconditionally, | |
| #: so the backend could never re-authorize; ``WorkflowAPIGateway`` excluded | |
| #: only ``host``/``content-length``, so it handed the caller's credentials to | |
| #: whichever round-robin backend was selected. One constant, one default | |
| #: (strip), one explicit opt-in (``forward_credentials=True``). | |
| PROXY_CREDENTIAL_HEADERS: frozenset = frozenset( | |
| { | |
| "authorization", | |
| "cookie", | |
| "x-api-key", | |
| "x-auth-token", | |
| "x-access-token", | |
| "x-session-token", | |
| "x-csrf-token", | |
| "x-amz-security-token", | |
| "proxy-authorization", | |
| "set-cookie", | |
| } | |
| ) | |
| # NOTE on shape: the RESPONSE direction is an allowlist, this is a denylist, | |
| # and that asymmetry is deliberate. A reverse proxy must pass arbitrary | |
| # application headers through to its backend, so an allowlist here would | |
| # break every backend relying on a custom header. The denylist is therefore | |
| # maintained explicitly and is known-incomplete by construction -- a bearer | |
| # token under a header this set does not name still reaches the backend. | |
| # `forward_credentials=False` is the real control; this set narrows the blast | |
| # radius, it does not close the class. | |
| #: Hop-by-hop headers (RFC 9110 §7.6.1). These describe the CALLER's connection | |
| #: to this proxy and are meaningless -- and dangerous -- on the separate | |
| #: connection this proxy opens to the backend. They MUST NOT be forwarded. | |
| #: | |
| #: ``transfer-encoding`` is the sharp one: forwarding ``chunked`` alongside a | |
| #: body the HTTP client will frame itself gives the backend two disagreeing | |
| #: statements about where the request ends, which is the CL.TE request-smuggling | |
| #: primitive. ``connection``/``keep-alive``/``upgrade``/``te``/``trailer``/ | |
| #: ``proxy-connection`` leak or attempt to renegotiate connection semantics | |
| #: across a boundary they do not span; ``expect: 100-continue`` desynchronises | |
| #: the two legs. | |
| PROXY_HOP_BY_HOP_HEADERS: frozenset = frozenset( | |
| { | |
| "connection", | |
| "keep-alive", | |
| "proxy-connection", | |
| "te", | |
| "trailer", | |
| "transfer-encoding", | |
| "upgrade", | |
| "expect", | |
| } | |
| ) | |
| #: Response headers safe to pass back to the caller. | |
| #: | |
| #: ``content-encoding`` and ``content-length`` are deliberately ABSENT. Both | |
| #: HTTP clients used here return DECOMPRESSED bytes (``aiohttp``'s | |
| #: ``resp.read()``, ``httpx``'s ``resp.content``), so echoing the backend's | |
| #: ``Content-Encoding: gzip`` labels plaintext as compressed and echoing its | |
| #: ``Content-Length`` states the COMPRESSED length over a decompressed body. | |
| #: Either mismatch is a response-smuggling primitive for anything parsing the | |
| #: stream downstream. The ASGI server computes the correct framing itself. | |
| PROXY_SAFE_RESPONSE_HEADERS: frozenset = frozenset( | |
| { | |
| "content-type", | |
| "cache-control", | |
| "etag", | |
| "last-modified", | |
| } | |
| ) | |
| #: Bytes a proxied response body may occupy in this process before the proxy | |
| #: refuses it (#2085). Per-registration, so a backend that legitimately serves | |
| #: large exports can raise it without widening every other route. | |
| #: | |
| #: 64 MiB is chosen to be generous for API payloads while still bounding the | |
| #: damage: the pre-#2085 behaviour was UNBOUNDED, and concurrent requests | |
| #: multiply whatever the figure is. A finite documented default is the point; | |
| #: the exact number is a judgement call the registration can override. | |
| DEFAULT_MAX_RESPONSE_BYTES: int = 64 * 1024 * 1024 | |
| class ProxyResponseTooLargeError(ValueError): | |
| """A proxied backend response exceeded the registration's byte cap.""" | |
| def normalize_max_response_bytes( | |
| max_response_bytes: Optional[int], | |
| *, | |
| name: str, | |
| ) -> int: | |
| """Validate the per-registration response cap. | |
| Args: | |
| max_response_bytes: The cap. ``None`` selects | |
| :data:`DEFAULT_MAX_RESPONSE_BYTES`. | |
| name: Workflow identifier, for error messages. | |
| Returns: | |
| The cap in bytes. | |
| Raises: | |
| ValueError: The cap is not a positive integer. There is deliberately | |
| no "unlimited" spelling: ``0`` or a negative value raises rather | |
| than disabling the bound, because an unbounded proxy is the defect | |
| #2085 exists to close and a magic disable value is how it would | |
| quietly come back. | |
| """ | |
| if max_response_bytes is None: | |
| return DEFAULT_MAX_RESPONSE_BYTES | |
| if isinstance(max_response_bytes, bool) or not isinstance(max_response_bytes, int): | |
| raise ValueError( | |
| f"max_response_bytes for proxied workflow '{name}' must be a " | |
| f"positive integer, got {type(max_response_bytes).__name__} " | |
| f"({max_response_bytes!r})." | |
| ) | |
| if max_response_bytes <= 0: | |
| raise ValueError( | |
| f"max_response_bytes for proxied workflow '{name}' must be a " | |
| f"POSITIVE integer, got {max_response_bytes}. There is no " | |
| f"'unlimited' setting: unbounded buffering is the defect this cap " | |
| f"exists to close (issue #2085). Raise the cap instead." | |
| ) | |
| return max_response_bytes | |
| def reject_unsafe_proxy_destination( | |
| proxy_url: str, | |
| *, | |
| name: str, | |
| surface: str, | |
| blocked_networks: Optional[Sequence[ipaddress._BaseNetwork]] = None, | |
| allow_metadata_destination: bool = False, | |
| require_public_destination: bool = False, | |
| ) -> None: | |
| """Refuse a proxy registration whose DESTINATION is an unsafe address. | |
| The fifth registration-time control (#2091). The four above constrain what | |
| a CALLER can do; this one constrains what the DEPLOYMENT can point at. | |
| ``proxy_url`` comes from a developer calling a Python API, not from | |
| request data, so this is a deployment-misconfiguration surface rather | |
| than a caller-driven one -- materially lower severity than the defects | |
| #2064 closed, and worth stating rather than glossing. It still matters: | |
| a registration pointing at ``http://169.254.169.254/`` publishes cloud | |
| metadata -- including IAM credentials on the usual providers -- to every | |
| authenticated caller, and a reader of the pre-#2091 code would reasonably | |
| have concluded the destination was deliberately unconstrained. | |
| The decision logic is :func:`kailash.utils.network_guard.check_url`, | |
| which is the guard lifted out of ``nexus.http_client`` -- the reference | |
| implementation the issue named. Both now run the same code. | |
| Default posture, and why it is not simply nexus's | |
| ------------------------------------------------- | |
| Nexus blocks RFC1918 + loopback + link-local + IMDS, which is right for | |
| an outbound client talking to the public internet. A reverse proxy is | |
| frequently pointed at an internal service ON PURPOSE -- that is the | |
| common legitimate use -- so a blanket RFC1918 block here would break the | |
| normal case, and a control that breaks the normal case gets switched off | |
| wholesale, taking the IMDS protection with it. | |
| So the default blocks the subset with NO legitimate proxy use at all: | |
| cloud metadata addresses, the metadata hostnames, and link-local | |
| (169.254.0.0/16, fe80::/10). RFC1918 and loopback are permitted by | |
| default and can be blocked with ``require_public_destination=True``. | |
| Per ``security.md`` § Secure-Default the metadata block is ON by default | |
| with an EXPLICIT, LOUD opt-out: ``allow_metadata_destination=True`` logs | |
| a WARNING naming the protection being disabled. It is deliberately a | |
| separate argument from ``require_public_destination`` so that widening | |
| the posture for internal backends never silently widens IMDS too. | |
| Limits, stated rather than implied | |
| ---------------------------------- | |
| * The check runs at REGISTRATION, against the address the destination | |
| resolves to THEN. A hostname that resolves benign at registration and | |
| to 169.254.169.254 later is NOT caught -- this is not a DNS-rebinding | |
| defence. The metadata HOSTNAMES are additionally blocked by name, which | |
| does not depend on resolution. | |
| * A destination that cannot be resolved at registration is PERMITTED with | |
| a WARNING rather than refused. Backends legitimately are not up yet | |
| when the proxy is registered, and failing there would make the control | |
| one that deployments route around. The warning names the destination as | |
| unverified so the gap is visible rather than silent. | |
| Raises: | |
| BlockedDestinationError: The destination is in the blocked set. | |
| """ | |
| if allow_metadata_destination: | |
| logger.warning( | |
| "proxy_guard.metadata_destination_allowed", | |
| extra={"workflow": name, "surface": surface}, | |
| ) | |
| logger.warning( | |
| "Proxied workflow '%s' on %s registered with " | |
| "allow_metadata_destination=True: cloud-metadata and link-local " | |
| "destinations are NOT blocked for this route. On the usual cloud " | |
| "providers the metadata service hands out IAM credentials, so any " | |
| "caller authorized to use this proxy can read them (issue #2091).", | |
| name, | |
| surface, | |
| ) | |
| try: | |
| _check_destination_url( | |
| proxy_url, | |
| blocked_networks=blocked_networks, | |
| allow_private=not require_public_destination, | |
| allow_metadata=allow_metadata_destination, | |
| resolve_dns=True, | |
| ) | |
| except BlockedDestinationError as exc: | |
| if exc.reason != "resolution_failed": | |
| raise | |
| # Not fatal -- see "Limits" above. Loud, and it names what was not | |
| # checked, so an unverified destination is visible rather than silent. | |
| logger.warning( | |
| "proxy_guard.destination_unresolved", | |
| extra={ | |
| "workflow": name, | |
| "surface": surface, | |
| "url_fingerprint": exc.url_fingerprint, | |
| }, | |
| ) | |
| logger.warning( | |
| "Destination for proxied workflow '%s' on %s could not be " | |
| "resolved at registration, so its address was NOT checked " | |
| "against the blocked set (issue #2091). Registration proceeds " | |
| "because a backend is legitimately not always up yet at " | |
| "registration time.", | |
| name, | |
| surface, | |
| ) | |
| class ProxyAuthNotConfiguredError(RuntimeError): | |
| """Raised when a proxy route would be registered with no authentication. | |
| This is the fail-closed half of issue #2025. It fires at **registration** | |
| time (``proxy_workflow(...)``), not at request time, so the failure lands | |
| in the deployment that misconfigured the proxy rather than silently | |
| exposing the backend to every caller. | |
| """ | |
| def _auth_error_message(surface: str, name: str) -> str: | |
| """Build the actionable message naming every accepted wiring.""" | |
| return ( | |
| f"Refusing to register unauthenticated proxy route for workflow " | |
| f"'{name}' on {surface}. A proxy route forwards arbitrary requests to " | |
| f"the backend at the registered URL, so registering one without an " | |
| f"authentication control publishes that backend to every caller " | |
| f"(issue #2025).\n" | |
| f"Supply exactly one of:\n" | |
| f" - proxy_workflow(..., auth_dependency=<callable>) -- any FastAPI " | |
| f"dependency that raises HTTPException(401/403) for unauthenticated " | |
| f"callers;\n" | |
| f" - an auth manager on the server: " | |
| f"WorkflowServer(auth_manager=...) / server.set_auth_manager(...) / " | |
| f"WorkflowAPIGateway(auth_manager=...), where the manager exposes " | |
| f"get_current_user_dependency() -- " | |
| f"kailash.middleware.auth.MiddlewareAuthManager is the shipped " | |
| f"implementation;\n" | |
| f" - server.declare_external_auth('<reason>') when an ASGI " | |
| f"middleware you installed on this app already authenticates every " | |
| f"request (for example nexus.auth.jwt.JWTMiddleware, installed by " | |
| f"Nexus(enable_auth=True)). This records an explicit, logged " | |
| f"acknowledgement -- it does not install anything." | |
| ) | |
| def resolve_proxy_auth_dependency( | |
| *, | |
| name: str, | |
| surface: str, | |
| auth_dependency: Optional[Callable[..., Any]] = None, | |
| auth_manager: Any = None, | |
| external_auth_reason: Optional[str] = None, | |
| ) -> Optional[Callable[..., Any]]: | |
| """Resolve the authentication dependency for a proxy route, or refuse. | |
| Resolution order, most specific first: | |
| 1. ``auth_dependency`` -- attached to the route verbatim. | |
| 2. ``auth_manager`` -- ``auth_manager.get_current_user_dependency()`` is | |
| called and its return value attached. | |
| 3. ``external_auth_reason`` -- the caller has explicitly declared that an | |
| ASGI middleware outside this class authenticates the app. Returns | |
| ``None`` (no route dependency) after logging a WARNING. | |
| 4. Nothing -- :class:`ProxyAuthNotConfiguredError`. | |
| Args: | |
| name: Workflow identifier being registered, for the error message. | |
| surface: Human-readable name of the registering class, for the message. | |
| auth_dependency: An explicit FastAPI dependency callable. | |
| auth_manager: An object exposing ``get_current_user_dependency()``. | |
| external_auth_reason: Non-empty justification recorded by | |
| ``declare_external_auth``. | |
| Returns: | |
| The dependency callable to attach to the route, or ``None`` when | |
| authentication is enforced by externally-declared middleware. | |
| Raises: | |
| ProxyAuthNotConfiguredError: When no authentication source is | |
| configured, or when ``auth_manager`` does not expose a usable | |
| ``get_current_user_dependency()``. | |
| """ | |
| if auth_dependency is not None: | |
| if not callable(auth_dependency): | |
| raise ProxyAuthNotConfiguredError( | |
| f"auth_dependency for proxied workflow '{name}' is not " | |
| f"callable (got {type(auth_dependency).__name__}). FastAPI " | |
| f"dependencies must be callables." | |
| ) | |
| return auth_dependency | |
| if auth_manager is not None: | |
| # Fail-CLOSED probe. A `hasattr` guard whose False branch silently | |
| # continues is the exact shape that shipped `enable_auth=True` as a | |
| # no-op for two releases (#2013, `zero-tolerance.md` Rule 3d): the | |
| # probed name had zero definitions anywhere, so the install never ran | |
| # and nothing said so. Here the absent branch RAISES, so a manager | |
| # that cannot produce a dependency stops the registration instead of | |
| # quietly leaving the route open. | |
| factory = getattr(auth_manager, "get_current_user_dependency", None) | |
| if not callable(factory): | |
| raise ProxyAuthNotConfiguredError( | |
| f"auth_manager supplied for proxied workflow '{name}' " | |
| f"({type(auth_manager).__name__}) does not expose a callable " | |
| f"get_current_user_dependency(); it cannot authenticate the " | |
| f"proxy route. kailash.middleware.auth.MiddlewareAuthManager " | |
| f"is the shipped implementation of that contract." | |
| ) | |
| dependency = factory() | |
| if not callable(dependency): | |
| raise ProxyAuthNotConfiguredError( | |
| f"auth_manager.get_current_user_dependency() for proxied " | |
| f"workflow '{name}' returned " | |
| f"{type(dependency).__name__}, which is not callable and " | |
| f"cannot be used as a FastAPI dependency." | |
| ) | |
| return dependency | |
| if external_auth_reason: | |
| logger.warning( | |
| "proxy_guard.external_auth_declared", | |
| extra={ | |
| "workflow": name, | |
| "surface": surface, | |
| "reason": external_auth_reason, | |
| }, | |
| ) | |
| logger.warning( | |
| "Proxied workflow '%s' registered on %s with NO route-level " | |
| "authentication; the deployment declared that an external ASGI " | |
| "middleware authenticates every request. Reason: %s. If that " | |
| "middleware is ever removed or misconfigured this route forwards " | |
| "unauthenticated requests to the backend (issue #2025).", | |
| name, | |
| surface, | |
| external_auth_reason, | |
| ) | |
| return None | |
| raise ProxyAuthNotConfiguredError(_auth_error_message(surface, name)) | |
| def normalize_allowed_methods( | |
| methods: Optional[Sequence[str]], | |
| *, | |
| name: str, | |
| supported: Sequence[str] = PROXY_SUPPORTED_METHODS, | |
| ) -> list[str]: | |
| """Validate and normalize a per-registration HTTP method allowlist. | |
| Args: | |
| methods: Requested methods. ``None`` selects | |
| :data:`DEFAULT_ALLOWED_METHODS` (``["GET"]``). | |
| name: Workflow identifier, for error messages. | |
| supported: Methods this surface is able to forward. | |
| Returns: | |
| Upper-cased methods, de-duplicated, in ``supported`` order so the | |
| registered route is stable regardless of caller ordering. | |
| Raises: | |
| ValueError: When the allowlist is empty or names an unsupported method. | |
| """ | |
| if methods is None: | |
| methods = DEFAULT_ALLOWED_METHODS | |
| if isinstance(methods, str): | |
| raise ValueError( | |
| f"allowed_methods for proxied workflow '{name}' must be a " | |
| f"sequence of method names, not a bare string " | |
| f"({methods!r}). Pass e.g. ['GET'] or ['GET', 'POST']." | |
| ) | |
| requested = [m.strip().upper() for m in methods if m and m.strip()] | |
| if not requested: | |
| raise ValueError( | |
| f"allowed_methods for proxied workflow '{name}' is empty. A proxy " | |
| f"registration must name at least one forwardable method; the " | |
| f"default is ['GET']." | |
| ) | |
| supported_upper = [m.upper() for m in supported] | |
| unsupported = sorted({m for m in requested if m not in supported_upper}) | |
| if unsupported: | |
| raise ValueError( | |
| f"allowed_methods for proxied workflow '{name}' names " | |
| f"unsupported method(s) {unsupported}. Supported: " | |
| f"{list(supported_upper)}." | |
| ) | |
| return [m for m in supported_upper if m in set(requested)] | |
| def compile_path_allowlist( | |
| patterns: Optional[Iterable[PathPattern]], | |
| *, | |
| name: str, | |
| ) -> list[PathPattern]: | |
| """Validate a path allowlist supplied at proxy registration. | |
| Replaces the unbounded ``{path:path}`` catch-all with an explicit set of | |
| forwardable paths. String patterns are matched against the forwarded path | |
| with the leading ``/`` stripped from both sides: | |
| * ``"*"`` -- every path. This restores the pre-#2025 behaviour and is | |
| accepted, but only when the deployment writes it down. | |
| * ``"api/*"`` -- ``api`` and anything beneath it, at any depth. | |
| * ``"status"`` -- that exact path and nothing else. | |
| A compiled :class:`re.Pattern` is matched with ``fullmatch`` against the | |
| same normalized path, for allowlists a prefix cannot express. | |
| Args: | |
| patterns: The allowlist. ``None`` or empty raises -- there is no | |
| implicit default, because the only safe implicit default would be | |
| "deny everything", which silently breaks the proxy, and the only | |
| convenient one is the catch-all this rule exists to remove. | |
| name: Workflow identifier, for error messages. | |
| Returns: | |
| The normalized allowlist, ready for :func:`path_matches_allowlist`. | |
| Raises: | |
| ValueError: When the allowlist is missing, empty, or holds an entry | |
| that is neither a string nor a compiled regex. | |
| """ | |
| if patterns is None: | |
| raise ValueError( | |
| f"allowed_paths is required when registering proxied workflow " | |
| f"'{name}'. Before issue #2025 this route forwarded EVERY path " | |
| f"beneath it to the backend; that catch-all is now explicit. " | |
| f"Pass the paths the backend should expose, e.g. " | |
| f"allowed_paths=['execute', 'status'] or allowed_paths=['api/*'], " | |
| f"or allowed_paths=['*'] to keep forwarding every path." | |
| ) | |
| if isinstance(patterns, (str, re.Pattern)): | |
| raise ValueError( | |
| f"allowed_paths for proxied workflow '{name}' must be a sequence " | |
| f"of patterns, not a single {type(patterns).__name__} " | |
| f"({patterns!r}). Wrap it in a list: [{patterns!r}]." | |
| ) | |
| compiled: list[PathPattern] = [] | |
| for pattern in patterns: | |
| if isinstance(pattern, re.Pattern): | |
| compiled.append(pattern) | |
| continue | |
| if not isinstance(pattern, str): | |
| raise ValueError( | |
| f"allowed_paths for proxied workflow '{name}' holds a " | |
| f"{type(pattern).__name__} ({pattern!r}); entries must be " | |
| f"strings or compiled regular expressions." | |
| ) | |
| normalized = pattern.strip().lstrip("/") | |
| if not normalized: | |
| raise ValueError( | |
| f"allowed_paths for proxied workflow '{name}' holds an empty " | |
| f"pattern ({pattern!r}). Use '*' if every path should be " | |
| f"forwarded." | |
| ) | |
| compiled.append(normalized) | |
| if not compiled: | |
| raise ValueError( | |
| f"allowed_paths for proxied workflow '{name}' is empty. A proxy " | |
| f"registration must name at least one forwardable path; use " | |
| f"allowed_paths=['*'] to forward every path." | |
| ) | |
| return compiled | |
| def path_matches_allowlist(path: str, allowlist: Sequence[PathPattern]) -> bool: | |
| """Return True when ``path`` is forwardable under ``allowlist``. | |
| Args: | |
| path: The path captured by the route, with or without a leading ``/``. | |
| allowlist: The value returned by :func:`compile_path_allowlist`. | |
| Returns: | |
| True if any entry matches. An empty allowlist matches nothing -- | |
| deny-by-default, so a construction bug cannot open the route. | |
| """ | |
| candidate = path.lstrip("/") | |
| for entry in allowlist: | |
| if isinstance(entry, re.Pattern): | |
| if entry.fullmatch(candidate): | |
| return True | |
| continue | |
| if entry == "*": | |
| return True | |
| if entry.endswith("/*"): | |
| prefix = entry[:-2] | |
| if candidate == prefix or candidate.startswith(prefix + "/"): | |
| return True | |
| continue | |
| if entry.endswith("*"): | |
| if candidate.startswith(entry[:-1]): | |
| return True | |
| continue | |
| if candidate == entry: | |
| return True | |
| return False | |
| #: Percent-encoded separators and dot-segments. Starlette decodes a path | |
| #: parameter once, so a singly-encoded ``%2e%2e`` already arrives as ``..`` | |
| #: and is caught by the segment check below. These catch the DOUBLE-encoded | |
| #: form (``%252e%252e`` -> ``%2e%2e`` after Starlette's decode), which this | |
| #: process would forward verbatim for the backend to decode a second time. | |
| _ENCODED_TRAVERSAL_TOKENS: tuple[str, ...] = ("%2e", "%2f", "%5c") | |
| #: A still-encoded semicolon, in either case. Starlette decodes a path | |
| #: parameter ONCE, so ``..%3B/`` already arrives as ``..;/`` and is handled by | |
| #: the literal-``;`` truncation in :func:`_collapse_segment_parameters`. This | |
| #: catches the DOUBLE-encoded form (``..%253B/`` -> ``..%3B/`` after that | |
| #: decode), which this process would otherwise forward verbatim for the | |
| #: backend to decode a second time and then collapse. | |
| _ENCODED_SEMICOLON_RE: re.Pattern = re.compile(r"%3[bB]") | |
| def _collapse_segment_parameters(segment: str) -> str: | |
| """Return ``segment`` as a servlet-class backend would resolve it. | |
| Servlet-class backends (Tomcat, Jetty, and others following the same | |
| convention) treat everything from ``;`` to the end of a path SEGMENT as a | |
| path parameter -- ``jsessionid`` is the canonical one -- and strip it | |
| while resolving the path. So the segment ``..;`` is not equal to ``..`` | |
| at this proxy but IS ``..`` at the backend. | |
| The still-encoded ``%3B`` form is decoded first so the double-encoded | |
| spelling collapses the same way. | |
| """ | |
| return _ENCODED_SEMICOLON_RE.sub(";", segment).split(";", 1)[0] | |
| def reject_unsafe_proxy_path(path: str) -> Optional[str]: | |
| """Return a human-readable reason to refuse ``path``, or ``None``. | |
| Checked **before** the target URL is built, rather than relying on the | |
| HTTP client's URL normalization to collapse ``..`` -- ``yarl`` and | |
| ``httpx`` normalize differently, and neither is a security control. | |
| Args: | |
| path: The raw path captured by the proxy route. | |
| Returns: | |
| The refusal reason, or ``None`` when the path is safe to forward. | |
| """ | |
| if "\x00" in path: | |
| return "path contains a null byte" | |
| for char in path: | |
| code = ord(char) | |
| # C0 (incl. DEL) and C1. C1 is checked because U+0085 NEL and the | |
| # rest of that block are treated as line terminators by several | |
| # parsers, which makes them a header/request-line injection vector | |
| # exactly like CR and LF. | |
| if code < 0x20 or code == 0x7F or 0x80 <= code <= 0x9F: | |
| return "path contains a control character" | |
| if "\\" in path: | |
| return "path contains a backslash" | |
| lowered = path.lower() | |
| for token in _ENCODED_TRAVERSAL_TOKENS: | |
| if token in lowered: | |
| return f"path contains an encoded path separator or dot-segment ({token})" | |
| for segment in path.split("/"): | |
| if segment == "..": | |
| return "path contains a parent-directory segment (..)" | |
| # #2087: the segment is not `..` HERE, but a servlet-class backend | |
| # strips the path parameter and resolves it as `..`. Checked only | |
| # when the collapse actually changes the segment, so legitimate | |
| # matrix parameters (`products;color=blue`) are unaffected -- only a | |
| # segment that BECOMES a dot-segment is refused. | |
| if segment != ".." and _collapse_segment_parameters(segment) == "..": | |
| return ( | |
| "path contains a parent-directory segment carrying a path " | |
| "parameter (..;), which a servlet-class backend resolves to .." | |
| ) | |
| if "\u2028" in path or "\u2029" in path: | |
| return "path contains a Unicode line or paragraph separator" | |
| return None | |
Xet Storage Details
- Size:
- 35 kB
- Xet hash:
- caf006c16a592683234f137eaabeea8fe724fe63e9784d6812761a2391e5ddd6
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.