Beispiel #1
0
def test_flash_dont_escape_html(user_id, request_context):
    now = datetime.now()
    with login.UserSessionContext(user_id):
        on_succeeded_login(user_id, now)  # Create and activate session

        flash(HTML("<script>aaa</script>"))
        assert get_flashed_messages() == [HTML("<script>aaa</script>")]
Beispiel #2
0
def test_render_help_html(request_context):
    assert html.have_help is False
    assert compare_html(
        html.render_help(HTML("<abc>")),
        HTML('<div style="display:none" class="help"><abc></div>'))
    # NOTE: This seems to be a mypy 0.780 bug.
    assert html.have_help is True  # type: ignore[comparison-overlap]
Beispiel #3
0
def test_flash(user_id):
    # Execute the first request flash some message
    with application_and_request_context(), login.UserSessionContext(user_id):
        session_id = on_succeeded_login(user_id)  # Create and activate session
        assert session is not None

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

    # Now create the second request to get the previously flashed message
    with application_and_request_context(), login.UserSessionContext(user_id):
        on_access(user_id, session_id)
        assert 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 application_and_request_context(), login.UserSessionContext(user_id):
        on_access(user_id, session_id)
        assert session is not None
        assert session.session_info.flashes == []
        assert get_flashed_messages() == []
Beispiel #4
0
 def test_tag_condition(self) -> None:
     assert list(RuleConditionRenderer()._tag_conditions({
         "tag_grp_1": {
             "$or": [
                 "grp_1_tg_1",
                 "grp_1_tg_2",
             ]
         },
         "tag_grp_2": {
             "$nor": [
                 "grp_2_tg_1",
                 "grp_2_tg_2",
             ]
         },
         "tag_grp_3": "grp_3_tg_1",
         "aux_tag_1": {
             "$ne": "aux_tag_1"
         },
     })) == [
         HTML(
             "Host tag: Tag group 1 is <b>Tag 1.1</b> <i>or</i> Host tag: Tag group 1 is <b>Tag 1.2</b>"
         ),
         HTML(
             "Neither Host tag: Tag group 2 is <b>Tag 2.1</b> <i>nor</i> Host tag: Tag group 2 is <b>Tag 2.2</b>"
         ),
         HTML("Host tag: Tag group 3 is <b>Tag 3.1</b>"),
         HTML("Host does not have tag <b>Auxiliary tag 1</b>"),
     ]
Beispiel #5
0
    def _display_log(self, log):
        with table_element(
            css="data wato auditlog audit", limit=None, sortable=False, searchable=False
        ) as table:
            for entry in log:
                table.row()
                table.cell(
                    _("Time"),
                    HTMLWriter.render_nobr(render.date_and_time(float(entry.time))),
                    css=["narrow"],
                )
                user_txt = ("<i>%s</i>" % _("internal")) if entry.user_id == "-" else entry.user_id
                table.cell(_("User"), user_txt, css=["nobreak narrow"])

                table.cell(
                    _("Object type"),
                    entry.object_ref.object_type.name if entry.object_ref else "",
                    css=["narrow"],
                )
                table.cell(_("Object"), render_object_ref(entry.object_ref) or "", css=["narrow"])

                text = HTML(escaping.escape_text(entry.text).replace("\n", "<br>\n"))
                table.cell(_("Summary"), text)

                if self._show_details:
                    diff_text = HTML(
                        escaping.escape_text(entry.diff_text).replace("\n", "<br>\n")
                        if entry.diff_text
                        else ""
                    )
                    table.cell(_("Details"), diff_text)
