Repository: ray-project/ray
File: python/ray/dashboard/optional_utils.py (Python)

Code before:


def init_ray_and_catch_exceptions() -> Callable:
    """Decorator to be used on methods that require being connected to Ray."""

    def decorator_factory(f: Callable) -> Callable:
        @functools.wraps(f)
        async def decorator(
            self: Union[DashboardAgentModule, DashboardHeadModule], *args, **kwargs
        ):
            try:
                if not ray.is_initialized():
                    try:
                        address = self.gcs_address
                        logger.info(f"Connecting to ray with address={address}")
                        # Set the gcs rpc timeout to shorter
                        os.environ["RAY_gcs_server_request_timeout_seconds"] = str(
                            dashboard_consts.GCS_RPC_TIMEOUT_SECONDS
                        )
                        # Init ray without logging to driver
                        # to avoid infinite logging issue.
                        ray.init(
                            address=address,
                            log_to_driver=False,
                            configure_logging=False,
                            namespace=RAY_INTERNAL_DASHBOARD_NAMESPACE,
                            _skip_env_hook=True,
                        )
                    except Exception as e:
                        ray.shutdown()
                        raise e from None
                return await f(self, *args, **kwargs)
            except Exception as e:
                logger.exception(f"Unexpected error in handler: {e}")
                return Response(
                    text=traceback.format_exc(),
                    status=aiohttp.web.HTTPInternalServerError.status_code,
                )

        return decorator

    return decorator_factory


Review comment (suggestion):
```suggestion
        if not allowed_methods:
            return aiohttp_module.web.Response(
                    status=403, text="Browser requests not allowed."
                )

        if request.method not in allowed_methods:
            return aiohttp_module.web.Response(
                status=405, text="Method Not Allowed for browser traffic."
            )
```

Code after:

    Returns:
        An aiohttp middleware function
    """
    allowed_methods = allowed_methods or set()

    @aiohttp_module.web.middleware
    async def browser_request_middleware(request, handler):
        if not is_browser_request(request):
            return await handler(request)

        # Allow whitelisted paths to bypass the check
        if allowed_paths and request.path in allowed_paths:
            return await handler(request)

        if request.method not in allowed_methods:
            # 403 if no methods allowed (all browsers blocked)
            # 405 if some methods allowed but not this one
            if allowed_methods:
                return aiohttp_module.web.Response(
                    status=405, text="Method Not Allowed for browser traffic."
                )
            else:
                return aiohttp_module.web.Response(
                    status=403, text="Browser requests not allowed."
                )

        return await handler(request)

    return browser_request_middleware


def init_ray_and_catch_exceptions() -> Callable:
    """Decorator to be used on methods that require being connected to Ray."""

    def decorator_factory(f: Callable) -> Callable:
        @functools.wraps(f)
        async def decorator(
            self: Union[DashboardAgentModule, DashboardHeadModule], *args, **kwargs
        ):
            try:
                if not ray.is_initialized():
                    try:
                        address = self.gcs_address
                        logger.info(f"Connecting to ray with address={address}")
                        # Set the gcs rpc timeout to shorter
                        os.environ["RAY_gcs_server_request_timeout_seconds"] = str(
                            dashboard_consts.GCS_RPC_TIMEOUT_SECONDS
                        )
                        # Init ray without logging to driver
                        # to avoid infinite logging issue.