signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
@staticmethod<EOL><INDENT>def validate_month(month):<DEDENT> | return <NUM_LIT:1> <= month <= <NUM_LIT:12><EOL> | Validate month. | f13616:c2:m2 |
@staticmethod<EOL><INDENT>def validate_year(year):<DEDENT> | return <NUM_LIT:1> <= year<EOL> | Validate year. | f13616:c2:m3 |
@staticmethod<EOL><INDENT>def validate_hour(hour):<DEDENT> | return <NUM_LIT:0> <= hour <= <NUM_LIT><EOL> | Validate hour. | f13616:c2:m4 |
@staticmethod<EOL><INDENT>def validate_minutes(minutes):<DEDENT> | return <NUM_LIT:0> <= minutes <= <NUM_LIT><EOL> | Validate minutes. | f13616:c2:m5 |
@classmethod<EOL><INDENT>def parse_value(cls, itype, value):<DEDENT> | parsed = None<EOL>if itype == "<STR_LIT:date>":<EOL><INDENT>m = RE_DATE.match(value)<EOL>if m:<EOL><INDENT>year = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>month = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>day = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>if cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day):<EOL><INDENT>parsed = (year, month, day)<EOL><DEDENT><DEDENT><DEDENT>elif itype == "<STR_LIT>":<EOL><INDENT>m = RE_MONTH.match(value)<EOL>if m:<EOL><INDENT>year = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>month = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>if cls.validate_year(year) and cls.validate_month(month):<EOL><INDENT>parsed = (year, month)<EOL><DEDENT><DEDENT><DEDENT>elif itype == "<STR_LIT>":<EOL><INDENT>m = RE_WEEK.match(value)<EOL>if m:<EOL><INDENT>year = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>week = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>if cls.validate_year(year) and cls.validate_week(year, week):<EOL><INDENT>parsed = (year, week)<EOL><DEDENT><DEDENT><DEDENT>elif itype == "<STR_LIT:time>":<EOL><INDENT>m = RE_TIME.match(value)<EOL>if m:<EOL><INDENT>hour = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>minutes = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>if cls.validate_hour(hour) and cls.validate_minutes(minutes):<EOL><INDENT>parsed = (hour, minutes)<EOL><DEDENT><DEDENT><DEDENT>elif itype == "<STR_LIT>":<EOL><INDENT>m = RE_DATETIME.match(value)<EOL>if m:<EOL><INDENT>year = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>month = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>day = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>hour = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>minutes = int(m.group('<STR_LIT>'), <NUM_LIT:10>)<EOL>if (<EOL>cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day) and<EOL>cls.validate_hour(hour) and cls.validate_minutes(minutes)<EOL>):<EOL><INDENT>parsed = (year, month, day, hour, minutes)<EOL><DEDENT><DEDENT><DEDENT>elif itype in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>m = RE_NUM.match(value)<EOL>if m:<EOL><INDENT>parsed = float(m.group('<STR_LIT:value>'))<EOL><DEDENT><DEDENT>return parsed<EOL> | Parse the input value. | f13616:c2:m6 |
def __init__(self, selectors, scope, namespaces, flags): | self.assert_valid_input(scope)<EOL>self.tag = scope<EOL>self.cached_meta_lang = []<EOL>self.cached_default_forms = []<EOL>self.cached_indeterminate_forms = []<EOL>self.selectors = selectors<EOL>self.namespaces = {} if namespaces is None else namespaces<EOL>self.flags = flags<EOL>self.iframe_restrict = False<EOL>doc = scope<EOL>parent = self.get_parent(doc)<EOL>while parent:<EOL><INDENT>doc = parent<EOL>parent = self.get_parent(doc)<EOL><DEDENT>root = None<EOL>if not self.is_doc(doc):<EOL><INDENT>root = doc<EOL><DEDENT>else:<EOL><INDENT>for child in self.get_children(doc):<EOL><INDENT>root = child<EOL>break<EOL><DEDENT><DEDENT>self.root = root<EOL>self.scope = scope if scope is not doc else root<EOL>self.has_html_namespace = self.has_html_ns(root)<EOL>self.is_xml = self.is_xml_tree(doc)<EOL>self.is_html = not self.is_xml or self.has_html_namespace<EOL> | Initialize. | f13616:c3:m0 |
def supports_namespaces(self): | return self.is_xml or self.has_html_namespace<EOL> | Check if namespaces are supported in the HTML type. | f13616:c3:m1 |
def get_tag_ns(self, el): | if self.supports_namespaces():<EOL><INDENT>namespace = '<STR_LIT>'<EOL>ns = el.namespace<EOL>if ns:<EOL><INDENT>namespace = ns<EOL><DEDENT><DEDENT>else:<EOL><INDENT>namespace = NS_XHTML<EOL><DEDENT>return namespace<EOL> | Get tag namespace. | f13616:c3:m2 |
def is_html_tag(self, el): | return self.get_tag_ns(el) == NS_XHTML<EOL> | Check if tag is in HTML namespace. | f13616:c3:m3 |
def get_tag(self, el): | name = self.get_tag_name(el)<EOL>return util.lower(name) if name is not None and not self.is_xml else name<EOL> | Get tag. | f13616:c3:m4 |
def get_prefix(self, el): | prefix = self.get_prefix_name(el)<EOL>return util.lower(prefix) if prefix is not None and not self.is_xml else prefix<EOL> | Get prefix. | f13616:c3:m5 |
def find_bidi(self, el): | for node in self.get_children(el, tags=False):<EOL><INDENT>if self.is_tag(node):<EOL><INDENT>direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(node, '<STR_LIT>', '<STR_LIT>')), None)<EOL>if (<EOL>self.get_tag(node) in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>') or<EOL>not self.is_html_tag(node) or<EOL>direction is not None<EOL>):<EOL><INDENT>continue <EOL><DEDENT>value = self.find_bidi(node)<EOL>if value is not None:<EOL><INDENT>return value<EOL><DEDENT>continue <EOL><DEDENT>if self.is_special_string(node):<EOL><INDENT>continue<EOL><DEDENT>for c in node:<EOL><INDENT>bidi = unicodedata.bidirectional(c)<EOL>if bidi in ('<STR_LIT>', '<STR_LIT:R>', '<STR_LIT:L>'):<EOL><INDENT>return ct.SEL_DIR_LTR if bidi == '<STR_LIT:L>' else ct.SEL_DIR_RTL<EOL><DEDENT><DEDENT><DEDENT>return None<EOL> | Get directionality from element text. | f13616:c3:m6 |
def match_attribute_name(self, el, attr, prefix): | value = None<EOL>if self.supports_namespaces():<EOL><INDENT>value = None<EOL>if prefix:<EOL><INDENT>ns = self.namespaces.get(prefix)<EOL>if ns is None and prefix != '<STR_LIT:*>':<EOL><INDENT>return None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ns = None<EOL><DEDENT>for k, v in self.iter_attributes(el):<EOL><INDENT>namespace, name = self.split_namespace(el, k)<EOL>if ns is None:<EOL><INDENT>if (self.is_xml and attr == k) or (not self.is_xml and util.lower(attr) == util.lower(k)):<EOL><INDENT>value = v<EOL>break<EOL><DEDENT>continue <EOL><DEDENT>if namespace is None or ns != namespace and prefix != '<STR_LIT:*>':<EOL><INDENT>continue<EOL><DEDENT>if (util.lower(attr) != util.lower(name)) if not self.is_xml else (attr != name):<EOL><INDENT>continue<EOL><DEDENT>value = v<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for k, v in self.iter_attributes(el):<EOL><INDENT>if util.lower(attr) != util.lower(k):<EOL><INDENT>continue<EOL><DEDENT>value = v<EOL>break<EOL><DEDENT><DEDENT>return value<EOL> | Match attribute name and return value if it exists. | f13616:c3:m7 |
def match_namespace(self, el, tag): | match = True<EOL>namespace = self.get_tag_ns(el)<EOL>default_namespace = self.namespaces.get('<STR_LIT>')<EOL>tag_ns = '<STR_LIT>' if tag.prefix is None else self.namespaces.get(tag.prefix, None)<EOL>if tag.prefix is None and (default_namespace is not None and namespace != default_namespace):<EOL><INDENT>match = False<EOL><DEDENT>elif (tag.prefix is not None and tag.prefix == '<STR_LIT>' and namespace):<EOL><INDENT>match = False<EOL><DEDENT>elif (<EOL>tag.prefix and<EOL>tag.prefix != '<STR_LIT:*>' and (tag_ns is None or namespace != tag_ns)<EOL>):<EOL><INDENT>match = False<EOL><DEDENT>return match<EOL> | Match the namespace of the element. | f13616:c3:m8 |
def match_attributes(self, el, attributes): | match = True<EOL>if attributes:<EOL><INDENT>for a in attributes:<EOL><INDENT>value = self.match_attribute_name(el, a.attribute, a.prefix)<EOL>pattern = a.xml_type_pattern if self.is_xml and a.xml_type_pattern else a.pattern<EOL>if isinstance(value, list):<EOL><INDENT>value = '<STR_LIT:U+0020>'.join(value)<EOL><DEDENT>if value is None:<EOL><INDENT>match = False<EOL>break<EOL><DEDENT>elif pattern is None:<EOL><INDENT>continue<EOL><DEDENT>elif pattern.match(value) is None:<EOL><INDENT>match = False<EOL>break<EOL><DEDENT><DEDENT><DEDENT>return match<EOL> | Match attributes. | f13616:c3:m9 |
def match_tagname(self, el, tag): | name = (util.lower(tag.name) if not self.is_xml and tag.name is not None else tag.name)<EOL>return not (<EOL>name is not None and<EOL>name not in (self.get_tag(el), '<STR_LIT:*>')<EOL>)<EOL> | Match tag name. | f13616:c3:m10 |
def match_tag(self, el, tag): | match = True<EOL>if tag is not None:<EOL><INDENT>if not self.match_namespace(el, tag):<EOL><INDENT>match = False<EOL><DEDENT>if not self.match_tagname(el, tag):<EOL><INDENT>match = False<EOL><DEDENT><DEDENT>return match<EOL> | Match the tag. | f13616:c3:m11 |
def match_past_relations(self, el, relation): | found = False<EOL>if relation[<NUM_LIT:0>].rel_type == REL_PARENT:<EOL><INDENT>parent = self.get_parent(el, no_iframe=self.iframe_restrict)<EOL>while not found and parent:<EOL><INDENT>found = self.match_selectors(parent, relation)<EOL>parent = self.get_parent(parent, no_iframe=self.iframe_restrict)<EOL><DEDENT><DEDENT>elif relation[<NUM_LIT:0>].rel_type == REL_CLOSE_PARENT:<EOL><INDENT>parent = self.get_parent(el, no_iframe=self.iframe_restrict)<EOL>if parent:<EOL><INDENT>found = self.match_selectors(parent, relation)<EOL><DEDENT><DEDENT>elif relation[<NUM_LIT:0>].rel_type == REL_SIBLING:<EOL><INDENT>sibling = self.get_previous_tag(el)<EOL>while not found and sibling:<EOL><INDENT>found = self.match_selectors(sibling, relation)<EOL>sibling = self.get_previous_tag(sibling)<EOL><DEDENT><DEDENT>elif relation[<NUM_LIT:0>].rel_type == REL_CLOSE_SIBLING:<EOL><INDENT>sibling = self.get_previous_tag(el)<EOL>if sibling and self.is_tag(sibling):<EOL><INDENT>found = self.match_selectors(sibling, relation)<EOL><DEDENT><DEDENT>return found<EOL> | Match past relationship. | f13616:c3:m12 |
def match_future_child(self, parent, relation, recursive=False): | match = False<EOL>children = self.get_descendants if recursive else self.get_children<EOL>for child in children(parent, no_iframe=self.iframe_restrict):<EOL><INDENT>match = self.match_selectors(child, relation)<EOL>if match:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return match<EOL> | Match future child. | f13616:c3:m13 |
def match_future_relations(self, el, relation): | found = False<EOL>if relation[<NUM_LIT:0>].rel_type == REL_HAS_PARENT:<EOL><INDENT>found = self.match_future_child(el, relation, True)<EOL><DEDENT>elif relation[<NUM_LIT:0>].rel_type == REL_HAS_CLOSE_PARENT:<EOL><INDENT>found = self.match_future_child(el, relation)<EOL><DEDENT>elif relation[<NUM_LIT:0>].rel_type == REL_HAS_SIBLING:<EOL><INDENT>sibling = self.get_next_tag(el)<EOL>while not found and sibling:<EOL><INDENT>found = self.match_selectors(sibling, relation)<EOL>sibling = self.get_next_tag(sibling)<EOL><DEDENT><DEDENT>elif relation[<NUM_LIT:0>].rel_type == REL_HAS_CLOSE_SIBLING:<EOL><INDENT>sibling = self.get_next_tag(el)<EOL>if sibling and self.is_tag(sibling):<EOL><INDENT>found = self.match_selectors(sibling, relation)<EOL><DEDENT><DEDENT>return found<EOL> | Match future relationship. | f13616:c3:m14 |
def match_relations(self, el, relation): | found = False<EOL>if relation[<NUM_LIT:0>].rel_type.startswith('<STR_LIT::>'):<EOL><INDENT>found = self.match_future_relations(el, relation)<EOL><DEDENT>else:<EOL><INDENT>found = self.match_past_relations(el, relation)<EOL><DEDENT>return found<EOL> | Match relationship to other elements. | f13616:c3:m15 |
def match_id(self, el, ids): | found = True<EOL>for i in ids:<EOL><INDENT>if i != self.get_attribute_by_name(el, '<STR_LIT:id>', '<STR_LIT>'):<EOL><INDENT>found = False<EOL>break<EOL><DEDENT><DEDENT>return found<EOL> | Match element's ID. | f13616:c3:m16 |
def match_classes(self, el, classes): | current_classes = self.get_classes(el)<EOL>found = True<EOL>for c in classes:<EOL><INDENT>if c not in current_classes:<EOL><INDENT>found = False<EOL>break<EOL><DEDENT><DEDENT>return found<EOL> | Match element's classes. | f13616:c3:m17 |
def match_root(self, el): | return self.is_root(el)<EOL> | Match element as root. | f13616:c3:m18 |
def match_scope(self, el): | return self.scope is el<EOL> | Match element as scope. | f13616:c3:m19 |
def match_nth_tag_type(self, el, child): | return(<EOL>(self.get_tag(child) == self.get_tag(el)) and<EOL>(self.get_tag_ns(child) == self.get_tag_ns(el))<EOL>)<EOL> | Match tag type for `nth` matches. | f13616:c3:m20 |
def match_nth(self, el, nth): | matched = True<EOL>for n in nth:<EOL><INDENT>matched = False<EOL>if n.selectors and not self.match_selectors(el, n.selectors):<EOL><INDENT>break<EOL><DEDENT>parent = self.get_parent(el)<EOL>if parent is None:<EOL><INDENT>parent = self.create_fake_parent(el)<EOL><DEDENT>last = n.last<EOL>last_index = len(parent) - <NUM_LIT:1><EOL>index = last_index if last else <NUM_LIT:0><EOL>relative_index = <NUM_LIT:0><EOL>a = n.a<EOL>b = n.b<EOL>var = n.n<EOL>count = <NUM_LIT:0><EOL>count_incr = <NUM_LIT:1><EOL>factor = -<NUM_LIT:1> if last else <NUM_LIT:1><EOL>idx = last_idx = a * count + b if var else a<EOL>if var:<EOL><INDENT>adjust = None<EOL>while idx < <NUM_LIT:1> or idx > last_index:<EOL><INDENT>if idx < <NUM_LIT:0>:<EOL><INDENT>diff_low = <NUM_LIT:0> - idx<EOL>if adjust is not None and adjust == <NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT>adjust = -<NUM_LIT:1><EOL>count += count_incr<EOL>idx = last_idx = a * count + b if var else a<EOL>diff = <NUM_LIT:0> - idx<EOL>if diff >= diff_low:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>diff_high = idx - last_index<EOL>if adjust is not None and adjust == -<NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT>adjust = <NUM_LIT:1><EOL>count += count_incr<EOL>idx = last_idx = a * count + b if var else a<EOL>diff = idx - last_index<EOL>if diff >= diff_high:<EOL><INDENT>break<EOL><DEDENT>diff_high = diff<EOL><DEDENT><DEDENT>lowest = count<EOL>if a < <NUM_LIT:0>:<EOL><INDENT>while idx >= <NUM_LIT:1>:<EOL><INDENT>lowest = count<EOL>count += count_incr<EOL>idx = last_idx = a * count + b if var else a<EOL><DEDENT>count_incr = -<NUM_LIT:1><EOL><DEDENT>count = lowest<EOL>idx = last_idx = a * count + b if var else a<EOL><DEDENT>while <NUM_LIT:1> <= idx <= last_index + <NUM_LIT:1>:<EOL><INDENT>child = None<EOL>for child in self.get_children(parent, start=index, reverse=factor < <NUM_LIT:0>, tags=False):<EOL><INDENT>index += factor<EOL>if not self.is_tag(child):<EOL><INDENT>continue<EOL><DEDENT>if n.selectors and not self.match_selectors(child, n.selectors):<EOL><INDENT>continue<EOL><DEDENT>if n.of_type and not self.match_nth_tag_type(el, child):<EOL><INDENT>continue<EOL><DEDENT>relative_index += <NUM_LIT:1><EOL>if relative_index == idx:<EOL><INDENT>if child is el:<EOL><INDENT>matched = True<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if child is el:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if child is el:<EOL><INDENT>break<EOL><DEDENT>last_idx = idx<EOL>count += count_incr<EOL>if count < <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>idx = a * count + b if var else a<EOL>if last_idx == idx:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if not matched:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return matched<EOL> | Match `nth` elements. | f13616:c3:m21 |
def match_empty(self, el): | is_empty = True<EOL>for child in self.get_children(el, tags=False):<EOL><INDENT>if self.is_tag(child):<EOL><INDENT>is_empty = False<EOL>break<EOL><DEDENT>elif self.is_content_string(child) and RE_NOT_EMPTY.search(child):<EOL><INDENT>is_empty = False<EOL>break<EOL><DEDENT><DEDENT>return is_empty<EOL> | Check if element is empty (if requested). | f13616:c3:m22 |
def match_subselectors(self, el, selectors): | match = True<EOL>for sel in selectors:<EOL><INDENT>if not self.match_selectors(el, sel):<EOL><INDENT>match = False<EOL><DEDENT><DEDENT>return match<EOL> | Match selectors. | f13616:c3:m23 |
def match_contains(self, el, contains): | match = True<EOL>content = None<EOL>for contain_list in contains:<EOL><INDENT>if content is None:<EOL><INDENT>content = self.get_text(el, no_iframe=self.is_html)<EOL><DEDENT>found = False<EOL>for text in contain_list.text:<EOL><INDENT>if text in content:<EOL><INDENT>found = True<EOL>break<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>match = False<EOL><DEDENT><DEDENT>return match<EOL> | Match element if it contains text. | f13616:c3:m24 |
def match_default(self, el): | match = False<EOL>form = None<EOL>parent = self.get_parent(el, no_iframe=True)<EOL>while parent and form is None:<EOL><INDENT>if self.get_tag(parent) == '<STR_LIT>' and self.is_html_tag(parent):<EOL><INDENT>form = parent<EOL><DEDENT>else:<EOL><INDENT>parent = self.get_parent(parent, no_iframe=True)<EOL><DEDENT><DEDENT>found_form = False<EOL>for f, t in self.cached_default_forms:<EOL><INDENT>if f is form:<EOL><INDENT>found_form = True<EOL>if t is el:<EOL><INDENT>match = True<EOL><DEDENT>break<EOL><DEDENT><DEDENT>if not found_form:<EOL><INDENT>for child in self.get_descendants(form, no_iframe=True):<EOL><INDENT>name = self.get_tag(child)<EOL>if name == '<STR_LIT>': <EOL><INDENT>break<EOL><DEDENT>if name in ('<STR_LIT:input>', '<STR_LIT>'):<EOL><INDENT>v = self.get_attribute_by_name(child, '<STR_LIT:type>', '<STR_LIT>')<EOL>if v and util.lower(v) == '<STR_LIT>':<EOL><INDENT>self.cached_default_forms.append([form, child])<EOL>if el is child:<EOL><INDENT>match = True<EOL><DEDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return match<EOL> | Match default. | f13616:c3:m25 |
def match_indeterminate(self, el): | match = False<EOL>name = self.get_attribute_by_name(el, '<STR_LIT:name>')<EOL>def get_parent_form(el):<EOL><INDENT>"""<STR_LIT>"""<EOL>form = None<EOL>parent = self.get_parent(el, no_iframe=True)<EOL>while form is None:<EOL><INDENT>if self.get_tag(parent) == '<STR_LIT>' and self.is_html_tag(parent):<EOL><INDENT>form = parent<EOL>break<EOL><DEDENT>last_parent = parent<EOL>parent = self.get_parent(parent, no_iframe=True)<EOL>if parent is None:<EOL><INDENT>form = last_parent<EOL>break<EOL><DEDENT><DEDENT>return form<EOL><DEDENT>form = get_parent_form(el)<EOL>found_form = False<EOL>for f, n, i in self.cached_indeterminate_forms:<EOL><INDENT>if f is form and n == name:<EOL><INDENT>found_form = True<EOL>if i is True:<EOL><INDENT>match = True<EOL><DEDENT>break<EOL><DEDENT><DEDENT>if not found_form:<EOL><INDENT>checked = False<EOL>for child in self.get_descendants(form, no_iframe=True):<EOL><INDENT>if child is el:<EOL><INDENT>continue<EOL><DEDENT>tag_name = self.get_tag(child)<EOL>if tag_name == '<STR_LIT:input>':<EOL><INDENT>is_radio = False<EOL>check = False<EOL>has_name = False<EOL>for k, v in self.iter_attributes(child):<EOL><INDENT>if util.lower(k) == '<STR_LIT:type>' and util.lower(v) == '<STR_LIT>':<EOL><INDENT>is_radio = True<EOL><DEDENT>elif util.lower(k) == '<STR_LIT:name>' and v == name:<EOL><INDENT>has_name = True<EOL><DEDENT>elif util.lower(k) == '<STR_LIT>':<EOL><INDENT>check = True<EOL><DEDENT>if is_radio and check and has_name and get_parent_form(child) is form:<EOL><INDENT>checked = True<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if checked:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if not checked:<EOL><INDENT>match = True<EOL><DEDENT>self.cached_indeterminate_forms.append([form, name, match])<EOL><DEDENT>return match<EOL> | Match default. | f13616:c3:m26 |
def match_lang(self, el, langs): | match = False<EOL>has_ns = self.supports_namespaces()<EOL>root = self.root<EOL>has_html_namespace = self.has_html_namespace<EOL>parent = el<EOL>found_lang = None<EOL>last = None<EOL>while not found_lang:<EOL><INDENT>has_html_ns = self.has_html_ns(parent)<EOL>for k, v in self.iter_attributes(parent):<EOL><INDENT>attr_ns, attr = self.split_namespace(parent, k)<EOL>if (<EOL>((not has_ns or has_html_ns) and (util.lower(k) if not self.is_xml else k) == '<STR_LIT>') or<EOL>(<EOL>has_ns and not has_html_ns and attr_ns == NS_XML and<EOL>(util.lower(attr) if not self.is_xml and attr is not None else attr) == '<STR_LIT>'<EOL>)<EOL>):<EOL><INDENT>found_lang = v<EOL>break<EOL><DEDENT><DEDENT>last = parent<EOL>parent = self.get_parent(parent, no_iframe=self.is_html)<EOL>if parent is None:<EOL><INDENT>root = last<EOL>has_html_namespace = self.has_html_ns(root)<EOL>parent = last<EOL>break<EOL><DEDENT><DEDENT>if not found_lang and self.cached_meta_lang:<EOL><INDENT>for cache in self.cached_meta_lang:<EOL><INDENT>if root is cache[<NUM_LIT:0>]:<EOL><INDENT>found_lang = cache[<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>if found_lang is None and (not self.is_xml or (has_html_namespace and root.name == '<STR_LIT:html>')):<EOL><INDENT>found = False<EOL>for tag in ('<STR_LIT:html>', '<STR_LIT>'):<EOL><INDENT>found = False<EOL>for child in self.get_children(parent, no_iframe=self.is_html):<EOL><INDENT>if self.get_tag(child) == tag and self.is_html_tag(child):<EOL><INDENT>found = True<EOL>parent = child<EOL>break<EOL><DEDENT><DEDENT>if not found: <EOL><INDENT>break<EOL><DEDENT><DEDENT>if found:<EOL><INDENT>for child in parent:<EOL><INDENT>if self.is_tag(child) and self.get_tag(child) == '<STR_LIT>' and self.is_html_tag(parent):<EOL><INDENT>c_lang = False<EOL>content = None<EOL>for k, v in self.iter_attributes(child):<EOL><INDENT>if util.lower(k) == '<STR_LIT>' and util.lower(v) == '<STR_LIT>':<EOL><INDENT>c_lang = True<EOL><DEDENT>if util.lower(k) == '<STR_LIT:content>':<EOL><INDENT>content = v<EOL><DEDENT>if c_lang and content:<EOL><INDENT>found_lang = content<EOL>self.cached_meta_lang.append((root, found_lang))<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if found_lang:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if not found_lang:<EOL><INDENT>self.cached_meta_lang.append((root, False))<EOL><DEDENT><DEDENT><DEDENT>if found_lang:<EOL><INDENT>for patterns in langs:<EOL><INDENT>match = False<EOL>for pattern in patterns:<EOL><INDENT>if pattern.match(found_lang):<EOL><INDENT>match = True<EOL><DEDENT><DEDENT>if not match:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return match<EOL> | Match languages. | f13616:c3:m27 |
def match_dir(self, el, directionality): | <EOL>if directionality & ct.SEL_DIR_LTR and directionality & ct.SEL_DIR_RTL:<EOL><INDENT>return False<EOL><DEDENT>if el is None or not self.is_html_tag(el):<EOL><INDENT>return False<EOL><DEDENT>direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(el, '<STR_LIT>', '<STR_LIT>')), None)<EOL>if direction not in (None, <NUM_LIT:0>):<EOL><INDENT>return direction == directionality<EOL><DEDENT>is_root = self.is_root(el)<EOL>if is_root and direction is None:<EOL><INDENT>return ct.SEL_DIR_LTR == directionality<EOL><DEDENT>name = self.get_tag(el)<EOL>is_input = name == '<STR_LIT:input>'<EOL>is_textarea = name == '<STR_LIT>'<EOL>is_bdi = name == '<STR_LIT>'<EOL>itype = util.lower(self.get_attribute_by_name(el, '<STR_LIT:type>', '<STR_LIT>')) if is_input else '<STR_LIT>'<EOL>if is_input and itype == '<STR_LIT>' and direction is None:<EOL><INDENT>return ct.SEL_DIR_LTR == directionality<EOL><DEDENT>if ((is_input and itype in ('<STR_LIT:text>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:url>', '<STR_LIT:email>')) or is_textarea) and direction == <NUM_LIT:0>:<EOL><INDENT>if is_textarea:<EOL><INDENT>value = []<EOL>for node in self.get_contents(el, no_iframe=True):<EOL><INDENT>if self.is_content_string(node):<EOL><INDENT>value.append(node)<EOL><DEDENT><DEDENT>value = '<STR_LIT>'.join(value)<EOL><DEDENT>else:<EOL><INDENT>value = self.get_attribute_by_name(el, '<STR_LIT:value>', '<STR_LIT>')<EOL><DEDENT>if value:<EOL><INDENT>for c in value:<EOL><INDENT>bidi = unicodedata.bidirectional(c)<EOL>if bidi in ('<STR_LIT>', '<STR_LIT:R>', '<STR_LIT:L>'):<EOL><INDENT>direction = ct.SEL_DIR_LTR if bidi == '<STR_LIT:L>' else ct.SEL_DIR_RTL<EOL>return direction == directionality<EOL><DEDENT><DEDENT>return ct.SEL_DIR_LTR == directionality<EOL><DEDENT>elif is_root:<EOL><INDENT>return ct.SEL_DIR_LTR == directionality<EOL><DEDENT>return self.match_dir(self.get_parent(el, no_iframe=True), directionality)<EOL><DEDENT>if (is_bdi and direction is None) or direction == <NUM_LIT:0>:<EOL><INDENT>direction = self.find_bidi(el)<EOL>if direction is not None:<EOL><INDENT>return direction == directionality<EOL><DEDENT>elif is_root:<EOL><INDENT>return ct.SEL_DIR_LTR == directionality<EOL><DEDENT>return self.match_dir(self.get_parent(el, no_iframe=True), directionality)<EOL><DEDENT>return self.match_dir(self.get_parent(el, no_iframe=True), directionality)<EOL> | Check directionality. | f13616:c3:m28 |
def match_range(self, el, condition): | out_of_range = False<EOL>itype = self.get_attribute_by_name(el, '<STR_LIT:type>').lower()<EOL>mn = self.get_attribute_by_name(el, '<STR_LIT>', None)<EOL>if mn is not None:<EOL><INDENT>mn = Inputs.parse_value(itype, mn)<EOL><DEDENT>mx = self.get_attribute_by_name(el, '<STR_LIT>', None)<EOL>if mx is not None:<EOL><INDENT>mx = Inputs.parse_value(itype, mx)<EOL><DEDENT>if mn is None and mx is None:<EOL><INDENT>return False<EOL><DEDENT>value = self.get_attribute_by_name(el, '<STR_LIT:value>', None)<EOL>if value is not None:<EOL><INDENT>value = Inputs.parse_value(itype, value)<EOL><DEDENT>if value is not None:<EOL><INDENT>if itype in ("<STR_LIT:date>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>if mn is not None and value < mn:<EOL><INDENT>out_of_range = True<EOL><DEDENT>if not out_of_range and mx is not None and value > mx:<EOL><INDENT>out_of_range = True<EOL><DEDENT><DEDENT>elif itype == "<STR_LIT:time>":<EOL><INDENT>if mn is not None and mx is not None and mn > mx:<EOL><INDENT>if value < mn and value > mx:<EOL><INDENT>out_of_range = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if mn is not None and value < mn:<EOL><INDENT>out_of_range = True<EOL><DEDENT>if not out_of_range and mx is not None and value > mx:<EOL><INDENT>out_of_range = True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return not out_of_range if condition & ct.SEL_IN_RANGE else out_of_range<EOL> | Match range.
Behavior is modeled after what we see in browsers. Browsers seem to evaluate
if the value is out of range, and if not, it is in range. So a missing value
will not evaluate out of range; therefore, value is in range. Personally, I
feel like this should evaluate as neither in or out of range. | f13616:c3:m29 |
def match_defined(self, el): | name = self.get_tag(el)<EOL>return (<EOL>name.find('<STR_LIT:->') == -<NUM_LIT:1> or<EOL>name.find('<STR_LIT::>') != -<NUM_LIT:1> or<EOL>self.get_prefix(el) is not None<EOL>)<EOL> | Match defined.
`:defined` is related to custom elements in a browser.
- If the document is XML (not XHTML), all tags will match.
- Tags that are not custom (don't have a hyphen) are marked defined.
- If the tag has a prefix (without or without a namespace), it will not match.
This is of course requires the parser to provide us with the proper prefix and namespace info,
if it doesn't, there is nothing we can do. | f13616:c3:m30 |
def match_selectors(self, el, selectors): | match = False<EOL>is_not = selectors.is_not<EOL>is_html = selectors.is_html<EOL>if is_html:<EOL><INDENT>namespaces = self.namespaces<EOL>iframe_restrict = self.iframe_restrict<EOL>self.namespaces = {'<STR_LIT:html>': NS_XHTML}<EOL>self.iframe_restrict = True<EOL><DEDENT>if not is_html or self.is_html:<EOL><INDENT>for selector in selectors:<EOL><INDENT>match = is_not<EOL>if isinstance(selector, ct.SelectorNull):<EOL><INDENT>continue<EOL><DEDENT>if not self.match_tag(el, selector.tag):<EOL><INDENT>continue<EOL><DEDENT>if selector.flags & ct.SEL_DEFINED and not self.match_defined(el):<EOL><INDENT>continue<EOL><DEDENT>if selector.flags & ct.SEL_ROOT and not self.match_root(el):<EOL><INDENT>continue<EOL><DEDENT>if selector.flags & ct.SEL_SCOPE and not self.match_scope(el):<EOL><INDENT>continue<EOL><DEDENT>if not self.match_nth(el, selector.nth):<EOL><INDENT>continue<EOL><DEDENT>if selector.flags & ct.SEL_EMPTY and not self.match_empty(el):<EOL><INDENT>continue<EOL><DEDENT>if selector.ids and not self.match_id(el, selector.ids):<EOL><INDENT>continue<EOL><DEDENT>if selector.classes and not self.match_classes(el, selector.classes):<EOL><INDENT>continue<EOL><DEDENT>if not self.match_attributes(el, selector.attributes):<EOL><INDENT>continue<EOL><DEDENT>if selector.flags & RANGES and not self.match_range(el, selector.flags & RANGES):<EOL><INDENT>continue<EOL><DEDENT>if selector.lang and not self.match_lang(el, selector.lang):<EOL><INDENT>continue<EOL><DEDENT>if selector.selectors and not self.match_subselectors(el, selector.selectors):<EOL><INDENT>continue<EOL><DEDENT>if selector.relation and not self.match_relations(el, selector.relation):<EOL><INDENT>continue<EOL><DEDENT>if selector.flags & ct.SEL_DEFAULT and not self.match_default(el):<EOL><INDENT>continue<EOL><DEDENT>if selector.flags & ct.SEL_INDETERMINATE and not self.match_indeterminate(el):<EOL><INDENT>continue<EOL><DEDENT>if selector.flags & DIR_FLAGS and not self.match_dir(el, selector.flags & DIR_FLAGS):<EOL><INDENT>continue<EOL><DEDENT>if not self.match_contains(el, selector.contains):<EOL><INDENT>continue<EOL><DEDENT>match = not is_not<EOL>break<EOL><DEDENT><DEDENT>if is_html:<EOL><INDENT>self.namespaces = namespaces<EOL>self.iframe_restrict = iframe_restrict<EOL><DEDENT>return match<EOL> | Check if element matches one of the selectors. | f13616:c3:m31 |
def select(self, limit=<NUM_LIT:0>): | if limit < <NUM_LIT:1>:<EOL><INDENT>limit = None<EOL><DEDENT>for child in self.get_descendants(self.tag):<EOL><INDENT>if self.match(child):<EOL><INDENT>yield child<EOL>if limit is not None:<EOL><INDENT>limit -= <NUM_LIT:1><EOL>if limit < <NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Match all tags under the targeted tag. | f13616:c3:m32 |
def closest(self): | current = self.tag<EOL>closest = None<EOL>while closest is None and current is not None:<EOL><INDENT>if self.match(current):<EOL><INDENT>closest = current<EOL><DEDENT>else:<EOL><INDENT>current = self.get_parent(current)<EOL><DEDENT><DEDENT>return closest<EOL> | Match closest ancestor. | f13616:c3:m33 |
def filter(self): | return [tag for tag in self.get_contents(self.tag) if not self.is_navigable_string(tag) and self.match(tag)]<EOL> | Filter tag's children. | f13616:c3:m34 |
def match(self, el): | return not self.is_doc(el) and self.is_tag(el) and self.match_selectors(el, self.selectors)<EOL> | Match. | f13616:c3:m35 |
def __init__(self, el): | self.assert_valid_input(el)<EOL>self.tag = el<EOL> | Initialize. | f13616:c4:m0 |
def get_comments(self, limit=<NUM_LIT:0>): | if limit < <NUM_LIT:1>:<EOL><INDENT>limit = None<EOL><DEDENT>for child in self.get_descendants(self.tag, tags=False):<EOL><INDENT>if self.is_comment(child):<EOL><INDENT>yield child<EOL>if limit is not None:<EOL><INDENT>limit -= <NUM_LIT:1><EOL>if limit < <NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Get comments. | f13616:c4:m1 |
def __init__(self, pattern, selectors, namespaces, custom, flags): | super(SoupSieve, self).__init__(<EOL>pattern=pattern,<EOL>selectors=selectors,<EOL>namespaces=namespaces,<EOL>custom=custom,<EOL>flags=flags<EOL>)<EOL> | Initialize. | f13616:c5:m0 |
def match(self, tag): | return CSSMatch(self.selectors, tag, self.namespaces, self.flags).match(tag)<EOL> | Match. | f13616:c5:m1 |
def closest(self, tag): | return CSSMatch(self.selectors, tag, self.namespaces, self.flags).closest()<EOL> | Match closest ancestor. | f13616:c5:m2 |
def filter(self, iterable): | if CSSMatch.is_tag(iterable):<EOL><INDENT>return CSSMatch(self.selectors, iterable, self.namespaces, self.flags).filter()<EOL><DEDENT>else:<EOL><INDENT>return [node for node in iterable if not CSSMatch.is_navigable_string(node) and self.match(node)]<EOL><DEDENT> | Filter.
`CSSMatch` can cache certain searches for tags of the same document,
so if we are given a tag, all tags are from the same document,
and we can take advantage of the optimization.
Any other kind of iterable could have tags from different documents or detached tags,
so for those, we use a new `CSSMatch` for each item in the iterable. | f13616:c5:m3 |
@util.deprecated("<STR_LIT>")<EOL><INDENT>def comments(self, tag, limit=<NUM_LIT:0>):<DEDENT> | return [comment for comment in CommentsMatch(tag).get_comments(limit)]<EOL> | Get comments only. | f13616:c5:m4 |
@util.deprecated("<STR_LIT>")<EOL><INDENT>def icomments(self, tag, limit=<NUM_LIT:0>):<DEDENT> | for comment in CommentsMatch(tag).get_comments(limit):<EOL><INDENT>yield comment<EOL><DEDENT> | Iterate comments only. | f13616:c5:m5 |
def select_one(self, tag): | tags = self.select(tag, limit=<NUM_LIT:1>)<EOL>return tags[<NUM_LIT:0>] if tags else None<EOL> | Select a single tag. | f13616:c5:m6 |
def select(self, tag, limit=<NUM_LIT:0>): | return list(self.iselect(tag, limit))<EOL> | Select the specified tags. | f13616:c5:m7 |
def iselect(self, tag, limit=<NUM_LIT:0>): | for el in CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit):<EOL><INDENT>yield el<EOL><DEDENT> | Iterate the specified tags. | f13616:c5:m8 |
def __repr__(self): | return "<STR_LIT>".format(<EOL>self.pattern,<EOL>self.namespaces,<EOL>self.custom,<EOL>self.flags<EOL>)<EOL> | Representation. | f13616:c5:m9 |
def get_version(): | path = os.path.join(os.path.dirname(__file__), '<STR_LIT>')<EOL>fp, pathname, desc = imp.find_module('<STR_LIT>', [path])<EOL>try:<EOL><INDENT>meta = imp.load_module('<STR_LIT>', fp, pathname, desc)<EOL>return meta.__version__, meta.__version_info__._get_dev_status()<EOL><DEDENT>finally:<EOL><INDENT>fp.close()<EOL><DEDENT> | Get version and version_info without importing the entire module. | f13617:m0 |
def get_requirements(): | with open("<STR_LIT>") as f:<EOL><INDENT>requirements = []<EOL>for line in f.readlines():<EOL><INDENT>line = line.strip()<EOL>if line and not line.startswith('<STR_LIT:#>'):<EOL><INDENT>requirements.append(line)<EOL><DEDENT><DEDENT><DEDENT>return requirements<EOL> | Get the dependencies. | f13617:m1 |
def get_description(): | with open("<STR_LIT>", '<STR_LIT:r>') as f:<EOL><INDENT>desc = f.read()<EOL><DEDENT>return desc<EOL> | Get long description. | f13617:m2 |
def rndstr(size=<NUM_LIT:16>): | _basech = string.ascii_letters + string.digits<EOL>return "<STR_LIT>".join([rnd.choice(_basech) for _ in range(size)])<EOL> | Returns a string of random ascii characters or digits
:param size: The length of the string
:return: string | f13619:m0 |
def unpack(self, token, **kwargs): | if isinstance(token, str):<EOL><INDENT>try:<EOL><INDENT>token = token.encode("<STR_LIT:utf-8>")<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>part = split_token(token)<EOL>self.b64part = part<EOL>self.part = [b64d(p) for p in part]<EOL>self.headers = json.loads(as_unicode(self.part[<NUM_LIT:0>]))<EOL>for key,val in kwargs.items():<EOL><INDENT>if not val and key in self.headers:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>_ok = self.verify_header(key,val)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>if not _ok:<EOL><INDENT>raise HeaderError(<EOL>'<STR_LIT>'.format(<EOL>key, val, self.headers[key]))<EOL><DEDENT><DEDENT><DEDENT>return self<EOL> | Unpacks a JWT into its parts and base64 decodes the parts
individually
:param token: The JWT
:param kwargs: A possible empty set of claims to verify the header
against. | f13630:c0:m1 |
def pack(self, parts=None, headers=None): | if not headers:<EOL><INDENT>if self.headers:<EOL><INDENT>headers = self.headers<EOL><DEDENT>else:<EOL><INDENT>headers = {'<STR_LIT>': '<STR_LIT:none>'}<EOL><DEDENT><DEDENT>logging.debug('<STR_LIT>'.format(headers))<EOL>if not parts:<EOL><INDENT>return "<STR_LIT:.>".join([a.decode() for a in self.b64part])<EOL><DEDENT>self.part = [headers] + parts<EOL>_all = self.b64part = [b64encode_item(headers)]<EOL>_all.extend([b64encode_item(p) for p in parts])<EOL>return "<STR_LIT:.>".join([a.decode() for a in _all])<EOL> | Packs components into a JWT
:param parts: List of parts to pack
:param headers: The JWT headers
:return: | f13630:c0:m2 |
def payload(self): | _msg = as_unicode(self.part[<NUM_LIT:1>])<EOL>if "<STR_LIT>" in self.headers and self.headers["<STR_LIT>"].lower() != "<STR_LIT>":<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>_msg = json.loads(_msg)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return _msg<EOL> | Picks out the payload from the different parts of the signed/encrypted
JSON Web Token. If the content type is said to be 'jwt' deserialize the
payload into a Python object otherwise return as-is.
:return: The payload | f13630:c0:m3 |
def verify_header(self, key, val): | if isinstance(val, list):<EOL><INDENT>if self.headers[key] in val:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self.headers[key] == val:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT> | Check that a particular header claim is present and has a specific value
:param key: The claim
:param val: The value of the claim
:raises: KeyError if the claim is not present in the header
:return: True if the claim exists in the header and has the prescribed
value | f13630:c0:m4 |
def verify_headers(self, check_presence=True, **kwargs): | for key, val in kwargs.items():<EOL><INDENT>try:<EOL><INDENT>_ok = self.verify_header(key, val)<EOL><DEDENT>except KeyError:<EOL><INDENT>if check_presence:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not _ok:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL> | Check that a set of particular header claim are present and has
specific values
:param kwargs: The claim/value sets as a dictionary
:return: True if the claim that appears in the header has the
prescribed values. If a claim is not present in the header and
check_presence is True then False is returned. | f13630:c0:m5 |
def build_keyjar(key_conf, kid_template="<STR_LIT>", keyjar=None, owner='<STR_LIT>'): | if keyjar is None:<EOL><INDENT>keyjar = KeyJar()<EOL><DEDENT>tot_kb = build_key_bundle(key_conf, kid_template)<EOL>keyjar.add_kb(owner, tot_kb)<EOL>return keyjar<EOL> | Builds a :py:class:`oidcmsg.key_jar.KeyJar` instance or adds keys to
an existing KeyJar based on a key specification.
An example of such a specification::
keys = [
{"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]},
{"type": "EC", "crv": "P-256", "use": ["sig"], "kid": "ec.1"},
{"type": "EC", "crv": "P-256", "use": ["enc"], "kid": "ec.2"}
]
Keys in this specification are:
type
The type of key. Presently only 'rsa' and 'ec' supported.
key
A name of a file where a key can be found. Only works with PEM encoded
RSA keys
use
What the key should be used for
crv
The elliptic curve that should be used. Only applies to elliptic curve
keys :-)
kid
Key ID, can only be used with one usage type is specified. If there
are more the one usage type specified 'kid' will just be ignored.
:param key_conf: The key configuration
:param kid_template: A template by which to build the key IDs. If no
kid_template is given then the built-in function add_kid() will be used.
:param keyjar: If an KeyJar instance the new keys are added to this key jar.
:param owner: The default owner of the keys in the key jar.
:return: A KeyJar instance | f13631:m0 |
def update_keyjar(keyjar): | for iss, kbl in keyjar.items():<EOL><INDENT>for kb in kbl:<EOL><INDENT>kb.update()<EOL><DEDENT><DEDENT> | Go through the whole key jar, key bundle by key bundle and update them one
by one.
:param keyjar: The key jar to update | f13631:m1 |
def key_summary(keyjar, issuer): | try:<EOL><INDENT>kbl = keyjar[issuer]<EOL><DEDENT>except KeyError:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>key_list = []<EOL>for kb in kbl:<EOL><INDENT>for key in kb.keys():<EOL><INDENT>if key.inactive_since:<EOL><INDENT>key_list.append(<EOL>'<STR_LIT>'.format(key.kty, key.use, key.kid))<EOL><DEDENT>else:<EOL><INDENT>key_list.append(<EOL>'<STR_LIT>'.format(key.kty, key.use, key.kid))<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT:U+002CU+0020>'.join(key_list)<EOL><DEDENT> | Return a text representation of the keyjar.
:param keyjar: A :py:class:`oidcmsg.key_jar.KeyJar` instance
:param issuer: Which key owner that we are looking at
:return: A text representation of the keys | f13631:m2 |
def init_key_jar(public_path='<STR_LIT>', private_path='<STR_LIT>', key_defs='<STR_LIT>', owner='<STR_LIT>',<EOL>read_only=True): | if private_path:<EOL><INDENT>if os.path.isfile(private_path):<EOL><INDENT>_jwks = open(private_path, '<STR_LIT:r>').read()<EOL>_kj = KeyJar()<EOL>_kj.import_jwks(json.loads(_jwks), owner)<EOL>if key_defs:<EOL><INDENT>_kb = _kj.issuer_keys[owner][<NUM_LIT:0>]<EOL>_diff = key_diff(_kb, key_defs)<EOL>if _diff:<EOL><INDENT>if read_only:<EOL><INDENT>logger.error('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>update_key_bundle(_kb, _diff)<EOL>_kj.issuer_keys[owner] = [_kb]<EOL>jwks = _kj.export_jwks(private=True, issuer=owner)<EOL>fp = open(private_path, '<STR_LIT:w>')<EOL>fp.write(json.dumps(jwks))<EOL>fp.close()<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>_kj = build_keyjar(key_defs, owner=owner)<EOL>if not read_only:<EOL><INDENT>jwks = _kj.export_jwks(private=True, issuer=owner)<EOL>head, tail = os.path.split(private_path)<EOL>if head and not os.path.isdir(head):<EOL><INDENT>os.makedirs(head)<EOL><DEDENT>fp = open(private_path, '<STR_LIT:w>')<EOL>fp.write(json.dumps(jwks))<EOL>fp.close()<EOL><DEDENT><DEDENT>if public_path and not read_only:<EOL><INDENT>jwks = _kj.export_jwks(issuer=owner) <EOL>head, tail = os.path.split(public_path)<EOL>if head and not os.path.isdir(head):<EOL><INDENT>os.makedirs(head)<EOL><DEDENT>fp = open(public_path, '<STR_LIT:w>')<EOL>fp.write(json.dumps(jwks))<EOL>fp.close()<EOL><DEDENT><DEDENT>elif public_path:<EOL><INDENT>if os.path.isfile(public_path):<EOL><INDENT>_jwks = open(public_path, '<STR_LIT:r>').read()<EOL>_kj = KeyJar()<EOL>_kj.import_jwks(json.loads(_jwks), owner)<EOL>if key_defs:<EOL><INDENT>_kb = _kj.issuer_keys[owner][<NUM_LIT:0>]<EOL>_diff = key_diff(_kb, key_defs)<EOL>if _diff:<EOL><INDENT>if read_only:<EOL><INDENT>logger.error('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>update_key_bundle(_kb, _diff)<EOL>_kj.issuer_keys[owner] = [_kb]<EOL>jwks = _kj.export_jwks(issuer=owner)<EOL>fp = open(private_path, '<STR_LIT:w>')<EOL>fp.write(json.dumps(jwks))<EOL>fp.close()<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>_kj = build_keyjar(key_defs, owner=owner)<EOL>if not read_only:<EOL><INDENT>_jwks = _kj.export_jwks(issuer=owner)<EOL>head, tail = os.path.split(public_path)<EOL>if head and not os.path.isdir(head):<EOL><INDENT>os.makedirs(head)<EOL><DEDENT>fp = open(public_path, '<STR_LIT:w>')<EOL>fp.write(json.dumps(_jwks))<EOL>fp.close()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>_kj = build_keyjar(key_defs, owner=owner)<EOL><DEDENT>return _kj<EOL> | A number of cases here:
1. A private path is given
a. The file exists and a JWKS is found there.
From that JWKS a KeyJar instance is built.
b.
If the private path file doesn't exit the key definitions are
used to build a KeyJar instance. A JWKS with the private keys are
written to the file named in private_path.
If a public path is also provided a JWKS with public keys are written
to that file.
2. A public path is given but no private path.
a. If the public path file exists then the JWKS in that file is used to
construct a KeyJar.
b. If no such file exists then a KeyJar will be built
based on the key_defs specification and a JWKS with the public keys
will be written to the public path file.
3. If neither a public path nor a private path is given then a KeyJar is
built based on the key_defs specification and no JWKS will be written
to file.
In all cases a KeyJar instance is returned
The keys stored in the KeyJar will be stored under the '' identifier.
:param public_path: A file path to a file that contains a JWKS with public
keys
:param private_path: A file path to a file that contains a JWKS with
private keys.
:param key_defs: A definition of what keys should be created if they are
not already available
:param owner: The owner of the keys
:param read_only: This function should not attempt to write anything
to a file system.
:return: An instantiated :py:class;`oidcmsg.key_jar.KeyJar` instance | f13631:m3 |
def __init__(self, ca_certs=None, verify_ssl=True, keybundle_cls=KeyBundle,<EOL>remove_after=<NUM_LIT>, httpc=None): | self.spec2key = {}<EOL>self.issuer_keys = {}<EOL>self.ca_certs = ca_certs<EOL>self.verify_ssl = verify_ssl<EOL>self.keybundle_cls = keybundle_cls<EOL>self.remove_after = remove_after<EOL>self.httpc = httpc or request<EOL> | KeyJar init function
:param ca_certs: CA certificates, to be used for HTTPS
:param verify_ssl: Attempting SSL certificate verification
:return: Keyjar instance | f13631:c3:m0 |
def add_url(self, issuer, url, **kwargs): | if not url:<EOL><INDENT>raise KeyError("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in url or "<STR_LIT>" in url:<EOL><INDENT>kb = self.keybundle_cls(source=url, verify_ssl=False,<EOL>httpc=self.httpc, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>kb = self.keybundle_cls(source=url, verify_ssl=self.verify_ssl,<EOL>httpc=self.httpc, **kwargs)<EOL><DEDENT>kb.update()<EOL>self.add_kb(issuer, kb)<EOL>return kb<EOL> | Add a set of keys by url. This method will create a
:py:class:`oidcmsg.key_bundle.KeyBundle` instance with the
url as source specification. If no file format is given it's assumed
that what's on the other side is a JWKS.
:param issuer: Who issued the keys
:param url: Where can the key/-s be found
:param kwargs: extra parameters for instantiating KeyBundle
:return: A :py:class:`oidcmsg.oauth2.keybundle.KeyBundle` instance | f13631:c3:m2 |
def add_symmetric(self, issuer, key, usage=None): | if issuer not in self.issuer_keys:<EOL><INDENT>self.issuer_keys[issuer] = []<EOL><DEDENT>if usage is None:<EOL><INDENT>self.issuer_keys[issuer].append(<EOL>self.keybundle_cls([{"<STR_LIT>": "<STR_LIT>", "<STR_LIT:key>": key}]))<EOL><DEDENT>else:<EOL><INDENT>for use in usage:<EOL><INDENT>self.issuer_keys[issuer].append(<EOL>self.keybundle_cls([{"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT:key>": key,<EOL>"<STR_LIT>": use}]))<EOL><DEDENT><DEDENT> | Add a symmetric key. This is done by wrapping it in a key bundle
cloak since KeyJar does not handle keys directly but only through
key bundles.
:param issuer: Owner of the key
:param key: The key
:param usage: What the key can be used for signing/signature
verification (sig) and/or encryption/decryption (enc) | f13631:c3:m3 |
def add_kb(self, issuer, kb): | try:<EOL><INDENT>self.issuer_keys[issuer].append(kb)<EOL><DEDENT>except KeyError:<EOL><INDENT>self.issuer_keys[issuer] = [kb]<EOL><DEDENT> | Add a key bundle and bind it to an identifier
:param issuer: Owner of the keys in the key bundle
:param kb: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance | f13631:c3:m4 |
def __setitem__(self, issuer, val): | if not isinstance(val, list):<EOL><INDENT>val = [val]<EOL><DEDENT>for kb in val:<EOL><INDENT>if not isinstance(kb, KeyBundle):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(kb))<EOL><DEDENT><DEDENT>self.issuer_keys[issuer] = val<EOL> | Bind one or a list of key bundles to a special identifier.
Will overwrite whatever was there before !!
:param issuer: The owner of the keys in the key bundle/-s
:param val: A single or a list of KeyBundle instance | f13631:c3:m5 |
def items(self): | return self.issuer_keys.items()<EOL> | Get all owner ID's and their key bundles
:return: list of 2-tuples (Owner ID., list of KeyBundles) | f13631:c3:m6 |
def get(self, key_use, key_type="<STR_LIT>", owner="<STR_LIT>", kid=None, **kwargs): | if key_use in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>use = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>use = "<STR_LIT>"<EOL><DEDENT>_kj = None<EOL>if owner != "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>_kj = self.issuer_keys[owner]<EOL><DEDENT>except KeyError:<EOL><INDENT>if owner.endswith("<STR_LIT:/>"):<EOL><INDENT>try:<EOL><INDENT>_kj = self.issuer_keys[owner[:-<NUM_LIT:1>]]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>_kj = self.issuer_keys[owner + "<STR_LIT:/>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>_kj = self.issuer_keys[owner]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if _kj is None:<EOL><INDENT>return []<EOL><DEDENT>lst = []<EOL>for bundle in _kj:<EOL><INDENT>if key_type:<EOL><INDENT>if key_use in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>_bkeys = bundle.get(key_type, only_active=False)<EOL><DEDENT>else:<EOL><INDENT>_bkeys = bundle.get(key_type)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_bkeys = bundle.keys()<EOL><DEDENT>for key in _bkeys:<EOL><INDENT>if key.inactive_since and key_use != "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>if not key.use or use == key.use:<EOL><INDENT>if kid:<EOL><INDENT>if key.kid == kid:<EOL><INDENT>lst.append(key)<EOL>break<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>lst.append(key)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if key_type == "<STR_LIT>" and "<STR_LIT>" in kwargs:<EOL><INDENT>name = "<STR_LIT>".format(kwargs["<STR_LIT>"][<NUM_LIT:2>:]) <EOL>_lst = []<EOL>for key in lst:<EOL><INDENT>if name != key.crv:<EOL><INDENT>continue<EOL><DEDENT>_lst.append(key)<EOL><DEDENT>lst = _lst<EOL><DEDENT>if use == '<STR_LIT>' and key_type == '<STR_LIT>' and owner != '<STR_LIT>':<EOL><INDENT>for kb in self.issuer_keys['<STR_LIT>']:<EOL><INDENT>for key in kb.get(key_type):<EOL><INDENT>if key.inactive_since:<EOL><INDENT>continue<EOL><DEDENT>if not key.use or key.use == use:<EOL><INDENT>lst.append(key)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return lst<EOL> | Get all keys that matches a set of search criteria
:param key_use: A key useful for this usage (enc, dec, sig, ver)
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:return: A possibly empty list of keys | f13631:c3:m7 |
def get_signing_key(self, key_type="<STR_LIT>", owner="<STR_LIT>", kid=None, **kwargs): | return self.get("<STR_LIT>", key_type, owner, kid, **kwargs)<EOL> | Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:param kwargs: Extra key word arguments
:return: A possibly empty list of keys | f13631:c3:m8 |
def keys_by_alg_and_usage(self, issuer, alg, usage): | if usage in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>ktype = jws_alg2keytype(alg)<EOL><DEDENT>else:<EOL><INDENT>ktype = jwe_alg2keytype(alg)<EOL><DEDENT>return self.get(usage, ktype, issuer)<EOL> | Find all keys that can be used for a specific crypto algorithm and
usage by key owner.
:param issuer: Key owner
:param alg: a crypto algorithm
:param usage: What the key should be used for
:return: A possibly empty list of keys | f13631:c3:m12 |
def get_issuer_keys(self, issuer): | res = []<EOL>for kbl in self.issuer_keys[issuer]:<EOL><INDENT>res.extend(kbl.keys())<EOL><DEDENT>return res<EOL> | Get all the keys that belong to an entity.
:param issuer: The entity ID
:return: A possibly empty list of keys | f13631:c3:m13 |
def __getitem__(self, owner='<STR_LIT>'): | try:<EOL><INDENT>return self.issuer_keys[owner]<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.debug(<EOL>"<STR_LIT>".format(<EOL>owner, list(self.issuer_keys.keys())))<EOL>raise<EOL><DEDENT> | Get all the key bundles that belong to an entity.
:param owner: The entity ID
:return: A possibly empty list of key bundles | f13631:c3:m15 |
def owners(self): | return list(self.issuer_keys.keys())<EOL> | Return a list of all the entities that has keys in this key jar.
:return: A list of entity IDs | f13631:c3:m16 |
def match_owner(self, url): | for owner in self.issuer_keys.keys():<EOL><INDENT>if owner.startswith(url):<EOL><INDENT>return owner<EOL><DEDENT><DEDENT>raise KeyError("<STR_LIT>".format(url))<EOL> | Finds the first entity, with keys in the key jar, with an
identifier that matches the given URL. The match is a leading
substring match.
:param url: A URL
:return: An issue entity ID that exists in the Key jar | f13631:c3:m17 |
def load_keys(self, issuer, jwks_uri='<STR_LIT>', jwks=None, replace=False): | logger.debug("<STR_LIT>" % issuer)<EOL>if replace or issuer not in self.issuer_keys:<EOL><INDENT>self.issuer_keys[issuer] = []<EOL><DEDENT>if jwks_uri:<EOL><INDENT>self.add_url(issuer, jwks_uri)<EOL><DEDENT>elif jwks:<EOL><INDENT>_keys = jwks['<STR_LIT>']<EOL>self.issuer_keys[issuer].append(self.keybundle_cls(_keys))<EOL><DEDENT> | Fetch keys from another server
:param jwks_uri: A URL pointing to a site that will return a JWKS
:param jwks: A dictionary representation of a JWKS
:param issuer: The provider URL
:param replace: If all previously gathered keys from this provider
should be replace.
:return: Dictionary with usage as key and keys as values | f13631:c3:m19 |
def find(self, source, issuer): | try:<EOL><INDENT>for kb in self.issuer_keys[issuer]:<EOL><INDENT>if kb.source == source:<EOL><INDENT>return kb<EOL><DEDENT><DEDENT><DEDENT>except KeyError:<EOL><INDENT>return None<EOL><DEDENT>return None<EOL> | Find a key bundle based on the source of the keys
:param source: A source url
:param issuer: The issuer of keys
:return: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance or None | f13631:c3:m20 |
def export_jwks(self, private=False, issuer="<STR_LIT>"): | keys = []<EOL>for kb in self.issuer_keys[issuer]:<EOL><INDENT>keys.extend([k.serialize(private) for k in kb.keys() if<EOL>k.inactive_since == <NUM_LIT:0>])<EOL><DEDENT>return {"<STR_LIT>": keys}<EOL> | Produces a dictionary that later can be easily mapped into a
JSON string representing a JWKS.
:param private: Whether it should be the private keys or the public
:param issuer: The entity ID.
:return: A dictionary with one key: 'keys' | f13631:c3:m21 |
def export_jwks_as_json(self, private=False, issuer="<STR_LIT>"): | return json.dumps(self.export_jwks(private, issuer))<EOL> | Export a JWKS as a JSON document.
:param private: Whether it should be the private keys or the public
:param issuer: The entity ID.
:return: A JSON representation of a JWKS | f13631:c3:m22 |
def import_jwks(self, jwks, issuer): | try:<EOL><INDENT>_keys = jwks["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>self.issuer_keys[issuer].append(<EOL>self.keybundle_cls(_keys, verify_ssl=self.verify_ssl))<EOL><DEDENT>except KeyError:<EOL><INDENT>self.issuer_keys[issuer] = [self.keybundle_cls(<EOL>_keys, verify_ssl=self.verify_ssl)]<EOL><DEDENT><DEDENT> | Imports all the keys that are represented in a JWKS
:param jwks: Dictionary representation of a JWKS
:param issuer: Who 'owns' the JWKS | f13631:c3:m23 |
def import_jwks_as_json(self, jwks, issuer): | return self.import_jwks(json.loads(jwks), issuer)<EOL> | Imports all the keys that are represented in a JWKS expressed as a
JSON object
:param jwks: JSON representation of a JWKS
:param issuer: Who 'owns' the JWKS | f13631:c3:m24 |
def remove_outdated(self, when=<NUM_LIT:0>): | for iss in list(self.owners()):<EOL><INDENT>_kbl = []<EOL>for kb in self.issuer_keys[iss]:<EOL><INDENT>kb.remove_outdated(self.remove_after, when=when)<EOL>if len(kb):<EOL><INDENT>_kbl.append(kb)<EOL><DEDENT><DEDENT>if _kbl:<EOL><INDENT>self.issuer_keys[iss] = _kbl<EOL><DEDENT>else:<EOL><INDENT>del self.issuer_keys[iss]<EOL><DEDENT><DEDENT> | Goes through the complete list of issuers and for each of them removes
outdated keys.
Outdated keys are keys that has been marked as inactive at a time that
is longer ago then some set number of seconds (when). If when=0 the
the base time is set to now.
The number of seconds a carried in the remove_after parameter in the
key jar.
:param when: To facilitate testing | f13631:c3:m27 |
def get_jwt_decrypt_keys(self, jwt, **kwargs): | try:<EOL><INDENT>_key_type = jwe_alg2keytype(jwt.headers['<STR_LIT>'])<EOL><DEDENT>except KeyError:<EOL><INDENT>_key_type = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>_kid = jwt.headers['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.info('<STR_LIT>')<EOL>_kid = '<STR_LIT>'<EOL><DEDENT>keys = self.get(key_use='<STR_LIT>', owner='<STR_LIT>', key_type=_key_type)<EOL>try:<EOL><INDENT>_aud = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>_aud = '<STR_LIT>'<EOL><DEDENT>if _aud:<EOL><INDENT>try:<EOL><INDENT>allow_missing_kid = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>allow_missing_kid = False<EOL><DEDENT>try:<EOL><INDENT>nki = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>nki = {}<EOL><DEDENT>keys = self._add_key(keys, _aud, '<STR_LIT>', _key_type, _kid, nki,<EOL>allow_missing_kid)<EOL><DEDENT>keys = [k for k in keys if k.appropriate_for('<STR_LIT>')]<EOL>return keys<EOL> | Get decryption keys from this keyjar based on information carried
in a JWE. These keys should be usable to decrypt an encrypted JWT.
:param jwt: A cryptojwt.jwt.JWT instance
:param kwargs: Other key word arguments
:return: list of usable keys | f13631:c3:m29 |
def get_jwt_verify_keys(self, jwt, **kwargs): | try:<EOL><INDENT>allow_missing_kid = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>allow_missing_kid = False<EOL><DEDENT>try:<EOL><INDENT>_key_type = jws_alg2keytype(jwt.headers['<STR_LIT>'])<EOL><DEDENT>except KeyError:<EOL><INDENT>_key_type = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>_kid = jwt.headers['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.info('<STR_LIT>')<EOL>_kid = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>nki = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>nki = {}<EOL><DEDENT>_payload = jwt.payload()<EOL>try:<EOL><INDENT>_iss = _payload['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>try:<EOL><INDENT>_iss = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>_iss = '<STR_LIT>'<EOL><DEDENT><DEDENT>if _iss:<EOL><INDENT>if "<STR_LIT>" in jwt.headers and _iss:<EOL><INDENT>if not self.find(jwt.headers["<STR_LIT>"], _iss):<EOL><INDENT>try:<EOL><INDENT>if kwargs["<STR_LIT>"]:<EOL><INDENT>self.add_url(_iss, jwt.headers["<STR_LIT>"])<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>keys = self._add_key([], _iss, '<STR_LIT>', _key_type,<EOL>_kid, nki, allow_missing_kid)<EOL>if _key_type == '<STR_LIT>':<EOL><INDENT>keys.extend(self.get(key_use='<STR_LIT>', owner='<STR_LIT>',<EOL>key_type=_key_type))<EOL><DEDENT><DEDENT>else: <EOL><INDENT>keys = self.get(key_use='<STR_LIT>', owner='<STR_LIT>', key_type=_key_type)<EOL><DEDENT>keys = [k for k in keys if k.appropriate_for('<STR_LIT>')]<EOL>return keys<EOL> | Get keys from this key jar based on information in a JWS. These keys
should be usable to verify the signed JWT.
:param jwt: A cryptojwt.jwt.JWT instance
:param kwargs: Other key word arguments
:return: list of usable keys | f13631:c3:m30 |
def copy(self): | kj = KeyJar()<EOL>for issuer in self.owners():<EOL><INDENT>kj[issuer] = [kb.copy() for kb in self[issuer]]<EOL><DEDENT>kj.verify_ssl = self.verify_ssl<EOL>return kj<EOL> | Make deep copy of this key jar.
:return: A :py:class:`oidcmsg.key_jar.KeyJar` instance | f13631:c3:m31 |
def utc_time_sans_frac(): | return int((datetime.utcnow() - datetime(<NUM_LIT>, <NUM_LIT:1>, <NUM_LIT:1>)).total_seconds())<EOL> | Produces UTC time without fractions
:return: A number of seconds | f13632:m0 |
def pick_key(keys, use, alg='<STR_LIT>', key_type='<STR_LIT>', kid='<STR_LIT>'): | res = []<EOL>if not key_type:<EOL><INDENT>if use == '<STR_LIT>':<EOL><INDENT>key_type = jws_alg2keytype(alg)<EOL><DEDENT>else:<EOL><INDENT>key_type = jwe_alg2keytype(alg)<EOL><DEDENT><DEDENT>for key in keys:<EOL><INDENT>if key.use and key.use != use:<EOL><INDENT>continue<EOL><DEDENT>if key.kty == key_type:<EOL><INDENT>if key.kid and kid:<EOL><INDENT>if key.kid == kid:<EOL><INDENT>res.append(key)<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if key.alg == '<STR_LIT>':<EOL><INDENT>if alg:<EOL><INDENT>if key_type == '<STR_LIT>':<EOL><INDENT>if key.crv == '<STR_LIT>'.format(alg[<NUM_LIT:2>:]):<EOL><INDENT>res.append(key)<EOL><DEDENT>continue<EOL><DEDENT><DEDENT>res.append(key)<EOL><DEDENT>elif alg and key.alg == alg:<EOL><INDENT>res.append(key)<EOL><DEDENT>else:<EOL><INDENT>res.append(key)<EOL><DEDENT><DEDENT><DEDENT>return res<EOL> | Based on given criteria pick out the keys that fulfill them from a
given set of keys.
:param keys: List of keys. These are :py:class:`cryptojwt.jwk.JWK`
instances.
:param use: What the key is going to be used for 'sig'/'enc'
:param alg: crypto algorithm
:param key_type: Type of key 'rsa'/'ec'/'oct'
:param kid: Key ID
:return: A list of keys that match the pattern | f13632:m1 |
def receivers(self): | return self.key_jar.owners<EOL> | Return a dictionary
:return: | f13632:c0:m2 |
@staticmethod<EOL><INDENT>def put_together_aud(recv, aud=None):<DEDENT> | if aud:<EOL><INDENT>if recv and recv not in aud:<EOL><INDENT>_aud = [recv]<EOL>_aud.extend(aud)<EOL><DEDENT>else:<EOL><INDENT>_aud = aud<EOL><DEDENT><DEDENT>elif recv:<EOL><INDENT>_aud = [recv]<EOL><DEDENT>else:<EOL><INDENT>_aud = []<EOL><DEDENT>return _aud<EOL> | :param recv: The intended receiver
:param aud: A list of entity identifiers (the audience)
:return: A possibly extended audience set | f13632:c0:m5 |
def pack_init(self, recv, aud): | argv = {'<STR_LIT>': self.iss, '<STR_LIT>': utc_time_sans_frac()}<EOL>if self.lifetime:<EOL><INDENT>argv['<STR_LIT>'] = argv['<STR_LIT>'] + self.lifetime<EOL><DEDENT>_aud = self.put_together_aud(recv, aud)<EOL>if _aud:<EOL><INDENT>argv['<STR_LIT>'] = _aud<EOL><DEDENT>return argv<EOL> | Gather initial information for the payload.
:return: A dictionary with claims and values | f13632:c0:m6 |
def pack_key(self, owner_id='<STR_LIT>', kid='<STR_LIT>'): | keys = pick_key(self.my_keys(owner_id, '<STR_LIT>'), '<STR_LIT>', alg=self.alg,<EOL>kid=kid)<EOL>if not keys:<EOL><INDENT>raise NoSuitableSigningKeys('<STR_LIT>'.format(kid))<EOL><DEDENT>return keys[<NUM_LIT:0>]<EOL> | Find a key to be used for signing the Json Web Token
:param owner_id: Owner of the keys to chose from
:param kid: Key ID
:return: One key | f13632:c0:m7 |
def pack(self, payload=None, kid='<STR_LIT>', owner='<STR_LIT>', recv='<STR_LIT>', aud=None, **kwargs): | _args = {}<EOL>if payload is not None:<EOL><INDENT>_args.update(payload)<EOL><DEDENT>_args.update(self.pack_init(recv, aud))<EOL>try:<EOL><INDENT>_encrypt = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>_encrypt = self.encrypt<EOL><DEDENT>else:<EOL><INDENT>del kwargs['<STR_LIT>']<EOL><DEDENT>if self.with_jti:<EOL><INDENT>try:<EOL><INDENT>_jti = kwargs['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>_jti = uuid.uuid4().hex<EOL><DEDENT>_args['<STR_LIT>'] = _jti<EOL><DEDENT>if not owner and self.iss:<EOL><INDENT>owner = self.iss<EOL><DEDENT>if self.sign:<EOL><INDENT>if self.alg != '<STR_LIT:none>':<EOL><INDENT>_key = self.pack_key(owner, kid)<EOL>_args['<STR_LIT>'] = _key.kid<EOL><DEDENT>else:<EOL><INDENT>_key = None<EOL><DEDENT>_jws = JWS(json.dumps(_args), alg=self.alg)<EOL>_sjwt = _jws.sign_compact([_key])<EOL><DEDENT>else:<EOL><INDENT>_sjwt = json.dumps(_args)<EOL><DEDENT>if _encrypt:<EOL><INDENT>if not self.sign:<EOL><INDENT>return self._encrypt(_sjwt, recv, cty='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return self._encrypt(_sjwt, recv)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return _sjwt<EOL><DEDENT> | :param payload: Information to be carried as payload in the JWT
:param kid: Key ID
:param owner: The owner of the the keys that are to be used for signing
:param recv: The intended immediate receiver
:param aud: Intended audience for this JWS/JWE, not expected to
contain the recipient.
:param kwargs: Extra keyword arguments
:return: A signed or signed and encrypted JsonWebtoken | f13632:c0:m8 |
def _verify(self, rj, token): | keys = self.key_jar.get_jwt_verify_keys(rj.jwt)<EOL>return rj.verify_compact(token, keys)<EOL> | Verify a signed JSON Web Token
:param rj: A :py:class:`cryptojwt.jws.JWS` instance
:param token: The signed JSON Web Token
:return: A verified message | f13632:c0:m9 |
def _decrypt(self, rj, token): | if self.iss:<EOL><INDENT>keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt, aud=self.iss)<EOL><DEDENT>else:<EOL><INDENT>keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt)<EOL><DEDENT>return rj.decrypt(token, keys=keys)<EOL> | Decrypt an encrypted JsonWebToken
:param rj: :py:class:`cryptojwt.jwe.JWE` instance
:param token: The encrypted JsonWebToken
:return: | f13632:c0:m10 |
@staticmethod<EOL><INDENT>def verify_profile(msg_cls, info, **kwargs):<DEDENT> | _msg = msg_cls(**info)<EOL>if not _msg.verify(**kwargs):<EOL><INDENT>raise VerificationError()<EOL><DEDENT>return _msg<EOL> | If a message type is known for this JSON document. Verify that the
document complies with the message specifications.
:param msg_cls: The message class. A
:py:class:`oidcmsg.message.Message` instance
:param info: The information in the JSON document as a dictionary
:param kwargs: Extra keyword arguments used when doing the verification.
:return: The verified message as a msg_cls instance. | f13632:c0:m11 |
def unpack(self, token): | if not token:<EOL><INDENT>raise KeyError<EOL><DEDENT>_jwe_header = _jws_header = None<EOL>darg = {}<EOL>if self.allowed_enc_encs:<EOL><INDENT>darg['<STR_LIT>'] = self.allowed_enc_encs<EOL><DEDENT>if self.allowed_enc_algs:<EOL><INDENT>darg['<STR_LIT>'] = self.allowed_enc_algs<EOL><DEDENT>try:<EOL><INDENT>_decryptor = jwe_factory(token, **darg)<EOL><DEDENT>except (KeyError, HeaderError):<EOL><INDENT>_decryptor = None<EOL><DEDENT>if _decryptor:<EOL><INDENT>_info = self._decrypt(_decryptor, token)<EOL>_jwe_header = _decryptor.jwt.headers<EOL>try:<EOL><INDENT>_content_type = _decryptor.jwt.headers['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>_content_type = '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_content_type = '<STR_LIT>'<EOL>_info = token<EOL><DEDENT>if _content_type.lower() == '<STR_LIT>':<EOL><INDENT>if self.allowed_sign_algs:<EOL><INDENT>_verifier = jws_factory(_info, alg=self.allowed_sign_algs)<EOL><DEDENT>else:<EOL><INDENT>_verifier = jws_factory(_info)<EOL><DEDENT>if _verifier:<EOL><INDENT>_info = self._verify(_verifier, _info)<EOL><DEDENT>else:<EOL><INDENT>raise Exception()<EOL><DEDENT>_jws_header = _verifier.jwt.headers<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>_info = json.loads(_info)<EOL><DEDENT>except JSONDecodeError: <EOL><INDENT>return _info<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>_info = as_unicode(_info)<EOL>_info = json.loads(_info)<EOL><DEDENT>except JSONDecodeError: <EOL><INDENT>return _info<EOL><DEDENT><DEDENT><DEDENT>if self.msg_cls:<EOL><INDENT>_msg_cls = self.msg_cls<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>_msg_cls = self.iss2msg_cls[_info['<STR_LIT>']]<EOL><DEDENT>except KeyError:<EOL><INDENT>_msg_cls = None<EOL><DEDENT><DEDENT>if _msg_cls:<EOL><INDENT>vp_args = {'<STR_LIT>': self.skew}<EOL>if self.iss:<EOL><INDENT>vp_args['<STR_LIT>'] = self.iss<EOL><DEDENT>_info = self.verify_profile(_msg_cls, _info, **vp_args)<EOL>_info.jwe_header = _jwe_header<EOL>_info.jws_header = _jws_header<EOL>return _info<EOL><DEDENT>else:<EOL><INDENT>return _info<EOL><DEDENT> | Unpack a received signed or signed and encrypted Json Web Token
:param token: The Json Web Token
:return: If decryption and signature verification work the payload
will be returned as a Message instance if possible. | f13632:c0:m12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.