Ejemplo n.º 1
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.º 2
0
def mock_livestatus(with_context=False):
    live = MockLiveStatusConnection()

    env = EnvironBuilder().get_environ()
    req = http.Request(env)

    app_context: ContextManager
    req_context: ContextManager
    if with_context:
        app_context = AppContext(None)
        req_context = RequestContext(
            req=req,
            display_options=DisplayOptions(),
            prefix_logs_with_url=False,
        )
    else:
        app_context = contextlib.nullcontext()
        req_context = contextlib.nullcontext()

    with app_context, req_context, \
         mock.patch("cmk.gui.sites._get_enabled_and_disabled_sites",
                    new=live.enabled_and_disabled_sites), \
         mock.patch("livestatus.MultiSiteConnection.set_prepend_site",
                    new=live.set_prepend_site), \
         mock.patch("livestatus.MultiSiteConnection.expect_query",
                    new=live.expect_query, create=True), \
         mock.patch("livestatus.SingleSiteConnection._create_socket", new=live.create_socket), \
         mock.patch.dict(os.environ, {'OMD_ROOT': '/', 'OMD_SITE': 'NO_SITE'}):

        yield live
Ejemplo n.º 3
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.º 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 __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.º 6
0
def mock_livestatus(with_context=False):
    def enabled_and_disabled_sites(_user):
        return {'NO_SITE': {'socket': 'unix:'}}, {}

    live = MockLiveStatusConnection()

    env = EnvironBuilder().get_environ()
    req = http.Request(env)

    app_context: ContextManager
    req_context: ContextManager
    if with_context:
        app_context = AppContext(None)
        req_context = RequestContext(req=req)
    else:
        app_context = contextlib.nullcontext()
        req_context = contextlib.nullcontext()

    with app_context, req_context, \
         mock.patch("cmk.gui.sites._get_enabled_and_disabled_sites",
                    new=enabled_and_disabled_sites), \
         mock.patch("livestatus.MultiSiteConnection.set_prepend_site",
                    new=live.set_prepend_site), \
         mock.patch("livestatus.MultiSiteConnection.expect_query",
                    new=live.expect_query, create=True), \
         mock.patch("livestatus.SingleSiteConnection._create_socket", new=live.create_socket), \
         mock.patch.dict(os.environ, {'OMD_ROOT': '/', 'OMD_SITE': 'NO_SITE'}):

        yield live
Ejemplo n.º 7
0
def test_request_del_vars_from_query_string():
    r = http.Request(create_environ(
        method="GET",
        query_string="a=1&b=2",
    ))
    r.del_var_from_env("a")
    assert r.query_string == b"b=2"
Ejemplo n.º 8
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.º 9
0
def mock_livestatus(
    with_context: bool = False,
    with_html: bool = False
) -> Generator[MockLiveStatusConnection, None, None]:
    live = MockLiveStatusConnection()

    env = EnvironBuilder().get_environ()
    req = http.Request(env)
    resp = http.Response()

    app_context: ContextManager
    req_context: ContextManager
    if with_html:
        html_obj = None
    else:
        html_obj = HTMLGenerator(
            request=req,
            output_funnel=OutputFunnel(resp),
            output_format="html",
            mobile=is_mobile(req, resp),
        )
    if with_context:
        app_context = AppContext(None, stack=app_stack())
        req_context = RequestContext(
            html_obj=html_obj,
            req=req,
            resp=resp,
            funnel=OutputFunnel(resp),
            config_obj=make_config_object(get_default_config()),
            user=LoggedInNobody(),
            display_options=DisplayOptions(),
            prefix_logs_with_url=False,
            stack=request_stack(),
            url_filter=PrependURLFilter(),
        )
    else:
        app_context = contextlib.nullcontext()
        req_context = contextlib.nullcontext()

    with app_context, req_context, mock.patch(
            "cmk.gui.sites._get_enabled_and_disabled_sites",
            new=live.enabled_and_disabled_sites), mock.patch(
                "livestatus.MultiSiteConnection.expect_query",
                new=live.expect_query,
                create=True), mock.patch(
                    "livestatus.SingleSiteConnection._create_socket",
                    new=live.create_socket), mock.patch.dict(
                        os.environ, {
                            "OMD_ROOT": "/",
                            "OMD_SITE": "NO_SITE"
                        }):

        # We don't want to be polluted by other tests.
        omd_site.cache_clear()
        yield live
        # We don't want to pollute other tests.
        omd_site.cache_clear()
