Repository: mozilla/bleach

Issue:
Exceptions on strange Html
Hello,

This small pattern raises an exception : 

    
    import bleach

    bleach.clean("<d {c}>")



Discussion:

Patch:
diff --git a/bleach/sanitizer.py b/bleach/sanitizer.py
index 12225ef..faf8fd7 100644
--- a/bleach/sanitizer.py
+++ b/bleach/sanitizer.py
@@ -668,8 +668,20 @@ class BleachSanitizerFilter(sanitizer.Filter):
             assert token_type in ("StartTag", "EmptyTag")
             attrs = []
             for (ns, name), v in token["data"].items():
+                # If we end up with a namespace, but no name, switch them so we
+                # have a valid name to use.
+                if ns and not name:
+                    ns, name = name, ns
+
+                # Figure out namespaced name if the namespace is appropriate
+                # and exists; if the ns isn't in prefixes, then drop it.
+                if ns is None or ns not in prefixes:
+                    namespaced_name = name
+                else:
+                    namespaced_name = '%s:%s' % (prefixes[ns], name)
+
                 attrs.append(' %s="%s"' % (
-                    name if ns is None else "%s:%s" % (prefixes[ns], name),
+                    namespaced_name,
                     # NOTE(willkg): HTMLSerializer escapes attribute values
                     # already, so if we do it here (like HTMLSerializer does),
                     # then we end up double-escaping.


Test patch:
diff --git a/tests/test_clean.py b/tests/test_clean.py
index 1f3cbfc..9547d63 100644
--- a/tests/test_clean.py
+++ b/tests/test_clean.py
@@ -759,6 +759,19 @@ def test_convert_entities(data, expected):
     assert convert_entities(data) == expected
 
 
+def test_nonexistent_namespace():
+    """Verify if the namespace doesn't exist, it doesn't fail with a KeyError
+
+    The tokenizer creates "c" as a namespace and that doesn't exist in the map
+    of namespaces, so then it fails with a KeyError. I don't understand why the
+    tokenizer makes "c" into a namespace in this string.
+
+    Issue #352.
+
+    """
+    assert clean('<d {c}>') == '&lt;d c=""&gt;&lt;/d&gt;'
+
+
 def get_tests():
     """Retrieves regression tests from data/ directory