Ejemplo n.º 1
0
    def __call__(self, environ: WSGIEnvironment,
                 start_response: StartResponse) -> WSGIResponse:
        req = http.Request(environ)

        output_format = get_output_format(
            req.get_ascii_input_mandatory("output_format", "html").lower())
        mime_type = get_mime_type_from_output_format(output_format)

        resp = Response(headers=default_response_headers(req),
                        mimetype=mime_type)
        funnel = OutputFunnel(resp)

        timeout_manager = TimeoutManager()
        timeout_manager.enable_timeout(req.request_timeout)

        theme = Theme()
        config_obj = config_module.make_config_object(
            config_module.get_default_config())

        with AppContext(self), RequestContext(
                req=req,
                resp=resp,
                funnel=funnel,
                config_obj=config_obj,
                user=LoggedInNobody(),
                html_obj=htmllib.html(req, resp, funnel, output_format),
                timeout_manager=timeout_manager,
                display_options=DisplayOptions(),
                theme=theme,
        ), patch_json(json):
            config_module.initialize()
            theme.from_config(config.ui_theme)
            return self.wsgi_app(environ, start_response)
Ejemplo n.º 2
0
 def __call__(self, environ, start_response):
     req = http.Request(environ)
     with AppContext(self), RequestContext(req=req,
                                           html_obj=htmllib.html(req)):
         config.initialize()
         html.init_modes()
         return self.wsgi_app(environ, start_response)
Ejemplo n.º 3
0
    def __call__(self, environ, start_response):
        req = http.Request(environ)

        output_format = get_output_format(
            req.get_ascii_input_mandatory("output_format", "html").lower())
        mime_type = get_mime_type_from_output_format(output_format)

        resp = Response(headers=default_response_headers(req),
                        mimetype=mime_type)
        funnel = OutputFunnel(resp)

        timeout_manager = TimeoutManager()
        timeout_manager.enable_timeout(req.request_timeout)

        theme = Theme()

        with AppContext(self), RequestContext(
                req=req,
                resp=resp,
                funnel=funnel,
                html_obj=htmllib.html(req, resp, funnel, output_format),
                timeout_manager=timeout_manager,
                display_options=DisplayOptions(),
                theme=theme,
        ), patch_json(json):
            config.initialize()
            theme.from_config(config.ui_theme, config.theme_choices())
            return self.wsgi_app(environ, start_response)
Ejemplo n.º 4
0
 def __call__(self, environ, start_response) -> Response:
     req = http.Request(environ)
     with AppContext(self), RequestContext(req=req,
                                           display_options=DisplayOptions(),
                                           html_obj=htmllib.html(req)):
         config.initialize()
         return _process_request(environ, start_response)
Ejemplo n.º 5
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     with AppContext(app), \
             RequestContext(req=req, display_options=DisplayOptions()), \
             cmk.utils.store.cleanup_locks(), \
             sites.cleanup_connections():
         config.initialize()
         return app(environ, start_response)
Ejemplo n.º 6
0
    def with_context(environ, start_response):
        req = cmk.gui.http.Request(environ)
        resp = cmk.gui.http.Response(is_secure=req.is_secure)

        with AppContext(app), RequestContext(cmk.gui.htmllib.html(req, resp)):
            config.initialize()
            html.init_modes()

            return app(environ, start_response)
Ejemplo n.º 7
0
def etags_off_fixture():
    def _set_config():
        config.rest_api_etag_locking = False

    config.register_post_config_load_hook(_set_config)
    config.initialize()
    yield
    config._post_config_load_hooks.remove(_set_config)
    config.initialize()