Ejemplo n.º 10
0
def test_http_request_allowed_vars():
    environ = dict(create_environ(
        method="POST",
        content_type="application/x-www-form-urlencoded",
        input_stream=io.BytesIO("asd=x&_Y21rYWRtaW4%3D=aaa")),
                   REQUEST_URI='')
    req = http.Request(environ)
    assert req.var("asd") == "x"
    assert req.var("_Y21rYWRtaW4=") == "aaa"
Ejemplo n.º 11
0
def fixture_current_cookie(with_user, session_id):
    user_id = with_user[0]
    cookie_name = login.auth_cookie_name()
    cookie_value = login._auth_cookie_value(user_id, session_id)

    environ = dict(create_environ(), HTTP_COOKIE=f"{cookie_name}={cookie_value}".encode("utf-8"))

    with AppContext(DummyApplication(environ, None)), \
            RequestContext(htmllib.html(http.Request(environ))):
        yield cookie_name
Ejemplo n.º 12
0
def fixture_pre_20_cookie():
    environ = dict(
        create_environ(),
        HTTP_COOKIE=
        u"xyz=123; auth_stable=lärs:1534272374.61:1f59cac3fcd5bcc389e4f8397bed315b; abc=123".encode(
            "utf-8"))

    with AppContext(DummyApplication(environ, None)), \
            RequestContext(htmllib.html(http.Request(environ))):
        yield "auth_stable"
Ejemplo n.º 13
0
def test_request_del_vars_from_post_body():
    r = http.Request(
        create_environ(
            method="GET",
            query_string="a=1&b=2",
            content_type="application/x-www-form-urlencoded",
            input_stream=io.BytesIO(b"a=2&c=3"),
        ))
    r.del_var_from_env("a")
    assert len(r.form) == 1
    assert r.query_string == b"b=2"
Ejemplo n.º 14
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.º 15
0
def test_pre_16_format_cookie_handling(monkeypatch):
    environ = dict(
        create_environ(),
        HTTP_COOKIE=
        "xyz=123; auth_stable=lärs:1534272374.61:1f59cac3fcd5bcc389e4f8397bed315b; abc=123")
    request = http.Request(environ)

    assert isinstance(request.cookie("auth_stable"), bytes)
    assert request.cookie("auth_stable") == "lärs:1534272374.61:1f59cac3fcd5bcc389e4f8397bed315b"

    assert request.has_cookie("xyz")
    assert request.has_cookie("abc")
Ejemplo n.º 16
0
def test_web_server_auth_session(user_id):
    environ = dict(create_environ(), REMOTE_USER=str(user_id))

    with AppContext(DummyApplication(environ, None)), \
            RequestContext(htmllib.html(http.Request(environ))):

        assert user.id is None
        with login.authenticate(request) as authenticated:
            assert authenticated is True
            assert user.id == user_id
            assert session.user_id == user.id
        assert user.id is None
