@@ -526,6 +526,7 @@ def _raise_if_failed(self) -> None:
526526_FRAMING_HEADERS = frozenset ({"content-length" , "transfer-encoding" })
527527# Workspace gateways read identity and routing from these, so only the SDK's credentials may set them.
528528_GATEWAY_HEADER_PREFIXES = ("x-databricks-" , "s2s-" )
529+ _LOOPBACK_HOSTS = ("127.0.0.1" , "localhost" )
529530
530531
531532class Forward :
@@ -679,6 +680,9 @@ def _relay(self, client: socket.socket) -> None:
679680 if request is None :
680681 client .sendall (_error_response (400 , "Bad Request" , "malformed request, or an unsupported path" ))
681682 return
683+ if _is_cross_site (request , self .server .server_address [1 ]):
684+ client .sendall (_error_response (403 , "Forbidden" , "requests must come from the forward's own URL" ))
685+ return
682686 target = self .server .target
683687 try :
684688 auth_headers = target .authenticate ()
@@ -795,6 +799,55 @@ def _parse_request(head: bytes) -> Optional[_Request]:
795799 return _Request (method , request_target , version , headers , connection_tokens , upgrade , body_length )
796800
797801
802+ def _is_cross_site (request : _Request , local_port : int ) -> bool :
803+ """Whether a browser sent the request for a page that is neither the forward nor a local app.
804+
805+ The relay attaches the SDK's credentials to every request, so a page on another site must
806+ not be able to make the user's browser send one. A ``Host`` other than the loopback address
807+ the relay listens on means the browser reached it through another name. A loopback ``Origin``
808+ passes whatever ``Sec-Fetch-Site`` says. Top-level GET navigations from other sites stay
809+ allowed, so links and sign-in redirects to the app work.
810+ Clients other than browsers send no ``Origin`` or ``Sec-Fetch-*`` headers and pass.
811+ """
812+ values : Dict [str , List [str ]] = {}
813+ for name , value in request .headers :
814+ values .setdefault (name .lower (), []).append (value )
815+ if any (len (values .get (name , [])) > 1 for name in ("host" , "sec-fetch-site" , "sec-fetch-mode" , "sec-fetch-dest" )):
816+ return True
817+ if not _is_loopback_authority (values .get ("host" , ["" ])[0 ], local_port ):
818+ return True
819+ origins = values .get ("origin" , [])
820+ if not all (_is_loopback_origin (origin ) for origin in origins ):
821+ return True
822+ # A page on the other loopback name, such as localhost:5173 calling 127.0.0.1, is cross-site
823+ # to the browser; its Origin, which pages can't set, still shows the page is local.
824+ if origins or values .get ("sec-fetch-site" , ["none" ])[0 ].lower () in ("same-origin" , "same-site" , "none" ):
825+ return False
826+ navigation = (
827+ request .method in ("GET" , "HEAD" )
828+ and values .get ("sec-fetch-mode" , ["" ])[0 ].lower () == "navigate"
829+ and values .get ("sec-fetch-dest" , ["" ])[0 ].lower () == "document"
830+ )
831+ return not navigation
832+
833+
834+ def _is_loopback_authority (authority : str , port : int ) -> bool :
835+ allowed = {f"{ host } :{ port } " for host in _LOOPBACK_HOSTS }
836+ if port == 80 :
837+ allowed .update (_LOOPBACK_HOSTS )
838+ return authority .lower () in allowed
839+
840+
841+ def _is_loopback_origin (origin : str ) -> bool :
842+ """Whether ``origin`` is an ``http`` origin on a loopback name, such as a local frontend
843+ calling the forwarded app. Any port is allowed."""
844+ try :
845+ parsed = urlsplit (origin )
846+ except ValueError :
847+ return False
848+ return parsed .scheme == "http" and parsed .hostname in _LOOPBACK_HOSTS and parsed .path == ""
849+
850+
798851def _rewrite_head (request : _Request , target : _Target , auth_headers : Dict [str , str ]) -> bytes :
799852 """Points the request at the sandbox port and replaces the caller's credentials with ``auth_headers``.
800853
@@ -1085,14 +1138,18 @@ def forward(self, name: str, remote_port: int, *, local_port: int = 0) -> Forwar
10851138 ``{sandbox_id}`` is also accepted. :attr:`Forward.url` is the local URL
10861139 to send requests to.
10871140
1088- The app must listen on ``0.0.0.0`` inside the sandbox. Ports 10000-65535
1089- are forwardable except 10101, 18767, and 19090. Clients speak HTTP/1.1 to
1141+ The app must listen on ``0.0.0.0`` inside the sandbox. The sandbox refuses
1142+ a few reserved platform ports; a request to a refused port gets a 403
1143+ response with a message saying why. Clients speak HTTP/1.1 to
10901144 the local port, including WebSocket upgrades; each local connection carries
10911145 one request. Requests whose path has a ``.`` or ``..`` segment, a ``;``, a
10921146 backslash, a control character, or an encoded ``/``, ``\\ ``, ``%``, ``?``,
10931147 or ``#`` get a local 400 response and are never sent, as do malformed
1094- heads. The caller's ``Authorization``, ``X-Databricks-*``, and ``S2S-*``
1095- headers are not forwarded, and the SDK's credentials are added.
1148+ heads. Requests must name ``127.0.0.1:<local_port>`` or
1149+ ``localhost:<local_port>`` as ``Host``; requests that a page on another site
1150+ makes a browser send get a 403, except top-level page loads. The caller's
1151+ ``Authorization``, ``X-Databricks-*``, and ``S2S-*`` headers are not
1152+ forwarded, and the SDK's credentials are added.
10961153 """
10971154 cfg = self ._api ._cfg
10981155 if not cfg .host :
0 commit comments