Ejemplo n.º 8
0
    def _process_request(self, request, response):  # pylint: disable=too-many-branches
        try:
            config.initialize()
            html.init_modes()

            # Make sure all plugins are available as early as possible. At least
            # we need the plugins (i.e. the permissions declared in these) at the
            # time before the first login for generating auth.php.
            _load_all_plugins()

            page_handler = get_and_wrap_page(request, html.myfile)
            page_handler()
            # If page_handler didn't raise we assume everything is OK.
            response.status_code = httplib.OK

        except HTTPRedirect as e:
            response.status_code = e.status
            response.headers["Location"] = e.url

        except FinalizeRequest as e:
            response.status_code = e.status

        except livestatus.MKLivestatusNotFoundError as e:
            _render_exception(e, title=_("Data not found"))

        except MKUserError as e:
            _render_exception(e, title=_("Invalid user Input"))

        except MKAuthException as e:
            _render_exception(e, title=_("Permission denied"))

        except livestatus.MKLivestatusException as e:
            _render_exception(e, title=_("Livestatus problem"))
            response.status_code = httplib.BAD_GATEWAY

        except MKUnauthenticatedException as e:
            _render_exception(e, title=_("Not authenticated"))
            response.status_code = httplib.UNAUTHORIZED

        except MKConfigError as e:
            _render_exception(e, title=_("Configuration error"))
            logger.error("MKConfigError: %s", e)

        except MKGeneralException as e:
            _render_exception(e, title=_("General error"))
            logger.error("MKGeneralException: %s", e)

        except Exception:
            crash = crash_reporting.GUICrashReport.from_exception()
            crash_reporting.CrashReportStore().save(crash)

            logger.exception("Unhandled exception (Crash-ID: %s)",
                             crash.ident_to_text())
            crash_reporting.show_crash_dump_message(crash, _plain_error(),
                                                    _fail_silently())
Ejemplo n.º 9
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     resp = http.Response()
     with AppContext(app), \
             RequestContext(req=req, resp=resp, funnel=OutputFunnel(resp),
                            config_obj=config.make_config_object(config.get_default_config()),
                            display_options=DisplayOptions()), \
             cmk.utils.store.cleanup_locks(), \
             sites.cleanup_connections():
         config.initialize()
         return app(environ, start_response)
Ejemplo n.º 10
0
def load_config(register_builtin_html):
    old_root_log_level = cmk.utils.log.logger.getEffectiveLevel()
    config.initialize()
    yield
    cmk.utils.log.logger.setLevel(old_root_log_level)
Ejemplo n.º 11
0
def load_config(request_context: None) -> Iterator[None]:
    old_root_log_level = cmk.utils.log.logger.getEffectiveLevel()
    config_module.initialize()
    yield
    cmk.utils.log.logger.setLevel(old_root_log_level)
Ejemplo n.º 12
0
    def _wsgi_app(self, environ: WSGIEnvironment,
                  start_response: StartResponse) -> WSGIResponse:
        urls = self.url_map.bind_to_environ(environ)
        endpoint: Optional[Endpoint] = None
        try:
            result: Tuple[str, Mapping[str,
                                       Any]] = urls.match(return_rule=False)
            endpoint_ident, matched_path_args = result  # pylint: disable=unpacking-non-sequence
            wsgi_app = self.endpoints[endpoint_ident]
            if isinstance(wsgi_app, Authenticate):
                endpoint = wsgi_app.endpoint

            # Remove _path again (see Submount above), so the validators don't go crazy.
            path_args = {
                key: value
                for key, value in matched_path_args.items() if key != "_path"
            }

            # This is an implicit dependency, as we only know the args at runtime, but the
            # function at setup-time.
            environ[ARGS_KEY] = path_args

            req = Request(environ)
            resp = Response()
            with AppContext(self, stack=app_stack()), RequestContext(
                    req=req,
                    resp=resp,
                    funnel=OutputFunnel(resp),
                    config_obj=config.make_config_object(
                        config.get_default_config()),
                    endpoint=endpoint,
                    user=LoggedInNobody(),
                    display_options=DisplayOptions(),
                    stack=request_stack(),
                    url_filter=PrependURLFilter(),
            ), cmk.utils.store.cleanup_locks(), sites.cleanup_connections():
                config.initialize()
                load_dynamic_permissions()
                return wsgi_app(environ, start_response)
        except ProblemException as exc:
            return exc(environ, start_response)
        except HTTPException as exc:
            # We don't want to log explicit HTTPExceptions as these are intentional.
            assert isinstance(exc.code, int)
            return problem(
                status=exc.code,
                title=http.client.responses[exc.code],
                detail=str(exc),
            )(environ, start_response)
        except MKException as exc:
            if self.debug:
                raise

            return problem(
                status=EXCEPTION_STATUS.get(type(exc), 500),
                title="An exception occurred.",
                detail=str(exc),
            )(environ, start_response)
        except Exception as exc:
            crash = APICrashReport.from_exception()
            crash_reporting.CrashReportStore().save(crash)
            logger.exception("Unhandled exception (Crash-ID: %s)",
                             crash.ident_to_text())
            if self.debug:
                raise

            request = Request(environ)
            site = config.omd_site()
            query_string = urllib.parse.urlencode([
                ("crash_id", (crash.ident_to_text())),
                ("site", site),
            ])
            crash_url = f"{request.host_url}{site}/check_mk/crash.py?{query_string}"
            crash_details = {
                "crash_id": (crash.ident_to_text()),
                "crash_report": {
                    "href": crash_url,
                    "method": "get",
                    "rel": "cmk/crash-report",
                    "type": "text/html",
                },
            }
            if user.may("general.see_crash_reports"):
                crash_details["stack_trace"] = traceback.format_exc().split(
                    "\n")

            return problem(
                status=500,
                title=http.client.responses[500],
                detail=str(exc),
                ext=crash_details,
            )(environ, start_response)