Ejemplo n.º 17
0
def mock_livestatus(
    with_context: bool = False,
    with_html: bool = False
) -> Generator[MockLiveStatusConnection, None, None]:
    live = MockLiveStatusConnection()

    env = EnvironBuilder().get_environ()
    req = http.Request(env)
    resp = http.Response()

    app_context: ContextManager
    req_context: ContextManager
    if with_html:
        html_obj = None
    else:
        html_obj = html(
            request=req,
            response=resp,
            output_funnel=OutputFunnel(resp),
            output_format="html",
        )
    if with_context:
        app_context = AppContext(None)
        req_context = RequestContext(
            html_obj=html_obj,
            req=req,
            resp=resp,
            funnel=OutputFunnel(resp),
            display_options=DisplayOptions(),
            prefix_logs_with_url=False,
        )
    else:
        app_context = contextlib.nullcontext()
        req_context = contextlib.nullcontext()

    with app_context, req_context, \
         mock.patch("cmk.gui.sites._get_enabled_and_disabled_sites",
                    new=live.enabled_and_disabled_sites), \
         mock.patch("livestatus.MultiSiteConnection.set_prepend_site",
                    new=live.set_prepend_site), \
         mock.patch("livestatus.MultiSiteConnection.expect_query",
                    new=live.expect_query, create=True), \
         mock.patch("livestatus.SingleSiteConnection._create_socket", new=live.create_socket), \
         mock.patch.dict(os.environ, {'OMD_ROOT': '/', 'OMD_SITE': 'NO_SITE'}):

        # We don't want to be polluted by other tests.
        version.omd_site.cache_clear()
        yield live
        # We don't want to pollute other tests.
        version.omd_site.cache_clear()
Ejemplo n.º 18
0
def test_flash(user_id):
    environ = create_environ()
    # Execute the first request flash some message
    with AppContext(DummyApplication(environ, None)), \
            RequestContext(htmllib.html(http.Request(environ))) as request, \
            login.UserContext(user_id):
        session_id = on_succeeded_login(user_id)  # Create and activate session
        assert request.session is not None

        flash("abc")
        assert session.session_info.flashes == ["abc"]

    # Now create the second request to get the previously flashed message
    with AppContext(DummyApplication(environ, None)), \
            RequestContext(htmllib.html(http.Request(environ))), \
            login.UserContext(user_id):
        on_access(user_id, session_id)
        assert request.session is not None
        assert session.session_info.flashes == ["abc"]

        # Get the flashed messages removes the messages from the session
        # and subsequent calls to get_flashed_messages return the messages
        # over and over.
        assert get_flashed_messages() == [HTML("abc")]
        assert get_flashed_messages() == [HTML("abc")]
        assert session.session_info.flashes == []

    # Now create the third request that should not have access to the flashed messages since the
    # second one consumed them.
    with AppContext(DummyApplication(environ, None)), \
            RequestContext(htmllib.html(http.Request(environ))), \
            login.UserContext(user_id):
        on_access(user_id, session_id)
        assert request.session is not None
        assert session.session_info.flashes == []
        assert get_flashed_messages() == []
Ejemplo n.º 19
0
def test_http_request_allowed_vars():
    environ = dict(create_environ(
        method="POST",
        content_type="application/x-www-form-urlencoded",
        input_stream=io.BytesIO("asd=x&_Y21rYWRtaW4%3D=aaa&foo%3ABAR_BAZ=abc")),
                   REQUEST_URI='')
    req = http.Request(environ)
    assert req.var("asd") == "x"
    assert req.var("_Y21rYWRtaW4=") == "aaa"
    assert req.var("foo:BAR_BAZ") == "abc"
    assert req.var("foo:BAR_BAZ", "default") == "abc"

    assert req.var("not_present") is None
    assert req.var("not_present", "default") == "default"

    req.set_var("test", "foo")
    assert req.var("test") == "foo"
    req.del_var("test")
    assert req.var("test") is None
    assert req.var("test", "default") == "default"
Ejemplo n.º 20
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     resp = http.Response(is_secure=req.is_secure)
     with AppContext(app), RequestContext(req=req, resp=resp):
         return app(environ, start_response)
Ejemplo n.º 21
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)
Ejemplo n.º 22
0
def tm():
    request = http.Request({"wsgi.input": "", "SCRIPT_NAME": ""})
    return TransactionManager(request, MockLoggedInUser())
Ejemplo n.º 23
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     with AppContext(app), RequestContext(req=req):
         return app(environ, start_response)
Ejemplo n.º 24
0
def tm():
    request = http.Request({"wsgi.input": "", "SCRIPT_NAME": ""})
    return htmllib.TransactionManager(request)