Beispiel #6
0
def get_wato_folder(row: Dict, how: str, with_links: bool = True) -> Union[str, HTML]:
    filename = row["host_filename"]
    if not filename.startswith("/wato/") or not filename.endswith("/hosts.mk"):
        return ""
    wato_path = filename[6:-9]
    try:
        title_path = get_folder_title_path(wato_path, with_links)
    except MKGeneralException:
        # happens when a path can not be resolved using the local WATO.
        # e.g. when having an independent site with different folder
        # hierarchy added to the GUI.
        # Display the raw path rather than the exception text.
        title_path = wato_path.split("/")
    except Exception as e:
        return "%s" % e

    if how == "plain":
        return title_path[-1]
    if how == "abs":
        return HTML(" / ").join(title_path)
    # We assume that only hosts are show, that are below the current WATO path.
    # If not then better output absolute path then wrong path.
    current_path = request.var("wato_folder")
    if not current_path or not wato_path.startswith(current_path):
        return HTML(" / ").join(title_path)

    depth = current_path.count("/") + 1
    return HTML(" / ").join(title_path[depth:])
Beispiel #7
0
def test_render_help_html(register_builtin_html):
    assert html.have_help is False
    assert compare_html(
        html.render_help(HTML("<abc>")),
        HTML("<div style=\"display:none\" class=\"help\"><abc></div>"))
    # NOTE: This seems to be a mypy 0.780 bug.
    assert html.have_help is True  # type: ignore[comparison-overlap]
Beispiel #8
0
def test_render_help_empty(request_context):
    assert html.have_help is False
    assert html.render_help(None) == HTML("")
    assert isinstance(html.render_help(None), HTML)
    assert html.have_help is False

    assert html.render_help("") == HTML("")
    assert isinstance(html.render_help(""), HTML)
    assert html.render_help("    ") == HTML("")
    assert isinstance(html.render_help("    "), HTML)
Beispiel #9
0
def test_render_help_empty(register_builtin_html):
    assert html.have_help is False
    assert html.render_help(None) == HTML("")
    assert isinstance(html.render_help(None), HTML)
    assert html.have_help is False

    assert html.render_help("") == HTML("")
    assert isinstance(html.render_help(""), HTML)
    assert html.render_help("    ") == HTML("")
    assert isinstance(html.render_help("    "), HTML)
Beispiel #10
0
def test_add_manual_link_localized(module_wide_request_context, monkeypatch):
    monkeypatch.setattr(config.user, "language", lambda: "de")
    assert compare_html(
        html.render_help(u"[introduction_docker|docker]"),
        HTML(
            u"<div style=\"display:none\" class=\"help\"><a href=\"https://docs.checkmk.com/master/de/introduction_docker.html\" target=\"_blank\">docker</a></div>"
        ))
Beispiel #11
0
def render_tree_folder(tree_id, folder, js_func):
    subfolders = folder.get(".folders", {}).values()
    is_leaf = len(subfolders) == 0

    # Suppress indentation for non-emtpy root folder
    if folder[".path"] == "" and is_leaf:
        html.open_ul()  # empty root folder
    elif folder and folder[".path"] != "":
        html.open_ul(style="padding-left:0px;")

    title = HTMLWriter.render_a(
        "%s (%d)" % (folder["title"], folder[".num_hosts"]),
        href="#",
        class_="link",
        onclick="%s(this, '%s');" % (js_func, folder[".path"]),
    )

    if not is_leaf:
        with foldable_container(
            treename=tree_id,
            id_="/" + folder[".path"],
            isopen=False,
            title=HTML(title),
            icon="foldable_sidebar",
            padding=6,
        ):
            for subfolder in sorted(subfolders, key=lambda x: x["title"].lower()):
                render_tree_folder(tree_id, subfolder, js_func)
    else:
        html.li(title)

    html.close_ul()
Beispiel #12
0
 def _deserialize(raw: object) -> "AuditLogStore.Entry":
     if not isinstance(raw, dict):
         raise ValueError("expected a dictionary")
     # TODO: Parse raw's entries, too, below we have our traditional 'wishful typing'... :-P
     raw["text"] = HTML(raw["text"][1]) if raw["text"][0] == "html" else raw["text"][1]
     raw["object_ref"] = ObjectRef.deserialize(raw["object_ref"]) if raw["object_ref"] else None
     return AuditLogStore.Entry(**raw)