Ejemplo n.º 13
0
def _process_request(environ, start_response):  # pylint: disable=too-many-branches
    try:
        config.initialize()
        html.init_modes()

        # Make sure all plugins are available as early as possible. At least
        # we need the plugins (i.e. the permissions declared in these) at the
        # time before the first login for generating auth.php.
        _load_all_plugins()

        page_handler = get_and_wrap_page(html.myfile)
        response = page_handler()
        # If page_handler didn't raise we assume everything is OK.
        response.status_code = http_client.OK
    except HTTPRedirect as e:
        # This can't be a new Response as it can have already cookies set/deleted by the pages.
        # We can't return the response because the Exception has been raised instead.
        # TODO: Remove all HTTPRedirect exceptions from all pages. Making the Exception a subclass
        #       of Response may also work as it can then be directly returned from here.
        response = html.response
        response.status_code = e.status
        response.headers["Location"] = e.url

    except FinalizeRequest as e:
        # This doesn't seem to serve much purpose anymore.
        # TODO: Remove all FinalizeRequest exceptions from all pages and replace it with a `return`.
        #       It may be necessary to rewire the control-flow a bit as this exception could have
        #       been used to short-circuit some code and jump directly to the response. This
        #       needs to be changed as well.
        response = html.response
        response.status_code = e.status

    except livestatus.MKLivestatusNotFoundError as e:
        response = _render_exception(e, title=_("Data not found"))

    except MKUserError as e:
        response = _render_exception(e, title=_("Invalid user Input"))

    except MKAuthException as e:
        response = _render_exception(e, title=_("Permission denied"))

    except livestatus.MKLivestatusException as e:
        response = _render_exception(e, title=_("Livestatus problem"))
        response.status_code = http_client.BAD_GATEWAY

    except MKUnauthenticatedException as e:
        response = _render_exception(e, title=_("Not authenticated"))
        response.status_code = http_client.UNAUTHORIZED

    except MKConfigError as e:
        response = _render_exception(e, title=_("Configuration error"))
        logger.error("MKConfigError: %s", e)

    except MKGeneralException as e:
        response = _render_exception(e, title=_("General error"))
        logger.error("MKGeneralException: %s", e)

    except Exception:
        crash_reporting.handle_exception_as_gui_crash_report(
            _plain_error(), _fail_silently())
        # This needs to be cleaned up.
        response = html.response

    return response(environ, start_response)
Ejemplo n.º 14
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     with AppContext(app), RequestContext(req=req):
         config.initialize()
         return app(environ, start_response)
Ejemplo n.º 15
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     with AppContext(app), RequestContext(req=req,
                                          display_options=DisplayOptions()):
         config.initialize()
         return app(environ, start_response)