text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_discovery_service_request(url, entity_id, **kwargs): """ Created the HTTP redirect URL needed to send the user to the discovery service. :param url: The URL of the discovery service :param entity_id: The unique identifier of the service provider :param return: The discovery service MUST redirect the user agent to this location in response to this request :param policy: A parameter name used to indicate the desired behavior controlling the processing of the discovery service :param returnIDParam: A parameter name used to return the unique identifier of the selected identity provider to the original requester. :param isPassive: A boolean value True/False that controls whether the discovery service is allowed to visibly interact with the user agent. :return: A URL """
args = {"entityID": entity_id} for key in ["policy", "returnIDParam"]: try: args[key] = kwargs[key] except KeyError: pass try: args["return"] = kwargs["return_url"] except KeyError: try: args["return"] = kwargs["return"] except KeyError: pass if "isPassive" in kwargs: if kwargs["isPassive"]: args["isPassive"] = "true" else: args["isPassive"] = "false" params = urlencode(args) return "%s?%s" % (url, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_discovery_service_response(url="", query="", returnIDParam="entityID"): """ Deal with the response url from a Discovery Service :param url: the url the user was redirected back to or :param query: just the query part of the URL. :param returnIDParam: This is where the identifier of the IdP is place if it was specified in the query. Default is 'entityID' :return: The IdP identifier or "" if none was given """
if url: part = urlparse(url) qsd = parse_qs(part[4]) elif query: qsd = parse_qs(query) else: qsd = {} try: return qsd[returnIDParam][0] except KeyError: return ""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_on_demands(ava, required=None, optional=None): """ Never return more than is needed. Filters out everything the server is prepared to return but the receiver doesn't ask for :param ava: Attribute value assertion as a dictionary :param required: Required attributes :param optional: Optional attributes :return: The possibly reduced assertion """
# Is all what's required there: if required is None: required = {} lava = dict([(k.lower(), k) for k in ava.keys()]) for attr, vals in required.items(): attr = attr.lower() if attr in lava: if vals: for val in vals: if val not in ava[lava[attr]]: raise MissingValue( "Required attribute value missing: %s,%s" % (attr, val)) else: raise MissingValue("Required attribute missing: %s" % (attr,)) if optional is None: optional = {} oka = [k.lower() for k in required.keys()] oka.extend([k.lower() for k in optional.keys()]) # OK, so I can imaging releasing values that are not absolutely necessary # but not attributes that are not asked for. for attr in lava.keys(): if attr not in oka: del ava[lava[attr]] return ava
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_attribute_value_assertions(ava, attribute_restrictions=None): """ Will weed out attribute values and values according to the rules defined in the attribute restrictions. If filtering results in an attribute without values, then the attribute is removed from the assertion. :param ava: The incoming attribute value assertion (dictionary) :param attribute_restrictions: The rules that govern which attributes and values that are allowed. (dictionary) :return: The modified attribute value assertion """
if not attribute_restrictions: return ava for attr, vals in list(ava.items()): _attr = attr.lower() try: _rests = attribute_restrictions[_attr] except KeyError: del ava[attr] else: if _rests is None: continue if isinstance(vals, six.string_types): vals = [vals] rvals = [] for restr in _rests: for val in vals: if restr.match(val): rvals.append(val) if rvals: ava[attr] = list(set(rvals)) else: del ava[attr] return ava
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self, restrictions): """ This is only for IdPs or AAs, and it's about limiting what is returned to the SP. In the configuration file, restrictions on which values that can be returned are specified with the help of regular expressions. This function goes through and pre-compiles the regular expressions. :param restrictions: :return: The assertion with the string specification replaced with a compiled regular expression. """
self._restrictions = copy.deepcopy(restrictions) for who, spec in self._restrictions.items(): if spec is None: continue try: items = spec["entity_categories"] except KeyError: pass else: ecs = [] for cat in items: _mod = importlib.import_module( "saml2.entity_category.%s" % cat) _ec = {} for key, items in _mod.RELEASE.items(): alist = [k.lower() for k in items] try: _only_required = _mod.ONLY_REQUIRED[key] except (AttributeError, KeyError): _only_required = False _ec[key] = (alist, _only_required) ecs.append(_ec) spec["entity_categories"] = ecs try: restr = spec["attribute_restrictions"] except KeyError: continue if restr is None: continue _are = {} for key, values in restr.items(): if not values: _are[key.lower()] = None continue _are[key.lower()] = [re.compile(value) for value in values] spec["attribute_restrictions"] = _are logger.debug("policy restrictions: %s", self._restrictions) return self._restrictions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conditions(self, sp_entity_id): """ Return a saml.Condition instance :param sp_entity_id: The SP entity ID :return: A saml.Condition instance """
return factory(saml.Conditions, not_before=instant(), # How long might depend on who's getting it not_on_or_after=self.not_on_or_after(sp_entity_id), audience_restriction=[factory( saml.AudienceRestriction, audience=[factory(saml.Audience, text=sp_entity_id)])])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct(self, sp_entity_id, attrconvs, policy, issuer, farg, authn_class=None, authn_auth=None, authn_decl=None, encrypt=None, sec_context=None, authn_decl_ref=None, authn_instant="", subject_locality="", authn_statem=None, name_id=None, session_not_on_or_after=None): """ Construct the Assertion :param sp_entity_id: The entityid of the SP :param in_response_to: An identifier of the message, this message is a response to :param name_id: An NameID instance :param attrconvs: AttributeConverters :param policy: The policy that should be adhered to when replying :param issuer: Who is issuing the statement :param authn_class: The authentication class :param authn_auth: The authentication instance :param authn_decl: An Authentication Context declaration :param encrypt: Whether to encrypt parts or all of the Assertion :param sec_context: The security context used when encrypting :param authn_decl_ref: An Authentication Context declaration reference :param authn_instant: When the Authentication was performed :param subject_locality: Specifies the DNS domain name and IP address for the system from which the assertion subject was apparently authenticated. :param authn_statem: A AuthnStatement instance :return: An Assertion instance """
if policy: _name_format = policy.get_name_form(sp_entity_id) else: _name_format = NAME_FORMAT_URI attr_statement = saml.AttributeStatement(attribute=from_local( attrconvs, self, _name_format)) if encrypt == "attributes": for attr in attr_statement.attribute: enc = sec_context.encrypt(text="%s" % attr) encd = xmlenc.encrypted_data_from_string(enc) encattr = saml.EncryptedAttribute(encrypted_data=encd) attr_statement.encrypted_attribute.append(encattr) attr_statement.attribute = [] # start using now and for some time conds = policy.conditions(sp_entity_id) if authn_statem: _authn_statement = authn_statem elif authn_auth or authn_class or authn_decl or authn_decl_ref: _authn_statement = authn_statement(authn_class, authn_auth, authn_decl, authn_decl_ref, authn_instant, subject_locality, session_not_on_or_after=session_not_on_or_after) else: _authn_statement = None subject = do_subject(policy, sp_entity_id, name_id, **farg['subject']) _ass = assertion_factory(issuer=issuer, conditions=conds, subject=subject) if _authn_statement: _ass.authn_statement = [_authn_statement] if not attr_statement.empty(): _ass.attribute_statement = [attr_statement] return _ass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_policy(self, sp_entity_id, policy, metadata=None): """ Apply policy to the assertion I'm representing :param sp_entity_id: The SP entity ID :param policy: The policy :param metadata: Metadata to use :return: The resulting AVA after the policy is applied """
policy.acs = self.acs ava = policy.restrict(self, sp_entity_id, metadata) for key, val in list(self.items()): if key in ava: self[key] = ava[key] else: del self[key] return ava
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def application(environ, start_response): """ The main WSGI application. Dispatch the current request to the functions from above. If nothing matches, call the `not_found` function. :param environ: The HTTP application environment :param start_response: The application to run when the handling of the request is done :return: The response as a list of lines """
path = environ.get("PATH_INFO", "").lstrip("/") logger.debug("<application> PATH: '%s'", path) if path == "metadata": return metadata(environ, start_response) logger.debug("Finding callback to run") try: for regex, spec in urls: match = re.search(regex, path) if match is not None: if isinstance(spec, tuple): callback, func_name, _sp = spec cls = callback(_sp, environ, start_response, cache=CACHE) func = getattr(cls, func_name) return func() else: return spec(environ, start_response, SP) if re.match(".*static/.*", path): return handle_static(environ, start_response, path) return not_found(environ, start_response) except StatusError as err: logging.error("StatusError: %s" % err) resp = BadRequest("%s" % err) return resp(environ, start_response) except Exception as err: # _err = exception_trace("RUN", err) # logging.error(exception_trace("RUN", _err)) print(err, file=sys.stderr) resp = ServiceError("%s" % err) return resp(environ, start_response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def soap(self): """ Single log out using HTTP_SOAP binding """
logger.debug("- SOAP -") _dict = self.unpack_soap() logger.debug("_dict: %s", _dict) return self.operation(_dict, BINDING_SOAP)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pick_idp(self, came_from): """ If more than one idp and if none is selected, I have to do wayf or disco """
_cli = self.sp logger.debug("[_pick_idp] %s", self.environ) if "HTTP_PAOS" in self.environ: if self.environ["HTTP_PAOS"] == PAOS_HEADER_INFO: if MIME_PAOS in self.environ["HTTP_ACCEPT"]: # Where should I redirect the user to # entityid -> the IdP to use # relay_state -> when back from authentication logger.debug("- ECP client detected -") _rstate = rndstr() self.cache.relay_state[_rstate] = geturl(self.environ) _entityid = _cli.config.ecp_endpoint(self.environ["REMOTE_ADDR"]) if not _entityid: return -1, ServiceError("No IdP to talk to") logger.debug("IdP to talk to: %s", _entityid) return ecp.ecp_auth_request(_cli, _entityid, _rstate) else: return -1, ServiceError("Faulty Accept header") else: return -1, ServiceError("unknown ECP version") # Find all IdPs idps = self.sp.metadata.with_descriptor("idpsso") idp_entity_id = None kaka = self.environ.get("HTTP_COOKIE", "") if kaka: try: (idp_entity_id, _) = parse_cookie("ve_disco", "SEED_SAW", kaka) except ValueError: pass except TypeError: pass # Any specific IdP specified in a query part query = self.environ.get("QUERY_STRING") if not idp_entity_id and query: try: _idp_entity_id = dict(parse_qs(query))[self.idp_query_param][0] if _idp_entity_id in idps: idp_entity_id = _idp_entity_id except KeyError: logger.debug("No IdP entity ID in query: %s", query) pass if not idp_entity_id: if self.wayf: if query: try: wayf_selected = dict(parse_qs(query))["wayf_selected"][0] except KeyError: return self._wayf_redirect(came_from) idp_entity_id = wayf_selected else: return self._wayf_redirect(came_from) elif self.discosrv: if query: idp_entity_id = _cli.parse_discovery_service_response( query=self.environ.get("QUERY_STRING") ) if not idp_entity_id: sid_ = sid() self.cache.outstanding_queries[sid_] = came_from logger.debug("Redirect to Discovery Service function") eid = _cli.config.entityid ret = _cli.config.getattr("endpoints", "sp")["discovery_response"][ 0 ][0] ret += "?sid=%s" % sid_ loc = _cli.create_discovery_service_request( self.discosrv, eid, **{"return": ret} ) return -1, SeeOther(loc) elif len(idps) == 1: # idps is a dictionary idp_entity_id = list(idps.keys())[0] elif not len(idps): return -1, ServiceError("Misconfiguration") else: return -1, NotImplemented("No WAYF or DS present!") logger.info("Chosen IdP: '%s'", idp_entity_id) return 0, idp_entity_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valid_any_uri(item):
try: part = urlparse(item) except Exception: raise NotValid("AnyURI") if part[0] == "urn" and part[1] == "": # A urn return True # elif part[1] == "localhost" or part[1] == "127.0.0.1": # raise NotValid("AnyURI") return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valid_anytype(val): """ Goes through all known type validators :param val: The value to validate :return: True is value is valid otherwise an exception is raised """
for validator in VALIDATOR.values(): if validator == valid_anytype: # To hinder recursion continue try: if validator(val): return True except NotValid: pass if isinstance(val, type): return True raise NotValid("AnyType")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_maps(dirspec): """ load the attribute maps :param dirspec: a directory specification :return: a dictionary with the name of the map as key and the map as value. The map itself is a dictionary with two keys: "to" and "fro". The values for those keys are the actual mapping. """
mapd = {} if dirspec not in sys.path: sys.path.insert(0, dirspec) for fil in os.listdir(dirspec): if fil.endswith(".py"): mod = import_module(fil[:-3]) for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: mapd[item["identifier"]] = item return mapd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ac_factory(path=""): """Attribute Converter factory :param path: The path to a directory where the attribute maps are expected to reside. :return: A AttributeConverter instance """
acs = [] if path: if path not in sys.path: sys.path.insert(0, path) for fil in os.listdir(path): if fil.endswith(".py"): mod = import_module(fil[:-3]) for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: atco = AttributeConverter(item["identifier"]) atco.from_dict(item) acs.append(atco) else: from saml2 import attributemaps for typ in attributemaps.__all__: mod = import_module(".%s" % typ, "saml2.attributemaps") for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: atco = AttributeConverter(item["identifier"]) atco.from_dict(item) acs.append(atco) return acs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust(self): """ If one of the transformations is not defined it is expected to be the mirror image of the other. """
if self._fro is None and self._to is not None: self._fro = dict( [(value.lower(), key) for key, value in self._to.items()]) if self._to is None and self._fro is not None: self._to = dict( [(value.lower(), key) for key, value in self._fro.items()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(self, mapdict): """ Import the attribute map from a dictionary :param mapdict: The dictionary """
self.name_format = mapdict["identifier"] try: self._fro = dict( [(k.lower(), v) for k, v in mapdict["fro"].items()]) except KeyError: pass try: self._to = dict([(k.lower(), v) for k, v in mapdict["to"].items()]) except KeyError: pass if self._fro is None and self._to is None: raise ConverterError("Missing specifications") if self._fro is None or self._to is None: self.adjust()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lcd_ava_from(self, attribute): """ If nothing else works, this should :param attribute: an Attribute instance :return: """
name = attribute.name.strip() values = [ (value.text or '').strip() for value in attribute.attribute_value] return name, values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fail_safe_fro(self, statement): """ In case there is not formats defined or if the name format is undefined :param statement: AttributeStatement instance :return: A dictionary with names and values """
result = {} for attribute in statement.attribute: if attribute.name_format and \ attribute.name_format != NAME_FORMAT_UNSPECIFIED: continue try: name = attribute.friendly_name.strip() except AttributeError: name = attribute.name.strip() result[name] = [] for value in attribute.attribute_value: if not value.text: result[name].append('') else: result[name].append(value.text.strip()) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fro(self, statement): """ Get the attributes and the attribute values. :param statement: The AttributeStatement. :return: A dictionary containing attributes and values """
if not self.name_format: return self.fail_safe_fro(statement) result = {} for attribute in statement.attribute: if attribute.name_format and self.name_format and \ attribute.name_format != self.name_format: continue try: (key, val) = self.ava_from(attribute) except (KeyError, AttributeError): pass else: result[key] = val return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_format(self, attr): """ Creates an Attribute instance with name, name_format and friendly_name :param attr: The local name of the attribute :return: An Attribute instance """
try: _attr = self._to[attr] except KeyError: try: _attr = self._to[attr.lower()] except: _attr = '' if _attr: return factory(saml.Attribute, name=_attr, name_format=self.name_format, friendly_name=attr) else: return factory(saml.Attribute, name=attr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def my_request_classifier(environ): """ Returns one of the classifiers 'dav', 'xmlpost', or 'browser', depending on the imperative logic below"""
request_method = REQUEST_METHOD(environ) if request_method in _DAV_METHODS: return "dav" useragent = USER_AGENT(environ) if useragent: for agent in _DAV_USERAGENTS: if useragent.find(agent) != -1: return "dav" if request_method == "POST": if CONTENT_TYPE(environ) == "text/xml": return "xmlpost" elif CONTENT_TYPE(environ) == "application/soap+xml": return "soap" return "browser"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _localized_name(val, klass): """If no language is defined 'en' is the default"""
try: (text, lang) = val return klass(text=text, lang=lang) except ValueError: return klass(text=val, lang="en")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_contact_person_info(ava): """Create a ContactPerson instance from configuration information."""
cper = md.ContactPerson() cper.loadd(ava) if not cper.contact_type: cper.contact_type = "technical" return cper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_pdp_descriptor(conf, cert=None, enc_cert=None): """ Create a Policy Decision Point descriptor """
pdp = md.PDPDescriptor() pdp.protocol_support_enumeration = samlp.NAMESPACE endps = conf.getattr("endpoints", "pdp") if endps: for (endpoint, instlist) in do_endpoints(endps, ENDPOINTS["pdp"]).items(): setattr(pdp, endpoint, instlist) _do_nameid_format(pdp, conf, "pdp") if cert: pdp.key_descriptor = do_key_descriptor(cert, enc_cert, use=conf.metadata_key_usage) return pdp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_return_url(base, query, **kwargs): """ Add a query string plus extra parameters to a base URL which may contain a query part already. :param base: redirect_uri may contain a query part, no fragment allowed. :param query: Old query part as a string :param kwargs: extra query parameters :return: """
part = urlsplit(base) if part.fragment: raise ValueError("Base URL contained parts it shouldn't") for key, values in parse_qs(query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values if part.query: for key, values in parse_qs(part.query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values _pre = base.split("?")[0] else: _pre = base logger.debug("kwargs: %s" % kwargs) return "%s?%s" % (_pre, url_encode_params(kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _issuer(self, entityid=None): """ Return an Issuer instance """
if entityid: if isinstance(entityid, Issuer): return entityid else: return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY) else: return Issuer(text=self.config.entityid, format=NAMEID_FORMAT_ENTITY)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_binding(self, binding, msg_str, destination="", relay_state="", response=False, sign=False, **kwargs): """ Construct the necessary HTTP arguments dependent on Binding :param binding: Which binding to use :param msg_str: The return message as a string (XML) if the message is to be signed it MUST contain the signature element. :param destination: Where to send the message :param relay_state: Relay_state if provided :param response: Which type of message this is :param kwargs: response type specific arguments :return: A dictionary """
# unless if BINDING_HTTP_ARTIFACT if response: typ = "SAMLResponse" else: typ = "SAMLRequest" if binding == BINDING_HTTP_POST: logger.info("HTTP POST") # if self.entity_type == 'sp': # info = self.use_http_post(msg_str, destination, relay_state, # typ) # info["url"] = destination # info["method"] = "POST" # else: info = self.use_http_form_post(msg_str, destination, relay_state, typ) info["url"] = destination info["method"] = "POST" elif binding == BINDING_HTTP_REDIRECT: logger.info("HTTP REDIRECT") sigalg = kwargs.get("sigalg") if sign and sigalg: signer = self.sec.sec_backend.get_signer(sigalg) else: signer = None info = self.use_http_get(msg_str, destination, relay_state, typ, signer=signer, **kwargs) info["url"] = str(destination) info["method"] = "GET" elif binding == BINDING_SOAP or binding == BINDING_PAOS: info = self.use_soap(msg_str, destination, sign=sign, **kwargs) elif binding == BINDING_URI: info = self.use_http_uri(msg_str, typ, destination) elif binding == BINDING_HTTP_ARTIFACT: if response: info = self.use_http_artifact(msg_str, destination, relay_state) info["method"] = "GET" info["status"] = 302 else: info = self.use_http_artifact(msg_str, destination, relay_state) else: raise SAMLError("Unknown binding type: %s" % binding) return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _message(self, request_cls, destination=None, message_id=0, consent=None, extensions=None, sign=False, sign_prepare=False, nsprefix=None, sign_alg=None, digest_alg=None, **kwargs): """ Some parameters appear in all requests so simplify by doing it in one place :param request_cls: The specific request type :param destination: The recipient :param message_id: A message identifier :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param sign_prepare: Whether the signature should be prepared or not. :param kwargs: Key word arguments specific to one request type :return: A tuple containing the request ID and an instance of the request_cls """
if not message_id: message_id = sid() for key, val in self.message_args(message_id).items(): if key not in kwargs: kwargs[key] = val req = request_cls(**kwargs) if destination: req.destination = destination if consent: req.consent = "true" if extensions: req.extensions = extensions if nsprefix: req.register_prefix(nsprefix) if self.msg_cb: req = self.msg_cb(req) reqid = req.id if sign: return reqid, self.sign(req, sign_prepare=sign_prepare, sign_alg=sign_alg, digest_alg=digest_alg) else: logger.info("REQUEST: %s", req) return reqid, req
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_info(self, msg, **kwargs): """ Add information to a SAML message. If the attribute is not part of what's defined in the SAML standard add it as an extension. :param msg: :param kwargs: :return: """
args, extensions = self._filter_args(msg, **kwargs) for key, val in args.items(): setattr(msg, key, val) if extensions: if msg.extension_elements: msg.extension_elements.extend(extensions) else: msg.extension_elements = extensions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_encrypt_cert_in_metadata(self, sp_entity_id): """ Verifies if the metadata contains encryption certificates. :param sp_entity_id: Entity ID for the calling service provider. :return: True if encrypt cert exists in metadata, otherwise False. """
if sp_entity_id is not None: _certs = self.metadata.certs(sp_entity_id, "any", "encryption") if len(_certs) > 0: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encrypt_assertion(self, encrypt_cert, sp_entity_id, response, node_xpath=None): """ Encryption of assertions. :param encrypt_cert: Certificate to be used for encryption. :param sp_entity_id: Entity ID for the calling service provider. :param response: A samlp.Response :param node_xpath: Unquie path to the element to be encrypted. :return: A new samlp.Resonse with the designated assertion encrypted. """
_certs = [] if encrypt_cert: _certs.append(encrypt_cert) elif sp_entity_id is not None: _certs = self.metadata.certs(sp_entity_id, "any", "encryption") exception = None for _cert in _certs: try: begin_cert = "-----BEGIN CERTIFICATE-----\n" end_cert = "\n-----END CERTIFICATE-----\n" if begin_cert not in _cert: _cert = "%s%s" % (begin_cert, _cert) if end_cert not in _cert: _cert = "%s%s" % (_cert, end_cert) _, cert_file = make_temp(_cert.encode('ascii'), decode=False) response = self.sec.encrypt_assertion(response, cert_file, pre_encryption_part(), node_xpath=node_xpath) return response except Exception as ex: exception = ex pass if exception: raise exception return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _status_response(self, response_class, issuer, status, sign=False, sign_alg=None, digest_alg=None, **kwargs): """ Create a StatusResponse. :param response_class: Which subclass of StatusResponse that should be used :param issuer: The issuer of the response message :param status: The return status of the response operation :param sign: Whether the response should be signed or not :param kwargs: Extra arguments to the response class :return: Class instance or string representation of the instance """
mid = sid() for key in ["binding"]: try: del kwargs[key] except KeyError: pass if not status: status = success_status_factory() response = response_class(issuer=issuer, id=mid, version=VERSION, issue_instant=instant(), status=status, **kwargs) if sign: return self.sign(response, mid, sign_alg=sign_alg, digest_alg=digest_alg) else: return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_request(self, enc_request, request_cls, service, binding): """Parse a Request :param enc_request: The request in its transport format :param request_cls: The type of requests I expect :param service: :param binding: Which binding that was used to transport the message to this entity. :return: A request instance """
_log_info = logger.info _log_debug = logger.debug # The addresses I should receive messages like this on receiver_addresses = self.config.endpoint(service, binding, self.entity_type) if not receiver_addresses and self.entity_type == "idp": for typ in ["aa", "aq", "pdp"]: receiver_addresses = self.config.endpoint(service, binding, typ) if receiver_addresses: break _log_debug("receiver addresses: %s", receiver_addresses) _log_debug("Binding: %s", binding) try: timeslack = self.config.accepted_time_diff if not timeslack: timeslack = 0 except AttributeError: timeslack = 0 _request = request_cls(self.sec, receiver_addresses, self.config.attribute_converters, timeslack=timeslack) xmlstr = self.unravel(enc_request, binding, request_cls.msgtype) must = self.config.getattr("want_authn_requests_signed", "idp") only_valid_cert = self.config.getattr( "want_authn_requests_only_with_valid_cert", "idp") if only_valid_cert is None: only_valid_cert = False if only_valid_cert: must = True _request = _request.loads(xmlstr, binding, origdoc=enc_request, must=must, only_valid_cert=only_valid_cert) _log_debug("Loaded request") if _request: _request = _request.verify() _log_debug("Verified request") if not _request: return None else: return _request
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_error_response(self, in_response_to, destination, info, sign=False, issuer=None, sign_alg=None, digest_alg=None, **kwargs): """ Create a error response. :param in_response_to: The identifier of the message this is a response to. :param destination: The intended recipient of this message :param info: Either an Exception instance or a 2-tuple consisting of error code and descriptive text :param sign: Whether the response should be signed or not :param issuer: The issuer of the response :param kwargs: To capture key,value pairs I don't care about :return: A response instance """
status = error_status_factory(info) return self._response(in_response_to, destination, status, issuer, sign, sign_alg=sign_alg, digest_alg=digest_alg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_logout_request(self, destination, issuer_entity_id, subject_id=None, name_id=None, reason=None, expire=None, message_id=0, consent=None, extensions=None, sign=False, session_indexes=None, sign_alg=None, digest_alg=None): """ Constructs a LogoutRequest :param destination: Destination of the request :param issuer_entity_id: The entity ID of the IdP the request is target at. :param subject_id: The identifier of the subject :param name_id: A NameID instance identifying the subject :param reason: An indication of the reason for the logout, in the form of a URI reference. :param expire: The time at which the request expires, after which the recipient may discard the message. :param message_id: Request identifier :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the query should be signed or not. :param session_indexes: SessionIndex instances or just values :return: A LogoutRequest instance """
if subject_id: if self.entity_type == "idp": name_id = NameID(text=self.users.get_entityid(subject_id, issuer_entity_id, False)) else: name_id = NameID(text=subject_id) if not name_id: raise SAMLError("Missing subject identification") args = {} if session_indexes: sis = [] for si in session_indexes: if isinstance(si, SessionIndex): sis.append(si) else: sis.append(SessionIndex(text=si)) args["session_index"] = sis return self._message(LogoutRequest, destination, message_id, consent, extensions, sign, name_id=name_id, reason=reason, not_on_or_after=expire, issuer=self._issuer(), sign_alg=sign_alg, digest_alg=digest_alg, **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_logout_response(self, request, bindings=None, status=None, sign=False, issuer=None, sign_alg=None, digest_alg=None): """ Create a LogoutResponse. :param request: The request this is a response to :param bindings: Which bindings that can be used for the response If None the preferred bindings are gathered from the configuration :param status: The return status of the response operation If None the operation is regarded as a Success. :param issuer: The issuer of the message :return: HTTP args """
rinfo = self.response_args(request, bindings) if not issuer: issuer = self._issuer() response = self._status_response(samlp.LogoutResponse, issuer, status, sign, sign_alg=sign_alg, digest_alg=digest_alg, **rinfo) logger.info("Response: %s", response) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_artifact_resolve(self, artifact, destination, sessid, consent=None, extensions=None, sign=False, sign_alg=None, digest_alg=None): """ Create a ArtifactResolve request :param artifact: :param destination: :param sessid: session id :param consent: :param extensions: :param sign: :return: The request message """
artifact = Artifact(text=artifact) return self._message(ArtifactResolve, destination, sessid, consent, extensions, sign, artifact=artifact, sign_alg=sign_alg, digest_alg=digest_alg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_response(self, xmlstr, response_cls, service, binding, outstanding_certs=None, **kwargs): """ Deal with a Response :param xmlstr: The response as a xml string :param response_cls: What type of response it is :param binding: What type of binding this message came through. :param outstanding_certs: Certificates that belongs to me that the IdP may have used to encrypt a response/assertion/.. :param kwargs: Extra key word arguments :return: None if the reply doesn't contain a valid SAML Response, otherwise the response. """
if self.config.accepted_time_diff: kwargs["timeslack"] = self.config.accepted_time_diff if "asynchop" not in kwargs: if binding in [BINDING_SOAP, BINDING_PAOS]: kwargs["asynchop"] = False else: kwargs["asynchop"] = True response = None if not xmlstr: return response if "return_addrs" not in kwargs: bindings = { BINDING_SOAP, BINDING_HTTP_REDIRECT, BINDING_HTTP_POST, } if binding in bindings: # expected return address kwargs["return_addrs"] = self.config.endpoint( service, binding=binding, context=self.entity_type) try: response = response_cls(self.sec, **kwargs) except Exception as exc: logger.info("%s", exc) raise xmlstr = self.unravel(xmlstr, binding, response_cls.msgtype) if not xmlstr: # Not a valid reponse return None try: response_is_signed = False # Record the response signature requirement. require_response_signature = response.require_response_signature # Force the requirement that the response be signed in order to # force signature checking to happen so that we can know whether # or not the response is signed. The attribute on the response class # is reset to the recorded value in the finally clause below. response.require_response_signature = True response = response.loads(xmlstr, False, origxml=xmlstr) except SigverError as err: if require_response_signature: logger.error("Signature Error: %s", err) raise else: # The response is not signed but a signature is not required # so reset the attribute on the response class to the recorded # value and attempt to consume the unpacked XML again. response.require_response_signature = require_response_signature response = response.loads(xmlstr, False, origxml=xmlstr) except UnsolicitedResponse: logger.error("Unsolicited response") raise except Exception as err: if "not well-formed" in "%s" % err: logger.error("Not well-formed XML") raise else: response_is_signed = True finally: response.require_response_signature = require_response_signature logger.debug("XMLSTR: %s", xmlstr) if not response: return response keys = None if outstanding_certs: try: cert = outstanding_certs[response.in_response_to] except KeyError: keys = None else: if not isinstance(cert, list): cert = [cert] keys = [] for _cert in cert: keys.append(_cert["key"]) try: assertions_are_signed = False # Record the assertions signature requirement. require_signature = response.require_signature # Force the requirement that the assertions be signed in order to # force signature checking to happen so that we can know whether # or not the assertions are signed. The attribute on the response class # is reset to the recorded value in the finally clause below. response.require_signature = True # Verify that the assertion is syntactically correct and the # signature on the assertion is correct if present. response = response.verify(keys) except SignatureError as err: if require_signature: logger.error("Signature Error: %s", err) raise else: response.require_signature = require_signature response = response.verify(keys) else: assertions_are_signed = True finally: response.require_signature = require_signature # If so configured enforce that either the response is signed # or the assertions within it are signed. if response.require_signature_or_response_signature: if not response_is_signed and not assertions_are_signed: msg = "Neither the response nor the assertions are signed" logger.error(msg) raise SigverError(msg) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def artifact2destination(self, artifact, descriptor): """ Translate an artifact into a receiver location :param artifact: The Base64 encoded SAML artifact :return: """
_art = base64.b64decode(artifact) assert _art[:2] == ARTIFACT_TYPECODE try: endpoint_index = str(int(_art[2:4])) except ValueError: endpoint_index = str(int(hexlify(_art[2:4]))) entity = self.sourceid[_art[4:24]] destination = None for desc in entity["%s_descriptor" % descriptor]: for srv in desc["artifact_resolution_service"]: if srv["index"] == endpoint_index: destination = srv["location"] break return destination
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_for_authenticate( self, entityid=None, relay_state="", binding=saml2.BINDING_HTTP_REDIRECT, vorg="", nameid_format=None, scoping=None, consent=None, extensions=None, sign=None, response_binding=saml2.BINDING_HTTP_POST, **kwargs): """ Makes all necessary preparations for an authentication request. :param entityid: The entity ID of the IdP to send the request to :param relay_state: To where the user should be returned after successfull log in. :param binding: Which binding to use for sending the request :param vorg: The entity_id of the virtual organization I'm a member of :param nameid_format: :param scoping: For which IdPs this query are aimed. :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param response_binding: Which binding to use for receiving the response :param kwargs: Extra key word arguments :return: session id and AuthnRequest info """
reqid, negotiated_binding, info = \ self.prepare_for_negotiated_authenticate( entityid=entityid, relay_state=relay_state, binding=binding, vorg=vorg, nameid_format=nameid_format, scoping=scoping, consent=consent, extensions=extensions, sign=sign, response_binding=response_binding, **kwargs) assert negotiated_binding == binding return reqid, info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_for_negotiated_authenticate( self, entityid=None, relay_state="", binding=None, vorg="", nameid_format=None, scoping=None, consent=None, extensions=None, sign=None, response_binding=saml2.BINDING_HTTP_POST, **kwargs): """ Makes all necessary preparations for an authentication request that negotiates which binding to use for authentication. :param entityid: The entity ID of the IdP to send the request to :param relay_state: To where the user should be returned after successfull log in. :param binding: Which binding to use for sending the request :param vorg: The entity_id of the virtual organization I'm a member of :param nameid_format: :param scoping: For which IdPs this query are aimed. :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param response_binding: Which binding to use for receiving the response :param kwargs: Extra key word arguments :return: session id and AuthnRequest info """
expected_binding = binding for binding in [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]: if expected_binding and binding != expected_binding: continue destination = self._sso_location(entityid, binding) logger.info("destination to provider: %s", destination) reqid, request = self.create_authn_request( destination, vorg, scoping, response_binding, nameid_format, consent=consent, extensions=extensions, sign=sign, **kwargs) _req_str = str(request) logger.info("AuthNReq: %s", _req_str) try: args = {'sigalg': kwargs["sigalg"]} except KeyError: args = {} http_info = self.apply_binding(binding, _req_str, destination, relay_state, sign=sign, **args) return reqid, binding, http_info else: raise SignOnError( "No supported bindings available for authentication")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_logged_in(self, name_id): """ Check if user is in the cache :param name_id: The identifier of the subject """
identity = self.users.get_identity(name_id)[0] return bool(identity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_logout_response(self, response, sign_alg=None, digest_alg=None): """ handles a Logout response :param response: A response.Response instance :return: 4-tuple of (session_id of the last sent logout request, response message, response headers and message) """
logger.info("state: %s", self.state) status = self.state[response.in_response_to] logger.info("status: %s", status) issuer = response.issuer() logger.info("issuer: %s", issuer) del self.state[response.in_response_to] if status["entity_ids"] == [issuer]: # done self.local_logout(decode(status["name_id"])) return 0, "200 Ok", [("Content-type", "text/html")], [] else: status["entity_ids"].remove(issuer) if "sign_alg" in status: sign_alg = status["sign_alg"] return self.do_logout(decode(status["name_id"]), status["entity_ids"], status["reason"], status["not_on_or_after"], status["sign"], sign_alg=sign_alg, digest_alg=digest_alg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_attribute_query(self, entityid, subject_id, attribute=None, sp_name_qualifier=None, name_qualifier=None, nameid_format=None, real_id=None, consent=None, extensions=None, sign=False, binding=BINDING_SOAP, nsprefix=None): """ Does a attribute request to an attribute authority, this is by default done over SOAP. :param entityid: To whom the query should be sent :param subject_id: The identifier of the subject :param attribute: A dictionary of attributes and values that is asked for :param sp_name_qualifier: The unique identifier of the service provider or affiliation of providers for whom the identifier was generated. :param name_qualifier: The unique identifier of the identity provider that generated the identifier. :param nameid_format: The format of the name ID :param real_id: The identifier which is the key to this entity in the identity database :param binding: Which binding to use :param nsprefix: Namespace prefixes preferred before those automatically produced. :return: The attributes returned if BINDING_SOAP was used. HTTP args if BINDING_HTT_POST was used. """
if real_id: response_args = {"real_id": real_id} else: response_args = {} if not binding: binding, destination = self.pick_binding("attribute_service", None, "attribute_authority", entity_id=entityid) else: srvs = self.metadata.attribute_service(entityid, binding) if srvs is []: raise SAMLError("No attribute service support at entity") destination = destinations(srvs)[0] if binding == BINDING_SOAP: return self._use_soap(destination, "attribute_query", consent=consent, extensions=extensions, sign=sign, subject_id=subject_id, attribute=attribute, sp_name_qualifier=sp_name_qualifier, name_qualifier=name_qualifier, format=nameid_format, response_args=response_args) elif binding == BINDING_HTTP_POST: mid = sid() query = self.create_attribute_query(destination, subject_id, attribute, mid, consent, extensions, sign, nsprefix) self.state[query.id] = {"entity_id": entityid, "operation": "AttributeQuery", "subject_id": subject_id, "sign": sign} relay_state = self._relay_state(query.id) return self.apply_binding(binding, "%s" % query, destination, relay_state, sign=sign) else: raise SAMLError("Unsupported binding")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def before(point): """ True if point datetime specification is before now. NOTE: If point is specified it is supposed to be in local time. Not UTC/GMT !! This is because that is what gmtime() expects. """
if not point: return True if isinstance(point, six.string_types): point = str_to_time(point) elif isinstance(point, int): point = time.gmtime(point) return time.gmtime() <= point
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def phase2(self, authn_request, rc_url, idp_entity_id, headers=None, sign=False, **kwargs): """ Doing the second phase of the ECP conversation, the conversation with the IdP happens. :param authn_request: The AuthenticationRequest :param rc_url: The assertion consumer service url of the SP :param idp_entity_id: The EntityID of the IdP :param headers: Possible extra headers :param sign: If the message should be signed :return: The response from the IdP """
_, destination = self.pick_binding("single_sign_on_service", [BINDING_SOAP], "idpsso", entity_id=idp_entity_id) ht_args = self.apply_binding(BINDING_SOAP, authn_request, destination, sign=sign) if headers: ht_args["headers"].extend(headers) logger.debug("[P2] Sending request: %s", ht_args["data"]) # POST the request to the IdP response = self.send(**ht_args) logger.debug("[P2] Got IdP response: %s", response) if response.status_code != 200: raise SAMLError( "Request to IdP failed (%s): %s" % (response.status_code, response.text)) # SAMLP response in a SOAP envelope body, ecp response in headers respdict = self.parse_soap_message(response.text) if respdict is None: raise SAMLError("Unexpected reply from the IdP") logger.debug("[P2] IdP response dict: %s", respdict) idp_response = respdict["body"] assert idp_response.c_tag == "Response" logger.debug("[P2] IdP AUTHN response: %s", idp_response) _ecp_response = None for item in respdict["header"]: if item.c_tag == "Response" and item.c_namespace == ecp.NAMESPACE: _ecp_response = item _acs_url = _ecp_response.assertion_consumer_service_url if rc_url != _acs_url: error = ("response_consumer_url '%s' does not match" % rc_url, "assertion_consumer_service_url '%s" % _acs_url) # Send an error message to the SP _ = self.send(rc_url, "POST", data=soap.soap_fault(error)) # Raise an exception so the user knows something went wrong raise SAMLError(error) return idp_response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def operation(self, url, idp_entity_id, op, **opargs): """ This is the method that should be used by someone that wants to authenticate using SAML ECP :param url: The page that access is sought for :param idp_entity_id: The entity ID of the IdP that should be used for authentication :param op: Which HTTP operation (GET/POST/PUT/DELETE) :param opargs: Arguments to the HTTP call :return: The page """
sp_url = self._sp # ******************************************** # Phase 1 - First conversation with the SP # ******************************************** # headers needed to indicate to the SP that I'm ECP enabled opargs["headers"] = self.add_paos_headers(opargs["headers"]) response = self.send(sp_url, op, **opargs) logger.debug("[Op] SP response: %s" % response) print(response.text) if response.status_code != 200: raise SAMLError( "Request to SP failed: %s" % response.text) # The response might be a AuthnRequest instance in a SOAP envelope # body. If so it's the start of the ECP conversation # Two SOAP header blocks; paos:Request and ecp:Request # may also contain a ecp:RelayState SOAP header block # If channel-binding was part of the PAOS header any number of # <cb:ChannelBindings> header blocks may also be present # if 'holder-of-key' option then one or more <ecp:SubjectConfirmation> # header blocks may also be present try: respdict = self.parse_soap_message(response.text) self.ecp_conversation(respdict, idp_entity_id) # should by now be authenticated so this should go smoothly response = self.send(url, op, **opargs) except (soap.XmlParseError, AssertionError, KeyError): raise if response.status_code >= 400: raise SAMLError("Error performing operation: %s" % ( response.text,)) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subjects(self): """ Return identifiers for all the subjects that are in the cache. :return: list of subject identifiers """
subj = [i["subject_id"] for i in self._cache.find()] return list(set(subj))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, name_id, entity_id, info, not_on_or_after=0): """ Stores session information in the cache. Assumes that the name_id is unique within the context of the Service Provider. :param name_id: The subject identifier, a NameID instance :param entity_id: The identifier of the entity_id/receiver of an assertion :param info: The session info, the assertion is part of this :param not_on_or_after: A time after which the assertion is not valid. """
info = dict(info) if 'name_id' in info and not isinstance(info['name_id'], six.string_types): # make friendly to (JSON) serialization info['name_id'] = code(name_id) cni = code(name_id) if cni not in self._db: self._db[cni] = {} self._db[cni][entity_id] = (not_on_or_after, info) if self._sync: try: self._db.sync() except AttributeError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_class_from_xml_string(target_class, xml_string): """Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param xml_string: A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. :return: An instance of the target class with members assigned according to the contents of the XML - or None if the root XML tag and namespace did not match those of the target class. """
if not isinstance(xml_string, six.binary_type): xml_string = xml_string.encode('utf-8') tree = defusedxml.ElementTree.fromstring(xml_string) return create_class_from_element_tree(target_class, tree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_class_from_element_tree(target_class, tree, namespace=None, tag=None): """Instantiates the class and populates members according to the tree. Note: Only use this function with classes that have c_namespace and c_tag class members. :param target_class: The class which will be instantiated and populated with the contents of the XML. :param tree: An element tree whose contents will be converted into members of the new target_class instance. :param namespace: The namespace which the XML tree's root node must match. If omitted, the namespace defaults to the c_namespace of the target class. :param tag: The tag which the XML tree's root node must match. If omitted, the tag defaults to the c_tag class member of the target class. :return: An instance of the target class - or None if the tag and namespace of the XML tree's root node did not match the desired namespace and tag. """
if namespace is None: namespace = target_class.c_namespace if tag is None: tag = target_class.c_tag if tree.tag == '{%s}%s' % (namespace, tag): target = target_class() target.harvest_element_tree(tree) return target else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_to_extension_element(element): """ Convert an element into a extension element :param element: The element instance :return: An extension element instance """
exel = ExtensionElement(element.c_tag, element.c_namespace, text=element.text) exel.attributes.update(element.extension_attributes) exel.children.extend(element.extension_elements) for xml_attribute, (member_name, typ, req) in \ iter(element.c_attributes.items()): member_value = getattr(element, member_name) if member_value is not None: exel.attributes[xml_attribute] = member_value exel.children.extend([element_to_extension_element(c) for c in element.children_with_values()]) return exel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extension_element_to_element(extension_element, translation_functions, namespace=None): """ Convert an extension element to a normal element. In order to do this you need to have an idea of what type of element it is. Or rather which module it belongs to. :param extension_element: The extension element :param translation_functions: A dictionary with class identifiers as keys and string-to-element translations functions as values :param namespace: The namespace of the translation functions. :return: An element instance or None """
try: element_namespace = extension_element.namespace except AttributeError: element_namespace = extension_element.c_namespace if element_namespace == namespace: try: try: ets = translation_functions[extension_element.tag] except AttributeError: ets = translation_functions[extension_element.c_tag] return ets(extension_element.to_string()) except KeyError: pass return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extension_elements_to_elements(extension_elements, schemas): """ Create a list of elements each one matching one of the given extension elements. This is of course dependent on the access to schemas that describe the extension elements. :param extension_elements: The list of extension elements :param schemas: Imported Python modules that represent the different known schemas used for the extension elements :return: A list of elements, representing the set of extension elements that was possible to match against a Class in the given schemas. The elements returned are the native representation of the elements according to the schemas. """
res = [] if isinstance(schemas, list): pass elif isinstance(schemas, dict): schemas = list(schemas.values()) else: return res for extension_element in extension_elements: for schema in schemas: inst = extension_element_to_element(extension_element, schema.ELEMENT_FROM_STRING, schema.NAMESPACE) if inst: res.append(inst) break return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadd(self, ava): """ expects a special set of keys """
if "attributes" in ava: for key, val in ava["attributes"].items(): self.attributes[key] = val try: self.tag = ava["tag"] except KeyError: if not self.tag: raise KeyError("ExtensionElement must have a tag") try: self.namespace = ava["namespace"] except KeyError: if not self.namespace: raise KeyError("ExtensionElement must belong to a namespace") try: self.text = ava["text"] except KeyError: pass if "children" in ava: for item in ava["children"]: self.children.append(ExtensionElement(item["tag"]).loadd(item)) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_extensions(self, tag=None, namespace=None): """Searches extension elements for child nodes with the desired name. Returns a list of extension elements within this object whose tag and/or namespace match those passed in. To find all extensions in a particular namespace, specify the namespace but not the tag name. If you specify only the tag, the result list may contain extension elements in multiple namespaces. :param tag: str (optional) The desired tag :param namespace: str (optional) The desired namespace :Return: A list of elements whose tag and/or namespace match the parameters values """
results = [] if tag and namespace: for element in self.extension_elements: if element.tag == tag and element.namespace == namespace: results.append(element) elif tag and not namespace: for element in self.extension_elements: if element.tag == tag: results.append(element) elif namespace and not tag: for element in self.extension_elements: if element.namespace == namespace: results.append(element) else: for element in self.extension_elements: results.append(element) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extensions_as_elements(self, tag, schema): """ Return extensions that has the given tag and belongs to the given schema as native elements of that schema. :param tag: The tag of the element :param schema: Which schema the element should originate from :return: a list of native elements """
result = [] for ext in self.find_extensions(tag, schema.NAMESPACE): ets = schema.ELEMENT_FROM_STRING[tag] result.append(ets(ext.to_string())) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_prefix(self, nspair): """ Register with ElementTree a set of namespaces :param nspair: A dictionary of prefixes and uris to use when constructing the text representation. :return: """
for prefix, uri in nspair.items(): try: ElementTree.register_namespace(prefix, uri) except AttributeError: # Backwards compatibility with ET < 1.3 ElementTree._namespace_map[uri] = prefix except ValueError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_xml_string_with_self_contained_assertion_within_encrypted_assertion( self, assertion_tag): """ Makes a encrypted assertion only containing self contained namespaces. :param assertion_tag: Tag for the assertion to be transformed. :return: A new samlp.Resonse in string representation. """
prefix_map = self.get_prefix_map( [self.encrypted_assertion._to_element_tree().find(assertion_tag)]) tree = self._to_element_tree() self.set_prefixes( tree.find( self.encrypted_assertion._to_element_tree().tag).find( assertion_tag), prefix_map) return ElementTree.tostring(tree, encoding="UTF-8").decode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_string(self, nspair=None): """Converts the Saml object to a string containing XML. :param nspair: A dictionary of prefixes and uris to use when constructing the text representation. :return: String representation of the object """
if not nspair and self.c_ns_prefix: nspair = self.c_ns_prefix if nspair: self.register_prefix(nspair) return ElementTree.tostring(self._to_element_tree(), encoding="UTF-8")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keys(self): """ Return all the keys that represent possible attributes and children. :return: list of keys """
keys = ['text'] keys.extend([n for (n, t, r) in self.c_attributes.values()]) keys.extend([v[0] for v in self.c_children.values()]) return keys
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def children_with_values(self): """ Returns all children that has values :return: Possibly empty list of children. """
childs = [] for attribute in self._get_all_c_children_with_order(): member = getattr(self, attribute) if member is None or member == []: pass elif isinstance(member, list): for instance in member: childs.append(instance) else: childs.append(member) return childs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_text(self, val, base64encode=False): """ Sets the text property of this instance. :param val: The value of the text property :param base64encode: Whether the value should be base64encoded :return: The instance """
# print("set_text: %s" % (val,)) if isinstance(val, bool): if val: setattr(self, "text", "true") else: setattr(self, "text", "false") elif isinstance(val, int): setattr(self, "text", "%d" % val) elif isinstance(val, six.string_types): setattr(self, "text", val) elif val is None: pass else: raise ValueError("Type shouldn't be '%s'" % (val,)) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def child_class(self, child): """ Return the class a child element should be an instance of :param child: The name of the child element :return: The class """
for prop, klassdef in self.c_children.values(): if child == prop: if isinstance(klassdef, list): return klassdef[0] else: return klassdef return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def child_cardinality(self, child): """ Return the cardinality of a child element :param child: The name of the child element :return: The cardinality as a 2-tuple (min, max). The max value is either a number or the string "unbounded". The min value is always a number. """
for prop, klassdef in self.c_children.values(): if child == prop: if isinstance(klassdef, list): try: _min = self.c_cardinality["min"] except KeyError: _min = 1 try: _max = self.c_cardinality["max"] except KeyError: _max = "unbounded" return _min, _max else: return 1, 1 return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self, subject_id, entity_id): """ Scrap the assertions received from a IdP or an AA about a special subject. :param subject_id: The subjects identifier :param entity_id: The identifier of the entity_id of the assertion :return: """
if not self._cache.set(_key(subject_id, entity_id), {}, 0): raise CacheError("reset failed")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_information_about_person(self, session_info): """If there already are information from this source in the cache this function will overwrite that information"""
session_info = dict(session_info) name_id = session_info["name_id"] issuer = session_info.pop("issuer") self.cache.set(name_id, issuer, session_info, session_info["not_on_or_after"]) return name_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, spec, method, level=0, authn_authority="", reference=None): """ Adds a new authentication method. Assumes not more than one authentication method per AuthnContext specification. :param spec: What the authentication endpoint offers in the form of an AuthnContext :param method: A identifier of the authentication method. :param level: security level, positive integers, 0 is lowest :param reference: Desired unique reference to this `spec' :return: """
if spec.authn_context_class_ref: key = spec.authn_context_class_ref.text _info = { "class_ref": key, "method": method, "level": level, "authn_auth": authn_authority } elif spec.authn_context_decl: key = spec.authn_context_decl.c_namespace _info = { "method": method, "decl": spec.authn_context_decl, "level": level, "authn_auth": authn_authority } else: raise NotImplementedError() self.next += 1 _ref = reference if _ref is None: _ref = str(self.next) assert _ref not in self.db["info"] self.db["info"][_ref] = _info try: self.db["key"][key].append(_ref) except KeyError: self.db["key"][key] = [_ref]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick(self, req_authn_context=None): """ Given the authentication context find zero or more places where the user could be sent next. Ordered according to security level. :param req_authn_context: The requested context as an RequestedAuthnContext instance :return: An URL """
if req_authn_context is None: return self._pick_by_class_ref(UNSPECIFIED, "minimum") if req_authn_context.authn_context_class_ref: if req_authn_context.comparison: _cmp = req_authn_context.comparison else: _cmp = "exact" if _cmp == 'exact': res = [] for cls_ref in req_authn_context.authn_context_class_ref: res += (self._pick_by_class_ref(cls_ref.text, _cmp)) return res else: return self._pick_by_class_ref( req_authn_context.authn_context_class_ref[0].text, _cmp) elif req_authn_context.authn_context_decl_ref: if req_authn_context.comparison: _cmp = req_authn_context.comparison else: _cmp = "exact" return self._pick_by_class_ref( req_authn_context.authn_context_decl_ref, _cmp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_pem_private_key(data, password): """Load RSA PEM certificate."""
key = _serialization.load_pem_private_key( data, password, _backends.default_backend()) return key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key_sign(rsakey, message, digest): """Sign the given message with the RSA key."""
padding = _asymmetric.padding.PKCS1v15() signature = rsakey.sign(message, padding, digest) return signature
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key_verify(rsakey, signature, message, digest): """Verify the given signature with the RSA key."""
padding = _asymmetric.padding.PKCS1v15() if isinstance(rsakey, _asymmetric.rsa.RSAPrivateKey): rsakey = rsakey.public_key() try: rsakey.verify(signature, message, padding, digest) except Exception as e: return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subject_id(self): """ The name of the subject can be in either of BaseID, NameID or EncryptedID :return: The identifier if there is one """
if "subject" in self.message.keys(): _subj = self.message.subject if "base_id" in _subj.keys() and _subj.base_id: return _subj.base_id elif _subj.name_id: return _subj.name_id else: if "base_id" in self.message.keys() and self.message.base_id: return self.message.base_id elif self.message.name_id: return self.message.name_id else: # EncryptedID pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(_dict, onts, mdb_safe=False): """ Convert a pysaml2 SAML2 message class instance into a basic dictionary format. The export interface. :param _dict: The pysaml2 metadata instance :param onts: List of schemas to use for the conversion :return: The converted information """
res = {} if isinstance(_dict, SamlBase): res["__class__"] = "%s&%s" % (_dict.c_namespace, _dict.c_tag) for key in _dict.keyswv(): if key in IMP_SKIP: continue val = getattr(_dict, key) if key == "extension_elements": _eel = extension_elements_to_elements(val, onts) _val = [_eval(_v, onts, mdb_safe) for _v in _eel] elif key == "extension_attributes": if mdb_safe: _val = dict([(k.replace(".", "__"), v) for k, v in val.items()]) #_val = {k.replace(".", "__"): v for k, v in val.items()} else: _val = val else: _val = _eval(val, onts, mdb_safe) if _val: if mdb_safe: key = key.replace(".", "__") res[key] = _val else: for key, val in _dict.items(): _val = _eval(val, onts, mdb_safe) if _val: if mdb_safe and "." in key: key = key.replace(".", "__") res[key] = _val return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _kwa(val, onts, mdb_safe=False): """ Key word argument conversion :param val: A dictionary :param onts: dictionary with schemas to use in the conversion schema namespase is the key in the dictionary :return: A converted dictionary """
if not mdb_safe: return dict([(k, from_dict(v, onts)) for k, v in val.items() if k not in EXP_SKIP]) else: _skip = ["_id"] _skip.extend(EXP_SKIP) return dict([(k.replace("__", "."), from_dict(v, onts)) for k, v in val.items() if k not in _skip])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redirect(self): """ This is the HTTP-redirect endpoint """
logger.info("--- In SSO Redirect ---") saml_msg = self.unpack_redirect() try: _key = saml_msg["key"] saml_msg = IDP.ticket[_key] self.req_info = saml_msg["req_info"] del IDP.ticket[_key] except KeyError: try: self.req_info = IDP.parse_authn_request(saml_msg["SAMLRequest"], BINDING_HTTP_REDIRECT) except KeyError: resp = BadRequest("Message signature verification failure") return resp(self.environ, self.start_response) _req = self.req_info.message if "SigAlg" in saml_msg and "Signature" in saml_msg: # Signed # request issuer = _req.issuer.text _certs = IDP.metadata.certs(issuer, "any", "signing") verified_ok = False for cert in _certs: if verify_redirect_signature(saml_msg, IDP.sec.sec_backend, cert): verified_ok = True break if not verified_ok: resp = BadRequest("Message signature verification failure") return resp(self.environ, self.start_response) if self.user: if _req.force_authn: saml_msg["req_info"] = self.req_info key = self._store_request(saml_msg) return self.not_authn(key, _req.requested_authn_context) else: return self.operation(saml_msg, BINDING_HTTP_REDIRECT) else: saml_msg["req_info"] = self.req_info key = self._store_request(saml_msg) return self.not_authn(key, _req.requested_authn_context) else: return self.operation(saml_msg, BINDING_HTTP_REDIRECT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self): """ The HTTP-Post endpoint """
logger.info("--- In SSO POST ---") saml_msg = self.unpack_either() self.req_info = IDP.parse_authn_request( saml_msg["SAMLRequest"], BINDING_HTTP_POST) _req = self.req_info.message if self.user: if _req.force_authn: saml_msg["req_info"] = self.req_info key = self._store_request(saml_msg) return self.not_authn(key, _req.requested_authn_context) else: return self.operation(saml_msg, BINDING_HTTP_POST) else: saml_msg["req_info"] = self.req_info key = self._store_request(saml_msg) return self.not_authn(key, _req.requested_authn_context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def code(item): """ Turn a NameID class instance into a quoted string of comma separated attribute,value pairs. The attribute names are replaced with digits. Depends on knowledge on the specific order of the attributes for the class that is used. :param item: The class instance :return: A quoted string """
_res = [] i = 0 for attr in ATTR: val = getattr(item, attr) if val: _res.append("%d=%s" % (i, quote(val))) i += 1 return ",".join(_res)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def code_binary(item): """ Return a binary 'code' suitable for hashing. """
code_str = code(item) if isinstance(code_str, six.string_types): return code_str.encode('utf-8') return code_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_remote(self, name_id): """ Remove a NameID to userID mapping :param name_id: NameID instance """
_cn = code(name_id) _id = self.db[name_id.text] try: vals = self.db[_id].split(" ") vals.remove(_cn) self.db[_id] = " ".join(vals) except KeyError: pass del self.db[name_id.text]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_nameid(self, userid, **kwargs): """ Find a set of NameID's that matches the search criteria. :param userid: User id :param kwargs: The search filter a set of attribute/value pairs :return: a list of NameID instances """
res = [] try: _vals = self.db[userid] except KeyError: logger.debug("failed to find userid %s in IdentDB", userid) return res for val in _vals.split(" "): nid = decode(val) if kwargs: for key, _val in kwargs.items(): if getattr(nid, key, None) != _val: break else: res.append(nid) else: res.append(nid) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_nameid(self, userid, local_policy=None, sp_name_qualifier=None, name_id_policy=None, name_qualifier=""): """ Returns a name_id for the object. How the name_id is constructed depends on the context. :param local_policy: The policy the server is configured to follow :param userid: The local permanent identifier of the object :param sp_name_qualifier: The 'user'/-s of the name_id :param name_id_policy: The policy the server on the other side wants us to follow. :param name_qualifier: A domain qualifier :return: NameID instance precursor """
args = self.nim_args(local_policy, sp_name_qualifier, name_id_policy) if name_qualifier: args["name_qualifier"] = name_qualifier else: args["name_qualifier"] = self.name_qualifier return self.get_nameid(userid, **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_local_id(self, name_id): """ Only find persistent IDs :param name_id: :return: """
try: return self.db[name_id.text] except KeyError: logger.debug("name: %s", name_id.text) #logger.debug("id sub keys: %s", self.subkeys()) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_manage_name_id_request(self, name_id, new_id=None, new_encrypted_id="", terminate=""): """ Requests from the SP is about the SPProvidedID attribute. So this is about adding,replacing and removing said attribute. :param name_id: NameID instance :param new_id: NewID instance :param new_encrypted_id: NewEncryptedID instance :param terminate: Terminate instance :return: The modified name_id """
_id = self.find_local_id(name_id) orig_name_id = copy.copy(name_id) if new_id: name_id.sp_provided_id = new_id.text elif new_encrypted_id: # TODO pass elif terminate: name_id.sp_provided_id = None else: #NOOP return name_id self.remove_remote(orig_name_id) self.store(_id, name_id) return name_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_config(self, stype="idp"): """ Remaining init of the server configuration :param stype: The type of Server ("idp"/"aa") """
if stype == "aa": return # subject information is stored in a database # default database is in memory which is OK in some setups dbspec = self.config.getattr("subject_data", "idp") idb = None typ = "" if not dbspec: idb = {} elif isinstance(dbspec, six.string_types): idb = _shelve_compat(dbspec, writeback=True, protocol=2) else: # database spec is a a 2-tuple (type, address) # print(>> sys.stderr, "DBSPEC: %s" % (dbspec,)) (typ, addr) = dbspec if typ == "shelve": idb = _shelve_compat(addr, writeback=True, protocol=2) elif typ == "memcached": import memcache idb = memcache.Client(addr) elif typ == "dict": # in-memory dictionary idb = {} elif typ == "mongodb": from saml2.mongo_store import IdentMDB self.ident = IdentMDB(database=addr, collection="ident") elif typ == "identdb": mod, clas = addr.rsplit('.', 1) mod = importlib.import_module(mod) self.ident = getattr(mod, clas)() if typ == "mongodb" or typ == "identdb": pass elif idb is not None: self.ident = IdentDB(idb) elif dbspec: raise Exception("Couldn't open identity database: %s" % (dbspec,)) try: _domain = self.config.getattr("domain", "idp") if _domain: self.ident.domain = _domain self.ident.name_qualifier = self.config.entityid dbspec = self.config.getattr("edu_person_targeted_id", "idp") if not dbspec: pass else: typ = dbspec[0] addr = dbspec[1] secret = dbspec[2] if typ == "shelve": self.eptid = EptidShelve(secret, addr) elif typ == "mongodb": from saml2.mongo_store import EptidMDB self.eptid = EptidMDB(secret, database=addr, collection="eptid") else: self.eptid = Eptid(secret) except Exception: self.ident.close() raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_authn_request(self, enc_request, binding=BINDING_HTTP_REDIRECT): """Parse a Authentication Request :param enc_request: The request in its transport format :param binding: Which binding that was used to transport the message to this entity. :return: A request instance """
return self._parse_request(enc_request, AuthnRequest, "single_sign_on_service", binding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_assertion(self, authn, sp_entity_id, in_response_to, consumer_url, name_id, policy, _issuer, authn_statement, identity, best_effort, sign_response, farg=None, session_not_on_or_after=None, **kwargs): """ Construct and return the Assertion :param authn: Authentication information :param sp_entity_id: :param in_response_to: The ID of the request this is an answer to :param consumer_url: The recipient of the assertion :param name_id: The NameID of the subject :param policy: Assertion policies :param _issuer: Issuer of the statement :param authn_statement: An AuthnStatement instance :param identity: Identity information about the Subject :param best_effort: Even if not the SPs demands can be met send a response. :param sign_response: Sign the response, only applicable if ErrorResponse :param kwargs: Extra keyword arguments :return: An Assertion instance """
ast = Assertion(identity) ast.acs = self.config.getattr("attribute_converters", "idp") if policy is None: policy = Policy() try: ast.apply_policy(sp_entity_id, policy, self.metadata) except MissingValue as exc: if not best_effort: return self.create_error_response(in_response_to, consumer_url, exc, sign_response) farg = self.update_farg(in_response_to, consumer_url, farg) if authn: # expected to be a dictionary # Would like to use dict comprehension but ... authn_args = dict( [(AUTHN_DICT_MAP[k], v) for k, v in authn.items() if k in AUTHN_DICT_MAP]) authn_args.update(kwargs) assertion = ast.construct( sp_entity_id, self.config.attribute_converters, policy, issuer=_issuer, farg=farg['assertion'], name_id=name_id, session_not_on_or_after=session_not_on_or_after, **authn_args) elif authn_statement: # Got a complete AuthnStatement assertion = ast.construct( sp_entity_id, self.config.attribute_converters, policy, issuer=_issuer, authn_statem=authn_statement, farg=farg['assertion'], name_id=name_id, **kwargs) else: assertion = ast.construct( sp_entity_id, self.config.attribute_converters, policy, issuer=_issuer, farg=farg['assertion'], name_id=name_id, session_not_on_or_after=session_not_on_or_after, **kwargs) return assertion
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _authn_response(self, in_response_to, consumer_url, sp_entity_id, identity=None, name_id=None, status=None, authn=None, issuer=None, policy=None, sign_assertion=False, sign_response=False, best_effort=False, encrypt_assertion=False, encrypt_cert_advice=None, encrypt_cert_assertion=None, authn_statement=None, encrypt_assertion_self_contained=False, encrypted_advice_attributes=False, pefim=False, sign_alg=None, digest_alg=None, farg=None, session_not_on_or_after=None): """ Create a response. A layer of indirection. :param in_response_to: The session identifier of the request :param consumer_url: The URL which should receive the response :param sp_entity_id: The entity identifier of the SP :param identity: A dictionary with attributes and values that are expected to be the bases for the assertion in the response. :param name_id: The identifier of the subject :param status: The status of the response :param authn: A dictionary containing information about the authn context. :param issuer: The issuer of the response :param policy: :param sign_assertion: Whether the assertion should be signed or not :param sign_response: Whether the response should be signed or not :param best_effort: Even if not the SPs demands can be met send a response. :param encrypt_assertion: True if assertions should be encrypted. :param encrypt_assertion_self_contained: True if all encrypted assertions should have alla namespaces selfcontained. :param encrypted_advice_attributes: True if assertions in the advice element should be encrypted. :param encrypt_cert_advice: Certificate to be used for encryption of assertions in the advice element. :param encrypt_cert_assertion: Certificate to be used for encryption of assertions. :param authn_statement: Authentication statement. :param sign_assertion: True if assertions should be signed. :param pefim: True if a response according to the PEFIM profile should be created. :param farg: Argument to pass on to the assertion constructor :return: A response instance """
if farg is None: assertion_args = {} args = {} # if identity: _issuer = self._issuer(issuer) # if encrypt_assertion and show_nameid: # tmp_name_id = name_id # name_id = None # name_id = None # tmp_authn = authn # authn = None # tmp_authn_statement = authn_statement # authn_statement = None if pefim: encrypted_advice_attributes = True encrypt_assertion_self_contained = True assertion_attributes = self.setup_assertion( None, sp_entity_id, None, None, None, policy, None, None, identity, best_effort, sign_response, farg=farg) assertion = self.setup_assertion( authn, sp_entity_id, in_response_to, consumer_url, name_id, policy, _issuer, authn_statement, [], True, sign_response, farg=farg, session_not_on_or_after=session_not_on_or_after) assertion.advice = saml.Advice() # assertion.advice.assertion_id_ref.append(saml.AssertionIDRef()) # assertion.advice.assertion_uri_ref.append(saml.AssertionURIRef()) assertion.advice.assertion.append(assertion_attributes) else: assertion = self.setup_assertion( authn, sp_entity_id, in_response_to, consumer_url, name_id, policy, _issuer, authn_statement, identity, True, sign_response, farg=farg, session_not_on_or_after=session_not_on_or_after) to_sign = [] if not encrypt_assertion: if sign_assertion: assertion.signature = pre_signature_part(assertion.id, self.sec.my_cert, 2, sign_alg=sign_alg, digest_alg=digest_alg) to_sign.append((class_name(assertion), assertion.id)) args["assertion"] = assertion if (self.support_AssertionIDRequest() or self.support_AuthnQuery()): self.session_db.store_assertion(assertion, to_sign) return self._response( in_response_to, consumer_url, status, issuer, sign_response, to_sign, sp_entity_id=sp_entity_id, encrypt_assertion=encrypt_assertion, encrypt_cert_advice=encrypt_cert_advice, encrypt_cert_assertion=encrypt_cert_assertion, encrypt_assertion_self_contained=encrypt_assertion_self_contained, encrypted_advice_attributes=encrypted_advice_attributes, sign_assertion=sign_assertion, pefim=pefim, sign_alg=sign_alg, digest_alg=digest_alg, **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_attribute_response(self, identity, in_response_to, destination, sp_entity_id, userid="", name_id=None, status=None, issuer=None, sign_assertion=False, sign_response=False, attributes=None, sign_alg=None, digest_alg=None, farg=None, **kwargs): """ Create an attribute assertion response. :param identity: A dictionary with attributes and values that are expected to be the bases for the assertion in the response. :param in_response_to: The session identifier of the request :param destination: The URL which should receive the response :param sp_entity_id: The entity identifier of the SP :param userid: A identifier of the user :param name_id: The identifier of the subject :param status: The status of the response :param issuer: The issuer of the response :param sign_assertion: Whether the assertion should be signed or not :param sign_response: Whether the whole response should be signed :param attributes: :param kwargs: To catch extra keyword arguments :return: A response instance """
policy = self.config.getattr("policy", "aa") if not name_id and userid: try: name_id = self.ident.construct_nameid(userid, policy, sp_entity_id) logger.warning("Unspecified NameID format") except Exception: pass to_sign = [] if identity: farg = self.update_farg(in_response_to, sp_entity_id, farg=farg) _issuer = self._issuer(issuer) ast = Assertion(identity) if policy: ast.apply_policy(sp_entity_id, policy, self.metadata) else: policy = Policy() if attributes: restr = restriction_from_attribute_spec(attributes) ast = filter_attribute_value_assertions(ast) assertion = ast.construct( sp_entity_id, self.config.attribute_converters, policy, issuer=_issuer, name_id=name_id, farg=farg['assertion']) if sign_assertion: assertion.signature = pre_signature_part(assertion.id, self.sec.my_cert, 1, sign_alg=sign_alg, digest_alg=digest_alg) # Just the assertion or the response and the assertion ? to_sign = [(class_name(assertion), assertion.id)] kwargs['sign_assertion'] = True kwargs["assertion"] = assertion if sp_entity_id: kwargs['sp_entity_id'] = sp_entity_id return self._response(in_response_to, destination, status, issuer, sign_response, to_sign, sign_alg=sign_alg, digest_alg=digest_alg, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_authn_response(self, identity, in_response_to, destination, sp_entity_id, name_id_policy=None, userid=None, name_id=None, authn=None, issuer=None, sign_response=None, sign_assertion=None, encrypt_cert_advice=None, encrypt_cert_assertion=None, encrypt_assertion=None, encrypt_assertion_self_contained=True, encrypted_advice_attributes=False, pefim=False, sign_alg=None, digest_alg=None, session_not_on_or_after=None, **kwargs): """ Constructs an AuthenticationResponse :param identity: Information about an user :param in_response_to: The identifier of the authentication request this response is an answer to. :param destination: Where the response should be sent :param sp_entity_id: The entity identifier of the Service Provider :param name_id_policy: How the NameID should be constructed :param userid: The subject identifier :param name_id: The identifier of the subject. A saml.NameID instance. :param authn: Dictionary with information about the authentication context :param issuer: Issuer of the response :param sign_assertion: Whether the assertion should be signed or not. :param sign_response: Whether the response should be signed or not. :param encrypt_assertion: True if assertions should be encrypted. :param encrypt_assertion_self_contained: True if all encrypted assertions should have alla namespaces selfcontained. :param encrypted_advice_attributes: True if assertions in the advice element should be encrypted. :param encrypt_cert_advice: Certificate to be used for encryption of assertions in the advice element. :param encrypt_cert_assertion: Certificate to be used for encryption of assertions. :param sign_assertion: True if assertions should be signed. :param pefim: True if a response according to the PEFIM profile should be created. :return: A response instance """
try: args = self.gather_authn_response_args( sp_entity_id, name_id_policy=name_id_policy, userid=userid, name_id=name_id, sign_response=sign_response, sign_assertion=sign_assertion, encrypt_cert_advice=encrypt_cert_advice, encrypt_cert_assertion=encrypt_cert_assertion, encrypt_assertion=encrypt_assertion, encrypt_assertion_self_contained =encrypt_assertion_self_contained, encrypted_advice_attributes=encrypted_advice_attributes, pefim=pefim, **kwargs) except IOError as exc: response = self.create_error_response(in_response_to, destination, sp_entity_id, exc, name_id) return ("%s" % response).split("\n") try: _authn = authn if (sign_assertion or sign_response) and \ self.sec.cert_handler.generate_cert(): with self.lock: self.sec.cert_handler.update_cert(True) return self._authn_response( in_response_to, destination, sp_entity_id, identity, authn=_authn, issuer=issuer, pefim=pefim, sign_alg=sign_alg, digest_alg=digest_alg, session_not_on_or_after=session_not_on_or_after, **args) return self._authn_response( in_response_to, destination, sp_entity_id, identity, authn=_authn, issuer=issuer, pefim=pefim, sign_alg=sign_alg, digest_alg=digest_alg, session_not_on_or_after=session_not_on_or_after, **args) except MissingValue as exc: return self.create_error_response(in_response_to, destination, sp_entity_id, exc, name_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_name_id_mapping_response(self, name_id=None, encrypted_id=None, in_response_to=None, issuer=None, sign_response=False, status=None, sign_alg=None, digest_alg=None, **kwargs): """ protocol for mapping a principal's name identifier into a different name identifier for the same principal. Done over soap. :param name_id: :param encrypted_id: :param in_response_to: :param issuer: :param sign_response: :param status: :return: """
# Done over SOAP ms_args = self.message_args() _resp = NameIDMappingResponse(name_id, encrypted_id, in_response_to=in_response_to, **ms_args) if sign_response: return self.sign(_resp, sign_alg=sign_alg, digest_alg=digest_alg) else: logger.info("Message: %s", _resp) return _resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_out_user(self, name_id): """ Remove all authentication statements that belongs to a user identified by a NameID instance :param name_id: NameID instance :return: The local identifier for the user """
lid = self.ident.find_local_id(name_id) logger.info("Clean out %s", lid) # remove the authentications try: for _nid in [decode(x) for x in self.ident.db[lid].split(" ")]: try: self.session_db.remove_authn_statements(_nid) except KeyError: pass except KeyError: pass return lid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mdb_get_database(uri, **kwargs): """ Helper-function to connect to MongoDB and return a database object. The `uri' argument should be either a full MongoDB connection URI string, or just a database name in which case a connection to the default mongo instance at mongodb://localhost:27017 will be made. Performs explicit authentication if a username is provided in a connection string URI, since PyMongo does not always seem to do that as promised. :params database: name as string or (uri, name) :returns: pymongo database object """
if not "tz_aware" in kwargs: # default, but not forced kwargs["tz_aware"] = True connection_factory = MongoClient _parsed_uri = {} try: _parsed_uri = pymongo.uri_parser.parse_uri(uri) except pymongo.errors.InvalidURI: # assume URI to be just the database name db_name = uri _conn = MongoClient() pass else: if "replicaset" in _parsed_uri["options"]: connection_factory = MongoReplicaSetClient db_name = _parsed_uri.get("database", "pysaml2") _conn = connection_factory(uri, **kwargs) _db = _conn[db_name] if "username" in _parsed_uri: _db.authenticate( _parsed_uri.get("username", None), _parsed_uri.get("password", None) ) return _db
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_path(tdict, path): """ Create or extend an argument tree `tdict` from `path`. :param tdict: a dictionary representing a argument tree :param path: a path list :return: a dictionary Convert a list of items in a 'path' into a nested dict, where the second to last item becomes the key for the final item. The remaining items in the path become keys in the nested dict around that final pair of items. For example, for input values of: tdict={} path = ['assertion', 'subject', 'subject_confirmation', 'method', 'urn:oasis:names:tc:SAML:2.0:cm:bearer'] Returns an output value of: {'assertion': {'subject': {'subject_confirmation': {'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}}}} Another example, this time with a non-empty tdict input: tdict={'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}, path=['subject_confirmation_data', 'in_response_to', '_012345'] Returns an output value of: {'subject_confirmation_data': {'in_response_to': '_012345'}, 'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'} """
t = tdict for step in path[:-2]: try: t = t[step] except KeyError: t[step] = {} t = t[step] t[path[-2]] = path[-1] return tdict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valid_email(emailaddress, domains=GENERIC_DOMAINS): """Checks for a syntactically valid email address."""
# Email address must be at least 6 characters in total. # Assuming noone may have addresses of the type a@com if len(emailaddress) < 6: return False # Address too short. # Split up email address into parts. try: localpart, domainname = emailaddress.rsplit('@', 1) host, toplevel = domainname.rsplit('.', 1) except ValueError: return False # Address does not have enough parts. # Check for Country code or Generic Domain. if len(toplevel) != 2 and toplevel not in domains: return False # Not a domain name. for i in '-_.%+.': localpart = localpart.replace(i, "") for i in '-_.': host = host.replace(i, "") if localpart.isalnum() and host.isalnum(): return True # Email address is fine. else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deflate_and_base64_encode(string_val): """ Deflates and the base64 encodes a string :param string_val: The string to deflate and encode :return: The deflated and encoded string """
if not isinstance(string_val, six.binary_type): string_val = string_val.encode('utf-8') return base64.b64encode(zlib.compress(string_val)[2:-4])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rndbytes(size=16, alphabet=""): """ Returns rndstr always as a binary type """
x = rndstr(size, alphabet) if isinstance(x, six.string_types): return x.encode('utf-8') return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_attribute_map(filenames): """ Expects a file with each line being composed of the oid for the attribute exactly one space, a user friendly name of the attribute and then the type specification of the name. :param filenames: List of filenames on mapfiles. :return: A 2-tuple, one dictionary with the oid as keys and the friendly names as values, the other one the other way around. """
forward = {} backward = {} for filename in filenames: with open(filename) as fp: for line in fp: (name, friendly_name, name_format) = line.strip().split() forward[(name, name_format)] = friendly_name backward[friendly_name] = (name, name_format) return forward, backward
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signature(secret, parts): """Generates a signature. All strings are assumed to be utf-8 """
if not isinstance(secret, six.binary_type): secret = secret.encode('utf-8') newparts = [] for part in parts: if not isinstance(part, six.binary_type): part = part.encode('utf-8') newparts.append(part) parts = newparts if sys.version_info >= (2, 5): csum = hmac.new(secret, digestmod=hashlib.sha1) else: csum = hmac.new(secret, digestmod=sha) for part in parts: csum.update(part) return csum.hexdigest()