Beispiel #13
0
    def render_icon_button(
        url: Union[None, str, str],
        title: str,
        icon: Icon,
        id_: Optional[str] = None,
        onclick: Optional[HTMLTagAttributeValue] = None,
        style: Optional[str] = None,
        target: Optional[str] = None,
        cssclass: Optional[str] = None,
        class_: Optional[CSSSpec] = None,
    ) -> HTML:
        classes = [] if cssclass is None else [cssclass]
        if isinstance(class_, list):
            classes.extend(class_)
        elif class_ is not None:
            classes.append(class_)

        href = url if not onclick else "javascript:void(0)"
        assert href is not None

        return HTMLWriter.render_a(
            content=HTML(HTMLGenerator.render_icon(icon, cssclass="iconbutton")),
            href=href,
            title=title,
            id_=id_,
            class_=classes,
            style=style,
            target=target if target else "",
            onfocus="if (this.blur) this.blur();",
            onclick=onclick,
        )
Beispiel #14
0
def text_with_links_to_user_translated_html(
    elements: Iterable[Tuple[str, Optional[str]]],
    separator: str = "",
) -> HTML:
    return HTML(separator).join(
        html.render_a(user_translation, href=url) if url else user_translation
        for txt, url in elements for user_translation in [_u(txt)] if txt)
Beispiel #15
0
    def _show_popup(self, entry: PageMenuEntry) -> None:
        assert isinstance(entry.item, PageMenuPopup)

        if entry.name is None:
            raise ValueError("Missing \"name\" attribute on entry \"%s\"" % entry.title)

        classes = ["page_menu_popup"] + html.normalize_css_spec(entry.item.css_classes)
        if isinstance(entry.item, PageMenuSidePopup):
            classes.append("side_popup")

        popup_id = "popup_%s" % entry.name
        html.open_div(id_=popup_id, class_=classes)

        html.open_div(class_="head")
        html.h3(entry.title)
        html.a(html.render_icon("close"),
               class_="close_popup",
               href="javascript:void(0)",
               onclick="cmk.page_menu.close_popup(this)")
        html.close_div()

        if (isinstance(entry.item, PageMenuSidePopup) and entry.item.content and
                "side_popup_content" not in entry.item.content):
            raise RuntimeError(
                "Add a div container with the class \"side_popup_content\" to the popup content")

        html.open_div(class_="content")
        html.write(HTML(entry.item.content))
        html.close_div()
        html.close_div()

        if isinstance(entry.item, PageMenuSidePopup):
            html.final_javascript("cmk.page_menu.side_popup_add_simplebar_scrollbar(%s);" %
                                  json.dumps(popup_id))
Beispiel #16
0
def test_add_manual_link_anchor(module_wide_request_context, monkeypatch):
    monkeypatch.setattr(config.user, "language", lambda: "de")
    assert compare_html(
        html.render_help(u"[graphing#rrds|RRDs]"),
        HTML(
            u"<div style=\"display:none\" class=\"help\"><a href=\"https://docs.checkmk.de/master/de/graphing.html#rrds\" target=\"_blank\">RRDs</a></div>"
        ))
Beispiel #17
0
def test_add_manual_link(register_builtin_html):
    assert config.user.language is None
    assert compare_html(
        html.render_help(u"[introduction_docker|docker]"),
        HTML(
            u"<div style=\"display:none\" class=\"help\"><a href=\"https://docs.checkmk.com/master/en/introduction_docker.html\" target=\"_blank\">docker</a></div>"
        ))
