holoviz/panel · #9197
Tighten autoload.js origin checks and cookie handling
doc/how_to/authentication/configuration.md1 + / 1 −
@@ -147,7 +147,7 @@ pn.serve(app, cookie_path="/sub/path", ...) The cookies Panel sets during authentication are `HttpOnly` and `SameSite=Lax`, and they are marked `Secure` when the request is made over HTTPS. If a proxy terminates TLS in front of Panel, serve with `--use-xheaders` so that Panel sees the original protocol. -Since the cookies are `SameSite=Lax`, browsers only send them to Panel from pages on the same site, so an authenticated app can be embedded with `server_document` or its `autoload.js` script only on a page of the same site, e.g. a sibling subdomain. That page must also be allowed to connect to the websocket with `--allow-websocket-origin`. The session token handed to a page whose origin is not allowed does not include the user's cookies or authorization headers.+Since the cookies are `SameSite=Lax`, browsers only send them to Panel from pages on the same site, so an authenticated app can be embedded with `server_document` or its `autoload.js` script only on a page of the same site, e.g. a sibling subdomain. That page must also be allowed to connect to the websocket with `--allow-websocket-origin`, by name or a pattern such as `*.example.com`; a catch-all `*` lets any page connect but does not vouch for any of them. The session token handed to a page whose origin is not allowed does not include the user's cookies or the request headers that may carry credentials. ## `oauth_expiry` panel/auth.py3 + / 2 −
@@ -420,12 +420,13 @@ def get_code(self): def get_code_cookie(self): code = (self.get_secure_cookie(CODE_COOKIE_NAME, max_age_days=config.oauth_expiry) or b'').decode('utf8', 'replace')- self.clear_cookie(CODE_COOKIE_NAME, path=config.cookie_path)+ self.clear_cookie(CODE_COOKIE_NAME, path='/') return code def set_code_cookie(self, code): self.set_secure_cookie(- CODE_COOKIE_NAME, code, expires_days=config.oauth_expiry, **cookie_options(self)+ CODE_COOKIE_NAME, code, expires_days=config.oauth_expiry,+ **cookie_options(self, path='/') ) async def get(self):panel/io/asgi.py15 + / 7 −
@@ -41,17 +41,16 @@ ) from .document import _cleanup_doc, extra_socket_handlers from .logging import LOG_SESSION_CREATED-from .proxy import forwarded_prefix+from .proxy import forwarded_prefix, forwarded_proto from .reload import record_modules from .resources import COMPONENT_PATH, DIST_DIR, Resources from .server import ( INDEX_HTML, _app_route_path, _sanitize_route_context, authorize_app_request, authorize_request, autoload_cors_headers,- autoload_js_script, compile_route_template, credentials_allowed,- index_redirect, render_auth_error, render_index_page,+ autoload_js_script, compile_route_template, credential_allowlist,+ credentials_allowed, index_redirect, render_auth_error, render_index_page, resolve_component_resource, resolve_session, server_html_page_for_session, strip_request_credentials, token_payload_for_request, validate_static_dirs,- websocket_allowlist, ) from .session import generate_session from .state import set_curdoc, state@@ -89,6 +88,8 @@ logger = logging.getLogger(__name__) +_WS_SCHEMES = {'http': 'ws', 'https': 'wss'}+ __all__ = ("PanelASGI", "build_asgi_app", "dispatch_asgi") # Application sub-routes, in the order Tornado registers them so that@@ -420,6 +421,10 @@ def _resolve_application(self, route: str) -> tuple[ApplicationContext, str] | N def _request(self, scope: Scope) -> ServerRequest: request = super()._request(scope)+ if self._use_xheaders and (proto := forwarded_proto(request.headers)):+ # Matches Tornado, which takes the protocol from the proxy headers+ # when serving with xheaders.+ request.protocol = proto if scope['type'] == 'http' else _WS_SCHEMES[proto] if self._use_xheaders and not request.root_path.strip('/'): if root_path := forwarded_prefix(request.headers): # Matches a root path set on the ASGI server, which also@@ -819,7 +824,10 @@ async def _autoload( if method == 'OPTIONS': await self._respond( request, send, 204, b'', 'text/plain',- extra_headers=self._cors_headers(request, preflight=True)+ extra_headers=[+ *self._cors_headers(request, preflight=True),+ (b'cache-control', b'no-store'),+ ] ) return if not await self._check_method(request, send, ('GET', 'HEAD', 'OPTIONS')):@@ -833,7 +841,7 @@ async def _autoload( 'text/plain', head=head ) return- allowlist = websocket_allowlist(self._core.websocket_origins)+ allowlist = credential_allowlist(self._core.websocket_origins) if not credentials_allowed(request, allowlist): strip_request_credentials(request) @@ -894,7 +902,7 @@ async def _autoload( def _cors_headers( # type: ignore[override] self, request: ServerRequest, preflight: bool = False ) -> list[tuple[bytes, bytes]]:- allowlist = websocket_allowlist(self._core.websocket_origins)+ allowlist = credential_allowlist(self._core.websocket_origins) headers = autoload_cors_headers(request, allowlist, preflight=preflight) headers['Access-Control-Allow-Methods'] = 'GET, HEAD, OPTIONS' return [(name.lower().encode(), value.encode()) for name, value in headers.items()]panel/io/proxy.py9 + / 0 −
@@ -68,6 +68,15 @@ def forwarded_prefix(headers: Mapping[str, str]) -> str: return '' +def forwarded_proto(headers: Mapping[str, str]) -> str | None:+ """+ The protocol the client used, as declared by the ``X-Forwarded-Proto``+ header, or None if it is missing or neither http nor https.+ """+ proto = (_header(headers, 'X-Forwarded-Proto') or '').lower()+ return proto if proto in ('http', 'https') else None++ def forwarded_host(headers: Mapping[str, str]) -> str | None: """ The host the client addressed, as declared by the ``X-Forwarded-Host``panel/io/server.py84 + / 49 −
@@ -673,43 +673,76 @@ def token_payload_for_request(app: t.Any, request: t.Any) -> TokenPayload: return payload -_CREDENTIAL_HEADERS = ('authorization', 'cookie', 'proxy-authorization')--# Authenticating proxies, e.g. oauth2-proxy, forward the user identity and-# tokens in headers with these prefixes, next to the X-Forwarded headers-# describing the original request, which are kept.-_CREDENTIAL_HEADER_PREFIXES = ('x-forwarded-', 'x-auth-request-')-_ROUTING_HEADERS = (- 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-port',- 'x-forwarded-prefix', 'x-forwarded-proto', 'x-forwarded-scheme',- 'x-forwarded-server',+# The headers kept in the session token of a request whose origin may not+# receive credentials. Proxies and gateways forward identities and tokens+# under many names, so anything not known to be harmless is dropped.+_PUBLIC_HEADERS = (+ 'accept', 'accept-encoding', 'accept-language', 'cache-control',+ 'connection', 'dnt', 'forwarded', 'host', 'origin', 'pragma', 'referer',+ 'upgrade-insecure-requests', 'user-agent', 'x-forwarded-for',+ 'x-forwarded-host', 'x-forwarded-port', 'x-forwarded-prefix',+ 'x-forwarded-proto', 'x-forwarded-scheme', 'x-forwarded-server',+ 'x-real-ip', 'x-script-name', )+_PUBLIC_HEADER_PREFIXES = ('sec-ch-', 'sec-fetch-') +_DEFAULT_PORTS = (':80', ':443') -def _is_credential_header(name: str) -> bool:++def _is_public_header(name: str) -> bool: name = name.lower()- return name in _CREDENTIAL_HEADERS or (- name.startswith(_CREDENTIAL_HEADER_PREFIXES) and name not in _ROUTING_HEADERS- )+ return name in _PUBLIC_HEADERS or name.startswith(_PUBLIC_HEADER_PREFIXES) -def websocket_allowlist(websocket_origins: t.Iterable[str]) -> list[str]:+def credential_allowlist(websocket_origins: t.Iterable[str]) -> list[str]: """- The hosts allowed to open a websocket, i.e. the ``--allow-websocket-origin``- hosts unless they are overridden with ``BOKEH_ALLOW_WS_ORIGIN``.+ The hosts whose pages may receive credentials from ``autoload.js``, i.e.+ the hosts allowed to open a websocket (``--allow-websocket-origin`` or+ ``BOKEH_ALLOW_WS_ORIGIN``) except catch-all ``*`` entries, which allow+ connections from anywhere but do not vouch for any particular page. """- return [host.lower() for host in (bk_settings.allowed_ws_origin() or websocket_origins)]+ hosts = bk_settings.allowed_ws_origin() or websocket_origins+ return [host.lower() for host in hosts if host.split(':')[0] != '*'] -def origin_allowed(origin: str, request: t.Any, allowlist: t.Sequence[str]) -> bool:+def _origin_host(origin: str) -> str | None:+ """+ The ``host[:port]`` of an ``Origin`` or ``Referer`` header value, or None+ if it is not a well-formed http(s) URL without credentials.+ """+ if not origin.isascii() or any(c.isspace() or not c.isprintable() for c in origin):+ return None+ try:+ parsed = urlparse(origin)+ hostname, port = parsed.hostname, parsed.port+ except ValueError:+ return None+ if parsed.scheme not in ('http', 'https') or not hostname or '@' in parsed.netloc:+ return None+ if ':' in hostname:+ hostname = f'[{hostname}]'+ return hostname if port is None else f'{hostname}:{port}'+++def _strip_default_port(host: str) -> str:+ return host[:host.rindex(':')] if host.endswith(_DEFAULT_PORTS) else host+++def origin_allowed(+ origin: str, request: t.Any, allowlist: t.Sequence[str], same_host: bool = True+) -> bool: """ Whether ``origin``, the value of an ``Origin`` or ``Referer`` header, is- the origin of ``request`` itself or one of the ``allowlist`` hosts.+ one of the ``allowlist`` hosts or, if ``same_host``, the host of+ ``request`` itself. """- origin_host = urlparse(origin).netloc.lower()- if not origin_host:+ origin_host = _origin_host(origin)+ if origin_host is None: return False- return origin_host == (request.host or '').lower() or check_allowlist(origin_host, allowlist)+ request_host = (request.host or '').lower()+ if same_host and _strip_default_port(origin_host) == _strip_default_port(request_host):+ return True+ return check_allowlist(origin_host, allowlist) def credentials_allowed(request: t.Any, allowlist: t.Sequence[str]) -> bool:@@ -720,40 +753,41 @@ def credentials_allowed(request: t.Any, allowlist: t.Sequence[str]) -> bool: A browser attaches cookies to requests for scripts included by any page, so a script embedding a session token must only carry them when the page including it is allowed to connect to the websocket anyway. The page is- identified by the ``Origin`` header or, for a plain ``<script>`` include- which does not send one, the ``Referer`` header the browser sends for a- request it marks as ``cross-site`` or ``same-site`` in ``Sec-Fetch-Site``.- Requests without any of these headers do not originate from a page- embedding the script, e.g. those of non-browser clients, and are allowed.+ identified by the ``Sec-Fetch-Site`` header when it reports a same-origin+ request, and otherwise by the ``Origin`` header or, for a plain+ ``<script>`` include which does not send one, the ``Referer`` header.+ Browsers omit ``Sec-Fetch-Site`` for plain http servers, so its absence+ does not prove anything. Requests without any of these headers do not+ identify a page, e.g. those of non-browser clients, and are allowed. """ headers = request.headers fetch_site = (headers.get('Sec-Fetch-Site') or '').lower() if fetch_site in ('same-origin', 'none'): return True- origin = headers.get('Origin')- if origin is None and fetch_site in ('cross-site', 'same-site'):- origin = headers.get('Referer')- if origin is None:- return False+ cross_origin = fetch_site in ('cross-site', 'same-site')+ origin = headers.get('Origin') or headers.get('Referer') if origin is None:- return True- return origin_allowed(origin, request, allowlist)+ return not cross_origin+ # A request the browser marks as cross-site comes from another origin+ # even if it names this host, e.g. from a sandboxed iframe.+ return origin_allowed(origin, request, allowlist, same_host=not cross_origin) def strip_request_credentials(request: t.Any) -> None: """- Removes the cookies and credential bearing headers from a Tornado- ``HTTPServerRequest`` or a Bokeh ``ServerRequest`` so that a session- token generated for it does not contain them.+ Removes the cookies, the authenticated user and all headers that may+ carry credentials from a Tornado ``HTTPServerRequest`` or a Bokeh+ ``ServerRequest`` so that a session created for it does not see them. """- names = [name for name in request.headers if _is_credential_header(name)]+ names = [name for name in request.headers if not _is_public_header(name)] if isinstance(request.headers, HTTPHeaders): for name in names: del request.headers[name] request.__dict__.pop('_cookies', None) else: request.headers = Headers({k: v for k, v in request.headers.items() if k not in names}) request.cookies = {}+ request.user = None def autoload_cors_headers(@@ -762,19 +796,20 @@ def autoload_cors_headers( """ The CORS headers of an ``autoload.js`` response. Credentialed requests, e.g. the XHR ``server_document`` issues when given ``headers``, are only- allowed from the origin of the request itself and the websocket allowlist.+ allowed from the origin of the request itself and the credential allowlist. """+ cors = {'Vary': 'Origin'} origin = request.headers.get('Origin') if origin is None or not origin_allowed(origin, request, allowlist):- return {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*'}- cors = {- 'Access-Control-Allow-Origin': origin,- 'Access-Control-Allow-Credentials': 'true',- 'Vary': 'Origin',- }+ cors['Access-Control-Allow-Origin'] = '*'+ if preflight:+ cors['Access-Control-Allow-Headers'] = '*'+ return cors+ cors['Access-Control-Allow-Origin'] = origin+ cors['Access-Control-Allow-Credentials'] = 'true' # A wildcard does not cover the headers of a credentialed request- requested = request.headers.get('Access-Control-Request-Headers') if preflight else None- cors['Access-Control-Allow-Headers'] = requested or '*'+ if preflight and (requested := request.headers.get('Access-Control-Request-Headers')):+ cors['Access-Control-Allow-Headers'] = requested return cors @@ -1301,7 +1336,7 @@ def set_default_headers(self) -> None: @property def _allowlist(self) -> list[str]:- return websocket_allowlist(self.application.websocket_origins)+ return credential_allowlist(self.application.websocket_origins) async def options(self, *args, **kwargs) -> None: self.set_header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS')panel/tests/io/test_auth.py66 + / 1 −
@@ -3,6 +3,7 @@ handlers run headlessly by panel.io.auth.PanelAuthPolicy. """ import datetime as dt+import typing as t from urllib.parse import parse_qs, urlparse @@ -16,7 +17,8 @@ from tornado.web import create_signed_value, decode_signed_value from panel.auth import (- AUTH_PROVIDERS, BasicAuthProvider, OAuthLoginHandler, OAuthProvider,+ AUTH_PROVIDERS, BasicAuthProvider, CodeChallengeLoginHandler,+ OAuthLoginHandler, OAuthProvider, ) from panel.config import config from panel.io.asgi import build_asgi_app@@ -193,6 +195,33 @@ def test_basic_auth_cookies_respect_cookie_path(basic_auth_client): assert 'Path=/app' in cookies[name].split('; '), name +def test_basic_auth_cookies_secure_behind_tls_proxy(auth_apps):+ asgi = auth_apps(basic_auth=PASSWORD, use_xheaders=True)+ with TestClient(asgi) as client:+ r = client.post(+ '/login', data={'username': 'user', 'password': PASSWORD},+ headers={'X-Forwarded-Proto': 'https'}, follow_redirects=False+ )+ assert 'Secure' in set_cookies(r)['user'].split('; ')+++def test_autoload_js_from_disallowed_origin_hides_user(basic_auth_client):+ users = []++ def app():+ users.append(getattr(state.curdoc.session_context.request, 'user', None))+ return Markdown('# Test app')++ with basic_auth_client({'/app': app}) as client:+ login(client)+ for headers in ({'Sec-Fetch-Site': 'same-origin'}, {'Origin': 'http://evil.example'}):+ r = client.get(+ '/app/autoload.js', params={'bokeh-autoload-element': 'x'}, headers=headers+ )+ assert r.status_code == 200+ assert users == ['user', None]++ OFFSITE_NEXT_URLS = [ 'https://evil.com', '//evil.com', '///evil.com', '////evil.com', ' ///evil.com', '/\\evil.com', '/\t//evil.com',@@ -619,6 +648,42 @@ def test_oauth_cookie_attributes(oauth_client, auth_apps, scheme): assert ('Secure' in attributes) == (scheme == 'https'), name +class StubCodeChallengeLoginHandler(CodeChallengeLoginHandler):++ _OAUTH_AUTHORIZE_URL = 'https://auth.example.com/authorize'+ _USER_KEY = 'email'++ code_verifiers: t.ClassVar[list[str]] = []++ async def get_authenticated_user(self, redirect_uri, client_id, state, code=None):+ self.code_verifiers.append(self.get_code_cookie())+ return OAuthLoginHandler.set_auth_cookies(self, {'email': OAUTH_USER}, 'access-token')+++def test_code_challenge_flow_with_cookie_path(auth_apps):+ AUTH_PROVIDERS['stub_pkce'] = StubCodeChallengeLoginHandler+ provider_param = config.param.objects(False)['_oauth_provider']+ provider_param.objects = list(AUTH_PROVIDERS)+ StubCodeChallengeLoginHandler.code_verifiers.clear()+ try:+ asgi = auth_apps(oauth_provider='stub_pkce', oauth_key='client-id', cookie_path='/app')+ with TestClient(asgi) as client:+ r = client.get('/login?next=%2Fapp', follow_redirects=False)+ assert 'Path=/' in set_cookies(r)['panel-oauth-code'].split('; ')+ params = parse_qs(urlparse(r.headers['location']).query)+ r = client.get(+ f'/login?code=authorization-code&state={params["state"][0]}',+ follow_redirects=False+ )+ assert r.status_code == 302+ assert client.get('/app').status_code == 200+ finally:+ del AUTH_PROVIDERS['stub_pkce']+ provider_param.objects = list(AUTH_PROVIDERS)+ assert len(StubCodeChallengeLoginHandler.code_verifiers) == 1+ assert StubCodeChallengeLoginHandler.code_verifiers[0]++ def test_oauth_refreshes_expired_access_token(oauth_client): with oauth_client(oauth_refresh_tokens=True) as client: oauth_login(client)panel/tests/test_server.py91 + / 36 −
@@ -688,36 +688,56 @@ def test_autoload_js(port): ({'Sec-Fetch-Site': 'none'}, True), ({'Origin': TRUSTED, 'Sec-Fetch-Site': 'cross-site'}, True), ({'Sec-Fetch-Site': 'cross-site', 'Referer': f'{TRUSTED}/page'}, True),+ ({'Referer': f'{TRUSTED}/page'}, True), ({'Origin': EVIL, 'Sec-Fetch-Site': 'cross-site'}, False), ({'Origin': EVIL}, False), ({'Origin': 'null', 'Sec-Fetch-Site': 'cross-site'}, False), ({'Sec-Fetch-Site': 'cross-site', 'Referer': f'{EVIL}/page'}, False),+ # Browsers omit Sec-Fetch-Site for plain http servers+ ({'Referer': f'{EVIL}/page'}, False), ({'Sec-Fetch-Site': 'cross-site'}, False), ({'Sec-Fetch-Site': 'same-site', 'Referer': 'http://sub.trusted.example/'}, False),+ ({'Origin': 'http://[', 'Sec-Fetch-Site': 'cross-site'}, False),+ ({'Referer': 'http://['}, False),+ ({'Origin': 'http://trusted.example@evil.example'}, False),+ ({'Origin': 'http://evil.example@trusted.example'}, False),+ ({'Origin': 'ftp://trusted.example'}, False),+]++# Cases depending on the host the request was made to, i.e. localhost:5006+SAME_HOST_CASES = [+ ({'Origin': 'http://localhost:5006', 'Sec-Fetch-Site': 'same-site'}, False),+ ({'Origin': 'http://localhost:5006'}, True),+ ({'Referer': 'http://localhost:5006/page'}, True),+ ({'Origin': 'https://app.example', 'host': 'app.example:443'}, True),+ ({'Origin': 'http://trusted\t.example'}, False),+ # A sandboxed iframe on this host is a cross-site context+ ({'Sec-Fetch-Site': 'cross-site', 'Referer': 'http://localhost:5006/page'}, False), ] -@pytest.mark.parametrize('headers, allowed', AUTOLOAD_CREDENTIAL_CASES)+@pytest.mark.parametrize('headers, allowed', AUTOLOAD_CREDENTIAL_CASES + SAME_HOST_CASES) def test_credentials_allowed(headers, allowed): from types import SimpleNamespace from bokeh.server.request import Headers from panel.io.server import credentials_allowed - request = SimpleNamespace(headers=Headers(headers), host='localhost:5006')+ headers = dict(headers)+ host = headers.pop('host', 'localhost:5006')+ request = SimpleNamespace(headers=Headers(headers), host=host) assert credentials_allowed(request, ['trusted.example:80']) is allowed -def test_credentials_allowed_same_host_origin():- from types import SimpleNamespace-- from bokeh.server.request import Headers-- from panel.io.server import credentials_allowed+@pytest.mark.parametrize('origins, expected', [+ (['trusted.example:80', '*', '*:5006', '*.example.com:80'], ['trusted.example:80', '*.example.com:80']),+ (['*'], []),+])+def test_credential_allowlist_ignores_catch_all(origins, expected):+ from panel.io.server import credential_allowlist - headers = Headers({'Origin': 'http://localhost:5006', 'Sec-Fetch-Site': 'cross-site'})- assert credentials_allowed(SimpleNamespace(headers=headers, host='localhost:5006'), [])+ assert credential_allowlist(origins) == expected def _token_payload(response):@@ -727,33 +747,59 @@ def _token_payload(response): return get_token_payload(re.search(r'"token":"([^"]+)"', response.text).group(1)) -def test_autoload_js_credentials_follow_websocket_allowlist(port, server_implementation):- serve_and_wait(- {'app': Markdown('# App')}, port=port, basic_auth="secret-password",- cookie_secret="cookie-secret", websocket_origin=['trusted.example']- )+def _login(port): session = requests.Session() r = session.post( f"http://localhost:{port}/login", data={'username': 'alice', 'password': 'secret-password'} ) assert r.status_code == 200+ return session+++def test_autoload_js_credentials_follow_websocket_allowlist(port, server_implementation):+ from panel.io.server import _is_public_header++ serve_and_wait(+ {'app': Markdown('# App')}, port=port, basic_auth="secret-password",+ cookie_secret="cookie-secret", websocket_origin=['trusted.example']+ )+ session = _login(port) url = f"http://localhost:{port}/app/autoload.js?{_autoload_args(port, 'app')}" credentials = { 'Authorization': 'Bearer token', 'X-Forwarded-User': 'alice',- 'X-Forwarded-For': '10.0.0.1',+ 'X-Amzn-Oidc-Accesstoken': 'token', 'X-Goog-Iap-Jwt-Assertion': 'token',+ 'Remote-User': 'alice', 'X-Api-Key': 'key', 'X-Forwarded-For': '10.0.0.1', }- for headers, allowed in AUTOLOAD_CREDENTIAL_CASES:- r = session.get(url, headers={**headers, **credentials}, timeout=10)- assert r.headers['Cache-Control'] == 'no-store'- payload = _token_payload(r)- assert ('user' in payload['cookies']) is allowed, headers- if not allowed:- assert payload['cookies'] == {}, headers- token_headers = {h.lower() for h in payload['headers']}- assert not {'authorization', 'cookie', 'x-forwarded-user'} & token_headers, headers- assert 'x-forwarded-for' in token_headers, headers- assert 'user_data' not in payload+ state._oauth_user_overrides['alice'] = {'access_token': 'token'}+ try:+ for headers, allowed in AUTOLOAD_CREDENTIAL_CASES:+ r = session.get(url, headers={**headers, **credentials}, timeout=10)+ assert r.headers['Cache-Control'] == 'no-store'+ payload = _token_payload(r)+ assert ('user' in payload['cookies']) is allowed, headers+ assert ('user_data' in payload) is allowed, headers+ if not allowed:+ assert payload['cookies'] == {}, headers+ assert all(_is_public_header(h) for h in payload['headers']), headers+ assert 'x-forwarded-for' in {h.lower() for h in payload['headers']}, headers+ finally:+ state._oauth_user_overrides.pop('alice', None)+++def test_autoload_js_wildcard_allowlist_does_not_grant_credentials(port, server_implementation):+ serve_and_wait(+ {'app': Markdown('# App')}, port=port, basic_auth="secret-password",+ cookie_secret="cookie-secret", websocket_origin=['*']+ )+ session = _login(port)+ url = f"http://localhost:{port}/app/autoload.js?{_autoload_args(port, 'app')}"+ r = session.get(url, headers={'Origin': EVIL, 'Sec-Fetch-Site': 'cross-site'}, timeout=10)+ assert r.headers['Access-Control-Allow-Origin'] == '*'+ assert 'Access-Control-Allow-Credentials' not in r.headers+ assert _token_payload(r)['cookies'] == {}+ r = session.get(url, headers={'Sec-Fetch-Site': 'same-origin'}, timeout=10)+ assert 'user' in _token_payload(r)['cookies'] def test_autoload_js_cors_headers(port, server_implementation):@@ -762,9 +808,12 @@ def test_autoload_js_cors_headers(port, server_implementation): ) url = f"http://localhost:{port}/app/autoload.js?{_autoload_args(port, 'app')}" - r = requests.get(url, headers={'Origin': EVIL}, timeout=10)- assert r.headers['Access-Control-Allow-Origin'] == '*'- assert 'Access-Control-Allow-Credentials' not in r.headers+ for headers in ({}, {'Origin': EVIL}, {'Origin': 'http://['}):+ r = requests.get(url, headers=headers, timeout=10)+ assert r.status_code == 200, headers+ assert r.headers['Access-Control-Allow-Origin'] == '*'+ assert 'Access-Control-Allow-Credentials' not in r.headers+ assert 'Origin' in r.headers['Vary'] r = requests.get(url, headers={'Origin': TRUSTED}, timeout=10) assert r.headers['Access-Control-Allow-Origin'] == TRUSTED@@ -779,15 +828,21 @@ def test_autoload_js_cors_headers(port, server_implementation): assert r.headers['Access-Control-Allow-Origin'] == TRUSTED assert r.headers['Access-Control-Allow-Credentials'] == 'true' assert r.headers['Access-Control-Allow-Headers'] == 'x-custom'+ assert r.headers['Cache-Control'] == 'no-store'+ assert 'Origin' in r.headers['Vary'] - r = requests.options(url, headers={- 'Origin': EVIL, 'Access-Control-Request-Method': 'GET'- }, timeout=10)- assert r.headers['Access-Control-Allow-Origin'] == '*'- assert 'Access-Control-Allow-Credentials' not in r.headers+ for origin in (EVIL, 'http://['):+ r = requests.options(url, headers={+ 'Origin': origin, 'Access-Control-Request-Method': 'GET'+ }, timeout=10)+ assert r.status_code in (200, 204), origin+ assert r.headers['Access-Control-Allow-Origin'] == '*'+ assert 'Access-Control-Allow-Credentials' not in r.headers+ assert r.headers['Cache-Control'] == 'no-store'+ assert 'Origin' in r.headers['Vary'] -def test_auth_cookies_secure_behind_tls_proxy(port):+def test_auth_cookies_secure_behind_tls_proxy(port, server_implementation): serve_and_wait( {'app': Markdown('# App')}, port=port, basic_auth="secret-password", cookie_secret="cookie-secret", use_xheaders=True