_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 75 19.8k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q36300 | Etcd3Client.snapshot | train | def snapshot(self, file_obj):
"""Take a snapshot of the database.
:param file_obj: A file-like object to write the database contents in.
"""
snapshot_request = etcdrpc.SnapshotRequest()
snapshot_response = self.maintenancestub.Snapshot(
snapshot_request,
self.timeout,
credentials=self.call_credentials,
metadata=self.metadata
)
for response in snapshot_response:
file_obj.write(response.blob) | python | {
"resource": ""
} |
q36301 | PixelClassifier.extract_pixels | train | def extract_pixels(X):
""" Extract pixels from array X
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: Reshaped 2D array
:rtype: numpy array, [n_samples*n_pixels_y*n_pixels_x,n_bands]
:raises: ValueError is input array has wrong dimensions
"""
if len(X.shape) != 4:
raise ValueError('Array of input images has to be a 4-dimensional array of shape'
'[n_images, n_pixels_y, n_pixels_x, n_bands]')
new_shape = (X.shape[0] * X.shape[1] * X.shape[2], X.shape[3],)
pixels = X.reshape(new_shape)
return pixels | python | {
"resource": ""
} |
q36302 | PixelClassifier.image_predict | train | def image_predict(self, X):
"""
Predicts class label for the entire image.
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: raster classification map
:rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x]
"""
pixels = self.extract_pixels(X)
predictions = self.classifier.predict(pixels)
return predictions.reshape(X.shape[0], X.shape[1], X.shape[2]) | python | {
"resource": ""
} |
q36303 | PixelClassifier.image_predict_proba | train | def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: classification probability map
:rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x]
"""
pixels = self.extract_pixels(X)
probabilities = self.classifier.predict_proba(pixels)
return probabilities.reshape(X.shape[0], X.shape[1], X.shape[2], probabilities.shape[1]) | python | {
"resource": ""
} |
q36304 | CloudMaskRequest._prepare_ogc_request_params | train | def _prepare_ogc_request_params(self):
""" Method makes sure that correct parameters will be used for download of S-2 bands.
"""
self.ogc_request.image_format = MimeType.TIFF_d32f
if self.ogc_request.custom_url_params is None:
self.ogc_request.custom_url_params = {}
self.ogc_request.custom_url_params.update({
CustomUrlParam.SHOWLOGO: False,
CustomUrlParam.TRANSPARENT: True,
CustomUrlParam.EVALSCRIPT: S2_BANDS_EVALSCRIPT if self.all_bands else MODEL_EVALSCRIPT,
CustomUrlParam.ATMFILTER: 'NONE'
})
self.ogc_request.create_request(reset_wfs_iterator=False) | python | {
"resource": ""
} |
q36305 | CloudMaskRequest._set_band_and_valid_mask | train | def _set_band_and_valid_mask(self):
""" Downloads band data and valid mask. Sets parameters self.bands, self.valid_data
"""
data = np.asarray(self.ogc_request.get_data())
self.bands = data[..., :-1]
self.valid_data = (data[..., -1] == 1.0).astype(np.bool) | python | {
"resource": ""
} |
q36306 | CloudMaskRequest.get_probability_masks | train | def get_probability_masks(self, non_valid_value=0):
"""
Get probability maps of areas for each available date. The pixels without valid data are assigned
non_valid_value.
:param non_valid_value: Value to be assigned to non valid data pixels
:type non_valid_value: float
:return: Probability map of shape `(times, height, width)` and `dtype=numpy.float64`
:rtype: numpy.ndarray
"""
if self.probability_masks is None:
self.get_data()
self.probability_masks = self.cloud_detector.get_cloud_probability_maps(self.bands)
self.probability_masks[~self.valid_data] = non_valid_value
return self.probability_masks | python | {
"resource": ""
} |
q36307 | CloudMaskRequest.get_cloud_masks | train | def get_cloud_masks(self, threshold=None, non_valid_value=False):
""" The binary cloud mask is computed on the fly. Be cautious. The pixels without valid data are assigned
non_valid_value.
:param threshold: A float from [0,1] specifying threshold
:type threshold: float
:param non_valid_value: Value which will be assigned to pixels without valid data
:type non_valid_value: int in range `[-254, 255]`
:return: Binary cloud masks of shape `(times, height, width)` and `dtype=numpy.int8`
:rtype: numpy.ndarray
"""
self.get_probability_masks()
cloud_masks = self.cloud_detector.get_mask_from_prob(self.probability_masks, threshold)
cloud_masks[~self.valid_data] = non_valid_value
return cloud_masks | python | {
"resource": ""
} |
q36308 | Base.add_vo_information_about_user | train | def add_vo_information_about_user(self, name_id):
""" Add information to the knowledge I have about the user. This is
for Virtual organizations.
:param name_id: The subject identifier
:return: A possibly extended knowledge.
"""
ava = {}
try:
(ava, _) = self.users.get_identity(name_id)
except KeyError:
pass
# is this a Virtual Organization situation
if self.vorg:
if self.vorg.do_aggregation(name_id):
# Get the extended identity
ava = self.users.get_identity(name_id)[0]
return ava | python | {
"resource": ""
} |
q36309 | Base.create_attribute_query | train | def create_attribute_query(self, destination, name_id=None,
attribute=None, message_id=0, consent=None,
extensions=None, sign=False, sign_prepare=False, sign_alg=None,
digest_alg=None,
**kwargs):
""" Constructs an AttributeQuery
:param destination: To whom the query should be sent
:param name_id: The identifier of the subject
:param attribute: A dictionary of attributes and values that is
asked for. The key are one of 4 variants:
3-tuple of name_format,name and friendly_name,
2-tuple of name_format and name,
1-tuple with name or
just the name as a string.
: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 format: The format of the name ID
:param message_id: The identifier of the session
:param consent: Whether the principal have given her consent
:param extensions: Possible extensions
:param sign: Whether the query should be signed or not.
:param sign_prepare: Whether the Signature element should be added.
:return: Tuple of request ID and an AttributeQuery instance
"""
if name_id is None:
if "subject_id" in kwargs:
name_id = saml.NameID(text=kwargs["subject_id"])
for key in ["sp_name_qualifier", "name_qualifier",
"format"]:
try:
setattr(name_id, key, kwargs[key])
except KeyError:
pass
else:
raise AttributeError("Missing required parameter")
elif isinstance(name_id, six.string_types):
name_id = saml.NameID(text=name_id)
for key in ["sp_name_qualifier", "name_qualifier", "format"]:
try:
setattr(name_id, key, kwargs[key])
except KeyError:
pass
subject = saml.Subject(name_id=name_id)
if attribute:
attribute = do_attributes(attribute)
try:
nsprefix = kwargs["nsprefix"]
except KeyError:
nsprefix = None
return self._message(AttributeQuery, destination, message_id, consent,
extensions, sign, sign_prepare, subject=subject,
attribute=attribute, nsprefix=nsprefix,
sign_alg=sign_alg, digest_alg=digest_alg) | python | {
"resource": ""
} |
q36310 | Base.create_authz_decision_query | train | def create_authz_decision_query(self, destination, action,
evidence=None, resource=None, subject=None,
message_id=0, consent=None, extensions=None,
sign=None, sign_alg=None, digest_alg=None, **kwargs):
""" Creates an authz decision query.
:param destination: The IdP endpoint
:param action: The action you want to perform (has to be at least one)
:param evidence: Why you should be able to perform the action
:param resource: The resource you want to perform the action on
:param subject: Who wants to do the thing
:param message_id: Message identifier
:param consent: If the principal gave her consent to this request
:param extensions: Possible request extensions
:param sign: Whether the request should be signed or not.
:return: AuthzDecisionQuery instance
"""
return self._message(AuthzDecisionQuery, destination, message_id,
consent, extensions, sign, action=action,
evidence=evidence, resource=resource,
subject=subject, sign_alg=sign_alg,
digest_alg=digest_alg, **kwargs) | python | {
"resource": ""
} |
q36311 | Base.create_authz_decision_query_using_assertion | train | def create_authz_decision_query_using_assertion(self, destination,
assertion, action=None,
resource=None,
subject=None, message_id=0,
consent=None,
extensions=None,
sign=False, nsprefix=None):
""" Makes an authz decision query based on a previously received
Assertion.
:param destination: The IdP endpoint to send the request to
:param assertion: An Assertion instance
:param action: The action you want to perform (has to be at least one)
:param resource: The resource you want to perform the action on
:param subject: Who wants to do the thing
:param message_id: Message identifier
:param consent: If the principal gave her consent to this request
:param extensions: Possible request extensions
:param sign: Whether the request should be signed or not.
:return: AuthzDecisionQuery instance
"""
if action:
if isinstance(action, six.string_types):
_action = [saml.Action(text=action)]
else:
_action = [saml.Action(text=a) for a in action]
else:
_action = None
return self.create_authz_decision_query(
destination, _action, saml.Evidence(assertion=assertion),
resource, subject, message_id=message_id, consent=consent,
extensions=extensions, sign=sign, nsprefix=nsprefix) | python | {
"resource": ""
} |
q36312 | Base.parse_authn_request_response | train | def parse_authn_request_response(self, xmlstr, binding, outstanding=None,
outstanding_certs=None, conv_info=None):
""" Deal with an AuthnResponse
:param xmlstr: The reply as a xml string
:param binding: Which binding that was used for the transport
:param outstanding: A dictionary with session IDs as keys and
the original web request from the user before redirection
as values.
:param outstanding_certs:
:param conv_info: Information about the conversation.
:return: An response.AuthnResponse or None
"""
if not getattr(self.config, 'entityid', None):
raise SAMLError("Missing entity_id specification")
if not xmlstr:
return None
kwargs = {
"outstanding_queries": outstanding,
"outstanding_certs": outstanding_certs,
"allow_unsolicited": self.allow_unsolicited,
"want_assertions_signed": self.want_assertions_signed,
"want_assertions_or_response_signed": self.want_assertions_or_response_signed,
"want_response_signed": self.want_response_signed,
"return_addrs": self.service_urls(binding=binding),
"entity_id": self.config.entityid,
"attribute_converters": self.config.attribute_converters,
"allow_unknown_attributes":
self.config.allow_unknown_attributes,
'conv_info': conv_info
}
try:
resp = self._parse_response(xmlstr, AuthnResponse,
"assertion_consumer_service",
binding, **kwargs)
except StatusError as err:
logger.error("SAML status error: %s", err)
raise
except UnravelError:
return None
except Exception as err:
logger.error("XML parse error: %s", err)
raise
if not isinstance(resp, AuthnResponse):
logger.error("Response type not supported: %s",
saml2.class_name(resp))
return None
if (resp.assertion and len(resp.response.encrypted_assertion) == 0 and
resp.assertion.subject.name_id):
self.users.add_information_about_person(resp.session_info())
logger.info("--- ADDED person info ----")
return resp | python | {
"resource": ""
} |
q36313 | Base.create_discovery_service_request | train | 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) | python | {
"resource": ""
} |
q36314 | Base.parse_discovery_service_response | train | 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 "" | python | {
"resource": ""
} |
q36315 | filter_on_demands | train | 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 | python | {
"resource": ""
} |
q36316 | filter_attribute_value_assertions | train | 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 | python | {
"resource": ""
} |
q36317 | Policy.compile | train | 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 | python | {
"resource": ""
} |
q36318 | Policy.conditions | train | 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)])]) | python | {
"resource": ""
} |
q36319 | Assertion.construct | train | 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 | python | {
"resource": ""
} |
q36320 | Assertion.apply_policy | train | 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 | python | {
"resource": ""
} |
q36321 | application | train | 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) | python | {
"resource": ""
} |
q36322 | Service.soap | train | 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) | python | {
"resource": ""
} |
q36323 | SSO._pick_idp | train | 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 | python | {
"resource": ""
} |
q36324 | valid_any_uri | train | def valid_any_uri(item):
"""very simplistic, ..."""
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 | python | {
"resource": ""
} |
q36325 | valid_anytype | train | 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") | python | {
"resource": ""
} |
q36326 | load_maps | train | 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 | python | {
"resource": ""
} |
q36327 | ac_factory | train | 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 | python | {
"resource": ""
} |
q36328 | AttributeConverter.adjust | train | 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()]) | python | {
"resource": ""
} |
q36329 | AttributeConverter.from_dict | train | 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() | python | {
"resource": ""
} |
q36330 | AttributeConverter.lcd_ava_from | train | 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 | python | {
"resource": ""
} |
q36331 | AttributeConverter.fail_safe_fro | train | 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 | python | {
"resource": ""
} |
q36332 | AttributeConverter.fro | train | 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 | python | {
"resource": ""
} |
q36333 | AttributeConverter.to_format | train | 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) | python | {
"resource": ""
} |
q36334 | my_request_classifier | train | 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" | python | {
"resource": ""
} |
q36335 | _localized_name | train | 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") | python | {
"resource": ""
} |
q36336 | do_contact_person_info | train | 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 | python | {
"resource": ""
} |
q36337 | do_pdp_descriptor | train | 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 | python | {
"resource": ""
} |
q36338 | create_return_url | train | 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)) | python | {
"resource": ""
} |
q36339 | Entity._issuer | train | 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) | python | {
"resource": ""
} |
q36340 | Entity.apply_binding | train | 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 | python | {
"resource": ""
} |
q36341 | Entity._message | train | 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 | python | {
"resource": ""
} |
q36342 | Entity._add_info | train | 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 | python | {
"resource": ""
} |
q36343 | Entity.has_encrypt_cert_in_metadata | train | 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 | python | {
"resource": ""
} |
q36344 | Entity._encrypt_assertion | train | 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 | python | {
"resource": ""
} |
q36345 | Entity._status_response | train | 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 | python | {
"resource": ""
} |
q36346 | Entity._parse_request | train | 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 | python | {
"resource": ""
} |
q36347 | Entity.create_error_response | train | 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) | python | {
"resource": ""
} |
q36348 | Entity.create_logout_request | train | 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) | python | {
"resource": ""
} |
q36349 | Entity.create_logout_response | train | 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 | python | {
"resource": ""
} |
q36350 | Entity.create_artifact_resolve | train | 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) | python | {
"resource": ""
} |
q36351 | Entity._parse_response | train | 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 | python | {
"resource": ""
} |
q36352 | Entity.artifact2destination | train | 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 | python | {
"resource": ""
} |
q36353 | Saml2Client.prepare_for_authenticate | train | 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 | python | {
"resource": ""
} |
q36354 | Saml2Client.prepare_for_negotiated_authenticate | train | 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") | python | {
"resource": ""
} |
q36355 | Saml2Client.is_logged_in | train | 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) | python | {
"resource": ""
} |
q36356 | Saml2Client.handle_logout_response | train | 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) | python | {
"resource": ""
} |
q36357 | Saml2Client.do_attribute_query | train | 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") | python | {
"resource": ""
} |
q36358 | before | train | 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 | python | {
"resource": ""
} |
q36359 | Client.phase2 | train | 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 | python | {
"resource": ""
} |
q36360 | Client.operation | train | 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 | python | {
"resource": ""
} |
q36361 | Cache.subjects | train | 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)) | python | {
"resource": ""
} |
q36362 | Cache.set | train | 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 | python | {
"resource": ""
} |
q36363 | create_class_from_xml_string | train | 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) | python | {
"resource": ""
} |
q36364 | create_class_from_element_tree | train | 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 | python | {
"resource": ""
} |
q36365 | element_to_extension_element | train | 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 | python | {
"resource": ""
} |
q36366 | extension_element_to_element | train | 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 | python | {
"resource": ""
} |
q36367 | extension_elements_to_elements | train | 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 | python | {
"resource": ""
} |
q36368 | ExtensionElement.loadd | train | 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 | python | {
"resource": ""
} |
q36369 | ExtensionContainer.find_extensions | train | 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 | python | {
"resource": ""
} |
q36370 | ExtensionContainer.extensions_as_elements | train | 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 | python | {
"resource": ""
} |
q36371 | SamlBase.register_prefix | train | 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 | python | {
"resource": ""
} |
q36372 | SamlBase.get_xml_string_with_self_contained_assertion_within_encrypted_assertion | train | 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') | python | {
"resource": ""
} |
q36373 | SamlBase.to_string | train | 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") | python | {
"resource": ""
} |
q36374 | SamlBase.keys | train | 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 | python | {
"resource": ""
} |
q36375 | SamlBase.children_with_values | train | 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 | python | {
"resource": ""
} |
q36376 | SamlBase.set_text | train | 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 | python | {
"resource": ""
} |
q36377 | SamlBase.child_class | train | 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 | python | {
"resource": ""
} |
q36378 | SamlBase.child_cardinality | train | 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 | python | {
"resource": ""
} |
q36379 | Cache.reset | train | 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") | python | {
"resource": ""
} |
q36380 | Population.add_information_about_person | train | 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 | python | {
"resource": ""
} |
q36381 | AuthnBroker.add | train | 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] | python | {
"resource": ""
} |
q36382 | AuthnBroker.pick | train | 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) | python | {
"resource": ""
} |
q36383 | load_pem_private_key | train | def load_pem_private_key(data, password):
"""Load RSA PEM certificate."""
key = _serialization.load_pem_private_key(
data, password, _backends.default_backend())
return key | python | {
"resource": ""
} |
q36384 | key_sign | train | 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 | python | {
"resource": ""
} |
q36385 | key_verify | train | 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 | python | {
"resource": ""
} |
q36386 | Request.subject_id | train | 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 | python | {
"resource": ""
} |
q36387 | to_dict | train | 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 | python | {
"resource": ""
} |
q36388 | _kwa | train | 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]) | python | {
"resource": ""
} |
q36389 | SSO.redirect | train | 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) | python | {
"resource": ""
} |
q36390 | SSO.post | train | 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) | python | {
"resource": ""
} |
q36391 | code | train | 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) | python | {
"resource": ""
} |
q36392 | code_binary | train | 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 | python | {
"resource": ""
} |
q36393 | IdentDB.remove_remote | train | 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] | python | {
"resource": ""
} |
q36394 | IdentDB.find_nameid | train | 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 | python | {
"resource": ""
} |
q36395 | IdentDB.construct_nameid | train | 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) | python | {
"resource": ""
} |
q36396 | IdentDB.find_local_id | train | 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 | python | {
"resource": ""
} |
q36397 | IdentDB.handle_manage_name_id_request | train | 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 | python | {
"resource": ""
} |
q36398 | Server.init_config | train | 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 | python | {
"resource": ""
} |
q36399 | Server.parse_authn_request | train | 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) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.