Beispiel #18
0
    def _show_tree(self):
        td_style = None if self._wrap_texts == "wrap" else "white-space: nowrap;"

        tree = self._get_tree()
        depth = status_tree_depth(tree)
        leaves = self._gen_table(tree, depth, len(self._row["aggr_hosts"]) > 1)

        html.open_table(class_=["aggrtree", "ltr"])
        odd = "odd"
        for code, colspan, parents in leaves:
            html.open_tr()

            leaf_td = HTMLWriter.render_td(code,
                                           class_=["leaf", odd],
                                           style=td_style,
                                           colspan=colspan)
            odd = "even" if odd == "odd" else "odd"

            tds = [leaf_td]
            for rowspan, c in parents:
                tds.append(
                    HTMLWriter.render_td(c,
                                         class_=["node"],
                                         style=td_style,
                                         rowspan=rowspan))

            if self._mirror:
                tds.reverse()

            html.write_html(HTML("").join(tds))
            html.close_tr()

        html.close_table()
Beispiel #19
0
    def render(self, row: Row, cell: Cell) -> CellSpec:
        classes = ["perfometer"]
        if is_stale(row):
            classes.append("stale")

        try:
            title, h = Perfometer(row).render()
            if title is None and h is None:
                return "", ""
        except Exception as e:
            logger.exception("error rendering performeter")
            if active_config.debug:
                raise
            return " ".join(classes), _("Exception: %s") % e

        assert h is not None
        content = (HTMLWriter.render_div(HTML(h), class_=["content"]) +
                   HTMLWriter.render_div(title, class_=["title"]) +
                   HTMLWriter.render_div("", class_=["glass"]))

        # pnpgraph_present: -1 means unknown (path not configured), 0: no, 1: yes
        if display_options.enabled(
                display_options.X) and row["service_pnpgraph_present"] != 0:
            url = cmk_graph_url(row, "service")
            disabled = False
        else:
            url = "javascript:void(0)"
            disabled = True

        return " ".join(classes), HTMLWriter.render_a(
            content=content,
            href=url,
            title=escaping.strip_tags(title),
            class_=["disabled"] if disabled else [],
        )
Beispiel #20
0
    def _render_tree(self, tree):
        for group, attrs in tree.items():
            aggr_group_tree = "/".join(attrs["__path__"])
            fetch_url = makeuri_contextless(
                request,
                [
                    ("view_name", "aggr_all"),
                    ("aggr_group_tree", aggr_group_tree),
                ],
                filename="view.py",
            )

            if attrs.get("__children__"):
                with foldable_container(
                        treename="bi_aggregation_group_trees",
                        id_=aggr_group_tree,
                        isopen=False,
                        title=HTML(
                            HTMLWriter.render_a(
                                group,
                                href=fetch_url,
                                target="main",
                            )),
                        icon="foldable_sidebar",
                ):
                    self._render_tree(attrs["__children__"])
            else:
                html.open_ul()
                bulletlink(group, fetch_url)
                html.close_ul()
Beispiel #21
0
def query_limit_exceeded_warn(limit: Optional[int],
                              user_config: LoggedInUser) -> None:
    """Compare query reply against limits, warn in the GUI about incompleteness"""
    text = HTML(_("Your query produced more than %d results. ") % limit)

    if request.get_ascii_input(
            "limit",
            "soft") == "soft" and user_config.may("general.ignore_soft_limit"):
        text += html.render_a(
            _("Repeat query and allow more results."),
            target="_self",
            href=makeuri(request, [("limit", "hard")]),
        )
    elif request.get_ascii_input("limit") == "hard" and user_config.may(
            "general.ignore_hard_limit"):
        text += html.render_a(
            _("Repeat query without limit."),
            target="_self",
            href=makeuri(request, [("limit", "none")]),
        )

    text += escaping.escape_to_html_permissive(" " + _(
        "<b>Note:</b> the shown results are incomplete and do not reflect the sort order."
    ))
    html.show_warning(text)
Beispiel #22
0
 def paint(self, value, hostname):
     value = convert_cgroups_from_tuple(value)
     texts: List[HTML] = []
     self.load_data()
     if self._contactgroups is None:  # conditional caused by horrible API
         raise Exception("invalid contact groups")
     items = self._contactgroups.items()
     for name, cgroup in sorted(items, key=lambda x: x[1]["alias"]):
         if name in value["groups"]:
             display_name = cgroup.get("alias", name)
             texts.append(
                 html.render_a(
                     display_name,
                     href=makeuri_contextless(
                         request,
                         [("mode", "edit_contact_group"), ("edit", name)],
                         filename="wato.py",
                     ),
                 ))
     result: HTML = HTML(", ").join(texts)
     if texts and value["use"]:
         result += html.render_span(
             html.render_b("*"),
             title=
             _("These contact groups are also used in the monitoring configuration."
               ),
         )
     return "", result
Beispiel #23
0
    def action(self) -> ActionResult:
        if request.var("_reset"):
            if not transactions.check_transaction():
                return None

            try:
                del self._current_settings[self._varname]
            except KeyError:
                pass

            msg = escape_to_html(
                _("Resetted configuration variable %s to its default.") %
                self._varname)
        else:
            new_value = self._valuespec.from_html_vars("ve")
            self._valuespec.validate_value(new_value, "ve")
            self._current_settings[self._varname] = new_value
            msg = HTML(
                _("Changed global configuration variable %s to %s.") % (
                    escaping.escape_attribute(self._varname),
                    self._valuespec.value_to_html(new_value),
                ))

        self._save()
        _changes.add_change(
            "edit-configvar",
            msg,
            sites=self._affected_sites(),
            domains=[self._config_variable.domain()],
            need_restart=self._config_variable.need_restart(),
        )

        return redirect(self._back_url())
Beispiel #24
0
 def html_head(
     self, title: str, javascripts: Optional[Sequence[str]] = None, force: bool = False
 ) -> None:
     if force or not self._header_sent:
         self.write_html(HTML("<!DOCTYPE HTML>\n"))
         self.open_html()
         self._head(title, javascripts)
         self._header_sent = True
Beispiel #25
0
def test_render_help_visible(module_wide_request_context,
                             register_builtin_html, monkeypatch):
    monkeypatch.setattr(config.LoggedInUser, "show_help",
                        property(lambda s: True))
    assert config.user.show_help is True
    assert compare_html(
        html.render_help(u"äbc"),
        HTML(u"<div style=\"display:block\" class=\"help\">äbc</div>"))
Beispiel #26
0
 def paint(self, value, hostname):
     parts = [
         HTMLWriter.render_a(
             hn, "wato.py?" + urlencode_vars([("mode", "edit_host"),
                                              ("host", hn)]))
         for hn in value
     ]
     return "", HTML(", ").join(parts)
Beispiel #27
0
def test_add_manual_link(request_context):
    assert user.language is None
    assert compare_html(
        html.render_help("[intro_welcome|Welcome]"),
        HTML(
            '<div style="display:none" class="help"><a href="https://docs.checkmk.com/master/en/intro_welcome.html" target="_blank">Welcome</a></div>'
        ),
    )
Beispiel #28
0
def test_flash_escape_html_in_str(user_id, module_wide_request_context):
    with login.UserContext(user_id):
        on_succeeded_login(user_id)  # Create and activate session

        flash("<script>aaa</script>")
        assert get_flashed_messages() == [
            HTML("&lt;script&gt;aaa&lt;/script&gt;")
        ]
Beispiel #29
0
def test_add_manual_link_anchor(request_context, monkeypatch):
    monkeypatch.setattr(user, "language", lambda: "de")
    assert compare_html(
        html.render_help("[graphing#rrds|RRDs]"),
        HTML(
            '<div style="display:none" class="help"><a href="https://docs.checkmk.de/master/de/graphing.html#rrds" target="_blank">RRDs</a></div>'
        ),
    )
Beispiel #30
0
def test_add_manual_link_localized(request_context, monkeypatch):
    monkeypatch.setattr(user, "language", lambda: "de")
    assert compare_html(
        html.render_help("[intro_welcome|Welcome]"),
        HTML(
            '<div style="display:none" class="help"><a href="https://docs.checkmk.com/master/de/intro_welcome.html" target="_blank">Welcome</a></div>'
        ),
    )