diff options
author | Aarni Koskela <akx@iki.fi> | 2022-10-27 15:14:12 +0300 |
---|---|---|
committer | Ivan Kanakarakis <ivan.kanak@gmail.com> | 2022-11-15 13:06:41 +0200 |
commit | 15f131d08a0905662bc578d1d9c7d8fa8d8fda43 (patch) | |
tree | 2c364fefc8d79c56dca8bef530c20141f6d4a39b /src | |
parent | 3824f60d97ea977c852d6e256b8a38e9d029e405 (diff) | |
download | pysaml2-15f131d08a0905662bc578d1d9c7d8fa8d8fda43.tar.gz |
Run flynt + black + isort
Diffstat (limited to 'src')
30 files changed, 129 insertions, 144 deletions
diff --git a/src/saml2/__init__.py b/src/saml2/__init__.py index 6259373c..c5142c55 100644 --- a/src/saml2/__init__.py +++ b/src/saml2/__init__.py @@ -587,7 +587,7 @@ class SamlBase(ExtensionContainer): uri_set = self.get_ns_map(elements, set()) prefix_map = {} for uri in sorted(uri_set): - prefix_map["encas%d" % len(prefix_map)] = uri + prefix_map[f"encas{len(prefix_map)}"] = uri return prefix_map def get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(self, assertion_tag, advice_tag): @@ -743,7 +743,7 @@ class SamlBase(ExtensionContainer): elif val is None: pass else: - raise ValueError("Type shouldn't be '%s'" % val) + raise ValueError(f"Type shouldn't be '{val}'") return self diff --git a/src/saml2/assertion.py b/src/saml2/assertion.py index 08c4f908..344c7863 100644 --- a/src/saml2/assertion.py +++ b/src/saml2/assertion.py @@ -117,7 +117,7 @@ def filter_on_attributes(ava, required=None, optional=None, acs=None, fail_on_un if _fn: _apply_attr_value_restrictions(attr, res, True) elif fail_on_unfulfilled_requirements: - desc = "Required attribute missing: '%s'" % (attr["name"]) + desc = f"Required attribute missing: '{attr['name']}'" raise MissingValue(desc) if optional is None: @@ -284,7 +284,7 @@ def compile(restrictions): try: _mod = importlib.import_module(cat) except ImportError: - _mod = importlib.import_module("saml2.entity_category.%s" % cat) + _mod = importlib.import_module(f"saml2.entity_category.{cat}") _ec = {} for key, items in _mod.RELEASE.items(): @@ -788,7 +788,7 @@ class Assertion(dict): if encrypt == "attributes": for attr in attr_statement.attribute: - enc = sec_context.encrypt(text="%s" % attr) + enc = sec_context.encrypt(text=f"{attr}") encd = xmlenc.encrypted_data_from_string(enc) encattr = saml.EncryptedAttribute(encrypted_data=encd) diff --git a/src/saml2/attribute_converter.py b/src/saml2/attribute_converter.py index 505d1564..7e86b917 100644 --- a/src/saml2/attribute_converter.py +++ b/src/saml2/attribute_converter.py @@ -70,7 +70,7 @@ def ac_factory(path=""): from saml2 import attributemaps for typ in attributemaps.__all__: - mod = import_module(".%s" % typ, "saml2.attributemaps") + mod = import_module(f".{typ}", "saml2.attributemaps") acs.extend(_attribute_map_module_to_acs(mod)) return acs @@ -223,7 +223,7 @@ def d_to_local_name(acs, attr): try: return attr["friendly_name"] except KeyError: - raise ConverterError("Could not find local name for %s" % attr) + raise ConverterError(f"Could not find local name for {attr}") class AttributeConverter: diff --git a/src/saml2/authn.py b/src/saml2/authn.py index a7ef3355..dfd0a925 100644 --- a/src/saml2/authn.py +++ b/src/saml2/authn.py @@ -97,7 +97,7 @@ def create_return_url(base, query, **kwargs): else: _pre = base - logger.debug("kwargs: %s" % kwargs) + logger.debug(f"kwargs: {kwargs}") return f"{_pre}?{url_encode_params(kwargs)}" @@ -144,7 +144,7 @@ class UsernamePasswordMako(UserAuthnMethod): "logo_url": logo_url, "query": query, } - logger.debug("do_authentication argv: %s" % argv) + logger.debug(f"do_authentication argv: {argv}") mte = self.template_lookup.get_template(self.mako_template) resp.message = mte.render(**argv) return resp @@ -190,7 +190,7 @@ class UsernamePasswordMako(UserAuthnMethod): if cookie is None: return None else: - logger.debug("kwargs: %s" % kwargs) + logger.debug(f"kwargs: {kwargs}") try: info, timestamp = parse_cookie(self.cookie_name, self.srv.seed, cookie) if self.active[info] == timestamp: diff --git a/src/saml2/cache.py b/src/saml2/cache.py index 56351fe7..5aaddbdb 100644 --- a/src/saml2/cache.py +++ b/src/saml2/cache.py @@ -104,7 +104,7 @@ class Cache: (timestamp, info) = self._db[cni][entity_id] info = info.copy() if check_not_on_or_after and time_util.after(timestamp): - raise TooOld("past %s" % str(timestamp)) + raise TooOld(f"past {str(timestamp)}") if "name_id" in info and isinstance(info["name_id"], str): info["name_id"] = decode(info["name_id"]) diff --git a/src/saml2/cert.py b/src/saml2/cert.py index 247b9f56..c5f62660 100644 --- a/src/saml2/cert.py +++ b/src/saml2/cert.py @@ -117,8 +117,8 @@ class OpenSSLWrapper: k_f = None if write_to_file: - cert_file = "%s.crt" % cn - key_file = "%s.key" % cn + cert_file = f"{cn}.crt" + key_file = f"{cn}.key" try: remove(cert_file) except Exception: @@ -331,9 +331,9 @@ class OpenSSLWrapper: crypto.verify(ca_cert, cert_crypto.signature, cert_crypto.tbs_certificate_bytes, cert_algorithm) return True, "Signed certificate is valid and correctly signed by CA certificate." except crypto.Error as e: - return False, "Certificate is incorrectly signed: %s" % str(e) + return False, f"Certificate is incorrectly signed: {str(e)}" except Exception as e: - return False, "Certificate is not valid for an unknown reason. %s" % str(e) + return False, f"Certificate is not valid for an unknown reason. {str(e)}" def read_cert_from_file(cert_file, cert_type="pem"): diff --git a/src/saml2/client.py b/src/saml2/client.py index 4f947954..1a40258d 100644 --- a/src/saml2/client.py +++ b/src/saml2/client.py @@ -427,8 +427,8 @@ class Saml2Client(Base): ) def _use_soap(self, destination, query_type, **kwargs): - _create_func = getattr(self, "create_%s" % query_type) - _response_func = getattr(self, "parse_%s_response" % query_type) + _create_func = getattr(self, f"create_{query_type}") + _response_func = getattr(self, f"parse_{query_type}_response") try: response_args = kwargs["response_args"] del kwargs["response_args"] @@ -501,7 +501,7 @@ class Saml2Client(Base): srvs = self.metadata.assertion_id_request_service(entity_id, BINDING_SOAP) if not srvs: - raise NoServiceDefined("{}: {}".format(entity_id, "assertion_id_request_service")) + raise NoServiceDefined(f"{entity_id}: assertion_id_request_service") if isinstance(assertion_ids, str): assertion_ids = [assertion_ids] diff --git a/src/saml2/client_base.py b/src/saml2/client_base.py index 8b548c44..673dae75 100644 --- a/src/saml2/client_base.py +++ b/src/saml2/client_base.py @@ -220,7 +220,7 @@ class Base(Entity): # IdP in the configuration raise exception eids = self.metadata.with_descriptor("idpsso") if len(eids) > 1: - raise IdpUnspecified("Too many IdPs to choose from: %s" % eids) + raise IdpUnspecified(f"Too many IdPs to choose from: {eids}") try: srvs = self.metadata.single_sign_on_service(list(eids.keys())[0], binding) diff --git a/src/saml2/discovery.py b/src/saml2/discovery.py index d4be1ef3..2f777d01 100644 --- a/src/saml2/discovery.py +++ b/src/saml2/discovery.py @@ -52,7 +52,7 @@ class DiscoveryServer(Entity): is_passive = dsr.get("isPassive") if is_passive not in ["true", "false"]: - raise ValueError("Invalid value '{v}' for attribute '{attr}'".format(v=is_passive, attr="isPassive")) + raise ValueError(f"Invalid value '{is_passive}' for attribute 'isPassive'") if "isPassive" in dsr and dsr["isPassive"] == "true": dsr["isPassive"] = True diff --git a/src/saml2/ecp.py b/src/saml2/ecp.py index 4615fc49..5e1ad0b7 100644 --- a/src/saml2/ecp.py +++ b/src/saml2/ecp.py @@ -137,7 +137,7 @@ def handle_ecp_authn_response(cls, soap_message, outstanding=None): response = authn_response(cls.config, cls.service_urls(), outstanding, allow_unsolicited=True) - response.loads("%s" % rdict["body"], False, soap_message) + response.loads(f"{rdict['body']}", False, soap_message) response.verify() cls.users.add_information_about_person(response.session_info()) @@ -163,7 +163,7 @@ def ecp_response(target_url, response): soap_envelope = soapenv.Envelope(header=header, body=body) - return "%s" % soap_envelope + return f"{soap_envelope}" class ECPServer(Server): diff --git a/src/saml2/ecp_client.py b/src/saml2/ecp_client.py index ce1fca2c..fe051990 100644 --- a/src/saml2/ecp_client.py +++ b/src/saml2/ecp_client.py @@ -167,8 +167,8 @@ class Client(Entity): _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, + f"response_consumer_url '{rc_url}' does not match", + f"assertion_consumer_service_url '{_acs_url}", ) # Send an error message to the SP _ = self.send(rc_url, "POST", data=soap.soap_fault(error)) @@ -247,7 +247,7 @@ class Client(Entity): # url I started off with. pass else: - raise SAMLError("Error POSTing package to SP: %s" % response.text) + raise SAMLError(f"Error POSTing package to SP: {response.text}") logger.debug("[P3] SP response: %s", response.text) @@ -262,14 +262,14 @@ class Client(Entity): headers = set_list2dict(headers) headers["PAOS"] = PAOS_HEADER_INFO if "Accept" in headers: - headers["Accept"] += ";%s" % MIME_PAOS + headers["Accept"] += f";{MIME_PAOS}" elif "accept" in headers: headers["Accept"] = headers["accept"] - headers["Accept"] += ";%s" % MIME_PAOS + headers["Accept"] += f";{MIME_PAOS}" del headers["accept"] headers = dict2set_list(headers) else: - headers = [("Accept", "text/html; %s" % MIME_PAOS), ("PAOS", PAOS_HEADER_INFO)] + headers = [("Accept", f"text/html; {MIME_PAOS}"), ("PAOS", PAOS_HEADER_INFO)] return headers @@ -298,7 +298,7 @@ class Client(Entity): print(response.text) if response.status_code != 200: - raise SAMLError("Request to SP failed: %s" % response.text) + raise SAMLError(f"Request to SP failed: {response.text}") # The response might be a AuthnRequest instance in a SOAP envelope # body. If so it's the start of the ECP conversation diff --git a/src/saml2/entity.py b/src/saml2/entity.py index f826177e..9d0d2dcf 100644 --- a/src/saml2/entity.py +++ b/src/saml2/entity.py @@ -122,7 +122,7 @@ def create_artifact(entity_id, message_handle, endpoint_index=0): if not isinstance(message_handle, bytes): message_handle = message_handle.encode("utf-8") - ter = b"".join((ARTIFACT_TYPECODE, ("%.2x" % endpoint_index).encode("ascii"), sourceid.digest(), message_handle)) + ter = b"".join((ARTIFACT_TYPECODE, (f"{endpoint_index:02x}").encode("ascii"), sourceid.digest(), message_handle)) return base64.b64encode(ter).decode("ascii") @@ -160,7 +160,7 @@ class Entity(HTTPBase): tmp = make_temp(r.text, ".pem", False, self.config.delete_tmpfiles) setattr(self.config, item, tmp.name) else: - raise Exception("Could not fetch certificate from %s" % _val) + raise Exception(f"Could not fetch certificate from {_val}") HTTPBase.__init__( self, @@ -214,7 +214,7 @@ class Entity(HTTPBase): try: self.metadata.reload(metadata_conf) except Exception as ex: - logger.error("Loading metadata failed; reason: %s" % str(ex)) + logger.error(f"Loading metadata failed; reason: {str(ex)}") return False self.sourceid = self.metadata.construct_source_id() @@ -305,7 +305,7 @@ class Entity(HTTPBase): else: info = self.use_http_artifact(msg_str, destination, relay_state) else: - raise SAMLError("Unknown binding type: %s" % binding) + raise SAMLError(f"Unknown binding type: {binding}") return info @@ -327,8 +327,8 @@ class Entity(HTTPBase): else: descr_type = "spsso" - _url = getattr(request, "%s_url" % service, None) - _index = getattr(request, "%s_index" % service, None) + _url = getattr(request, f"{service}_url", None) + _index = getattr(request, f"{service}_index", None) for binding in bindings: try: @@ -438,7 +438,7 @@ class Entity(HTTPBase): BINDING_HTTP_ARTIFACT, None, ]: - raise UnknownBinding("Don't know how to handle '%s'" % binding) + raise UnknownBinding(f"Don't know how to handle '{binding}'") else: try: if binding == BINDING_HTTP_REDIRECT: @@ -446,14 +446,14 @@ class Entity(HTTPBase): elif binding == BINDING_HTTP_POST: xmlstr = base64.b64decode(txt) elif binding == BINDING_SOAP: - func = getattr(soap, "parse_soap_enveloped_saml_%s" % msgtype) + func = getattr(soap, f"parse_soap_enveloped_saml_{msgtype}") xmlstr = func(txt) elif binding == BINDING_HTTP_ARTIFACT: xmlstr = base64.b64decode(txt) else: xmlstr = txt except Exception: - raise UnravelError("Unravelling binding '%s' failed" % binding) + raise UnravelError(f"Unravelling binding '{binding}' failed") return xmlstr @@ -837,7 +837,7 @@ class Entity(HTTPBase): ) node_xpath = "".join( [ - '/*[local-name()="%s"]' % v + f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] ] ) @@ -1459,7 +1459,7 @@ class Entity(HTTPBase): logger.error("Unsolicited response") raise except Exception as err: - if "not well-formed" in "%s" % err: + if "not well-formed" in f"{err}": logger.error("Not well-formed XML") raise else: @@ -1579,11 +1579,7 @@ class Entity(HTTPBase): typecode = _art[:2] if typecode != ARTIFACT_TYPECODE: - raise ValueError( - "Invalid artifact typecode '{invalid}' should be {valid}".format( - invalid=typecode, valid=ARTIFACT_TYPECODE - ) - ) + raise ValueError(f"Invalid artifact typecode '{typecode}' should be {ARTIFACT_TYPECODE}") try: endpoint_index = str(int(_art[2:4])) @@ -1592,7 +1588,7 @@ class Entity(HTTPBase): entity = self.sourceid[_art[4:24]] destination = None - for desc in entity["%s_descriptor" % descriptor]: + for desc in entity[f"{descriptor}_descriptor"]: for srv in desc["artifact_resolution_service"]: if srv["index"] == endpoint_index: destination = srv["location"] diff --git a/src/saml2/httpbase.py b/src/saml2/httpbase.py index f183cf8e..11685d4f 100644 --- a/src/saml2/httpbase.py +++ b/src/saml2/httpbase.py @@ -134,7 +134,7 @@ class HTTPBase: # print(cookie) if cookie.expires and cookie.expires <= now: continue - if not re.search("%s$" % cookie.domain, _domain): + if not re.search(f"{cookie.domain}$", _domain): continue if not re.match(cookie.path, part.path): continue @@ -233,7 +233,7 @@ class HTTPBase: r = requests.request(method, url, **_kwargs) logger.debug("Response status: %s", r.status_code) except requests.ConnectionError as exc: - raise ConnectionError("%s" % exc) + raise ConnectionError(f"{exc}") try: self.set_cookie(SimpleCookie(r.headers["set-cookie"]), r) diff --git a/src/saml2/mdstore.py b/src/saml2/mdstore.py index 95ab0945..639c7a2d 100644 --- a/src/saml2/mdstore.py +++ b/src/saml2/mdstore.py @@ -426,14 +426,14 @@ class MetaData: Returns any entities with the specified descriptor """ res = {} - desc = "%s_descriptor" % descriptor + desc = f"{descriptor}_descriptor" for eid, ent in self.items(): if desc in ent: res[eid] = ent return res def __str__(self): - return "%s" % self.items() + return f"{self.items()}" def construct_source_id(self): raise NotImplementedError @@ -490,13 +490,13 @@ class MetaData: res = [] for descr in ["spsso", "idpsso", "role", "authn_authority", "attribute_authority", "pdp"]: try: - srvs = ent["%s_descriptor" % descr] + srvs = ent[f"{descr}_descriptor"] except KeyError: continue res.extend(extract_certs(srvs)) else: - srvs = ent["%s_descriptor" % descriptor] + srvs = ent[f"{descriptor}_descriptor"] res = extract_certs(srvs) return res @@ -552,7 +552,7 @@ class InMemoryMetaData(MetaData): # have I seen this entity_id before ? If so if log: ignore it if entity_descr.entity_id in self.entity: - print("Duplicated Entity descriptor (entity id: '%s')" % entity_descr.entity_id, file=sys.stderr) + print(f"Duplicated Entity descriptor (entity id: '{entity_descr.entity_id}')", file=sys.stderr) return _ent = to_dict(entity_descr, metadata_modules()) @@ -561,7 +561,7 @@ class InMemoryMetaData(MetaData): for descr in ["spsso", "idpsso", "role", "authn_authority", "attribute_authority", "pdp", "affiliation"]: _res = [] try: - _items = _ent["%s_descriptor" % descr] + _items = _ent[f"{descr}_descriptor"] except KeyError: continue @@ -576,7 +576,7 @@ class InMemoryMetaData(MetaData): _res.append(item) break if not _res: - del _ent["%s_descriptor" % descr] + del _ent[f"{descr}_descriptor"] else: flag += 1 @@ -1082,7 +1082,7 @@ class MetadataStore(MetaData): url = args[1] _md = MetaDataMDX(url, http_client_timeout=self.http_client_timeout) else: - raise SAMLError("Unknown metadata type '%s'" % typ) + raise SAMLError(f"Unknown metadata type '{typ}'") _md.load() self.metadata[key] = _md @@ -1115,13 +1115,13 @@ class MetadataStore(MetaData): try: key = item["class"] except (KeyError, AttributeError): - raise SAMLError("Misconfiguration in metadata %s" % item) + raise SAMLError(f"Misconfiguration in metadata {item}") mod, clas = key.rsplit(".", 1) try: mod = importlib.import_module(mod) MDloader = getattr(mod, clas) except (ImportError, AttributeError): - raise SAMLError("Unknown metadata loader %s" % key) + raise SAMLError(f"Unknown metadata loader {key}") # Separately handle MDExtern if MDloader == MetaDataExtern: @@ -1243,25 +1243,25 @@ class MetadataStore(MetaData): raise AttributeError("Missing type specification") if binding is None: binding = BINDING_SOAP - return self.service(entity_id, "%s_descriptor" % typ, "assertion_id_request_service", binding) + return self.service(entity_id, f"{typ}_descriptor", "assertion_id_request_service", binding) def single_logout_service(self, entity_id, binding=None, typ=None): # IDP + SP if typ is None: raise AttributeError("Missing type specification") - return self.service(entity_id, "%s_descriptor" % typ, "single_logout_service", binding) + return self.service(entity_id, f"{typ}_descriptor", "single_logout_service", binding) def manage_name_id_service(self, entity_id, binding=None, typ=None): # IDP + SP if binding is None: binding = BINDING_HTTP_REDIRECT - return self.service(entity_id, "%s_descriptor" % typ, "manage_name_id_service", binding) + return self.service(entity_id, f"{typ}_descriptor", "manage_name_id_service", binding) def artifact_resolution_service(self, entity_id, binding=None, typ=None): # IDP + SP if binding is None: binding = BINDING_HTTP_REDIRECT - return self.service(entity_id, "%s_descriptor" % typ, "artifact_resolution_service", binding) + return self.service(entity_id, f"{typ}_descriptor", "artifact_resolution_service", binding) def assertion_consumer_service(self, entity_id, binding=None, _="spsso"): # SP @@ -1699,7 +1699,7 @@ class MetadataStore(MetaData): except AttributeError: res.entity_descriptor.append(_md.entity_descr) - return "%s" % res + return f"{res}" elif format == "md": # self.items() returns dictitems(), convert that back into a dict return json.dumps(dict(self.items()), indent=2) diff --git a/src/saml2/metadata.py b/src/saml2/metadata.py index d87be05f..d7f19453 100644 --- a/src/saml2/metadata.py +++ b/src/saml2/metadata.py @@ -351,7 +351,7 @@ DEFAULT_BINDING = { def do_extensions(mname, item): try: - _mod = __import__("saml2.extension.%s" % mname, globals(), locals(), mname) + _mod = __import__(f"saml2.extension.{mname}", globals(), locals(), mname) except ImportError: return None else: @@ -567,7 +567,7 @@ def do_idpsso_descriptor(conf, cert=None, enc_cert=None): if val is None: setattr(idpsso, key, DEFAULT[key]) else: - setattr(idpsso, key, ("%s" % val).lower()) + setattr(idpsso, key, (f"{val}").lower()) except KeyError: setattr(idpsso, key, DEFAULTS[key]) @@ -771,7 +771,7 @@ def entities_descriptor(eds, valid_for, name, ident, sign, secc, sign_alg=None, entities.signature = pre_signature_part(ident, secc.my_cert, 1, sign_alg=sign_alg, digest_alg=digest_alg) entities.id = ident - xmldoc = secc.sign_statement("%s" % entities, class_name(entities)) + xmldoc = secc.sign_statement(f"{entities}", class_name(entities)) entities = md.entities_descriptor_from_string(xmldoc) else: xmldoc = None @@ -793,6 +793,6 @@ def sign_entity_descriptor(edesc, ident, secc, sign_alg=None, digest_alg=None): edesc.signature = pre_signature_part(ident, secc.my_cert, 1, sign_alg=sign_alg, digest_alg=digest_alg) edesc.id = ident - xmldoc = secc.sign_statement("%s" % edesc, class_name(edesc)) + xmldoc = secc.sign_statement(f"{edesc}", class_name(edesc)) edesc = md.entity_descriptor_from_string(xmldoc) return edesc, xmldoc diff --git a/src/saml2/mongo_store.py b/src/saml2/mongo_store.py index 23729237..f2fc0a6e 100644 --- a/src/saml2/mongo_store.py +++ b/src/saml2/mongo_store.py @@ -422,7 +422,7 @@ class MetadataMDB(InMemoryMetaData): elif len(res) == 1: return unprotect(res[0]["entity_description"]) else: - raise CorruptDatabase("More then one document with key %s" % item) + raise CorruptDatabase(f"More then one document with key {item}") def bindings(self, entity_id, typ, service): pass diff --git a/src/saml2/pack.py b/src/saml2/pack.py index 30b9cdf9..4a081ed1 100644 --- a/src/saml2/pack.py +++ b/src/saml2/pack.py @@ -177,7 +177,7 @@ def http_redirect_message( elif typ == "SAMLart": args = {typ: message} else: - raise Exception("Unknown message type: %s" % typ) + raise Exception(f"Unknown message type: {typ}") if relay_state: args["RelayState"] = relay_state @@ -297,7 +297,7 @@ def parse_soap_enveloped_saml(text, body_class, header_class=None): try: body = saml2.create_class_from_element_tree(body_class, sub) except Exception: - raise Exception("Wrong body type (%s) in SOAP envelope" % sub.tag) + raise Exception(f"Wrong body type ({sub.tag}) in SOAP envelope") elif part.tag == "{%s}Header" % NAMESPACE: if not header_class: raise Exception("Header where I didn't expect one") @@ -325,7 +325,7 @@ def packager(identifier): try: return PACKING[identifier] except KeyError: - raise Exception("Unknown binding type: %s" % identifier) + raise Exception(f"Unknown binding type: {identifier}") def factory(binding, message, location, relay_state="", typ="SAMLRequest", **kwargs): diff --git a/src/saml2/response.py b/src/saml2/response.py index 7d51ce6d..3b564c62 100644 --- a/src/saml2/response.py +++ b/src/saml2/response.py @@ -535,14 +535,14 @@ class AuthnResponse(StatusResponse): # del self.outstanding_queries[self.in_response_to] try: if not self.check_subject_confirmation_in_response_to(self.in_response_to): - raise UnsolicitedResponse("Unsolicited response: %s" % self.in_response_to) + raise UnsolicitedResponse(f"Unsolicited response: {self.in_response_to}") except AttributeError: pass elif self.allow_unsolicited: # Should check that I haven't seen this before pass else: - raise UnsolicitedResponse("Unsolicited response: %s" % self.in_response_to) + raise UnsolicitedResponse(f"Unsolicited response: {self.in_response_to}") return self @@ -609,7 +609,7 @@ class AuthnResponse(StatusResponse): if not for_me(conditions, self.entity_id): if not lax: - raise Exception("AudienceRestrictions conditions not satisfied! (Local entity_id=%s)" % self.entity_id) + raise Exception(f"AudienceRestrictions conditions not satisfied! (Local entity_id={self.entity_id})") if conditions.condition: # extra conditions for cond in conditions.condition: @@ -1000,7 +1000,7 @@ class AuthnResponse(StatusResponse): if self.context == "AuthnReq" or self.context == "AttrQuery": self.ava = self.get_identity() - logger.debug("--- AVA: %s" % self.ava) + logger.debug(f"--- AVA: {self.ava}") return True diff --git a/src/saml2/s2repoze/plugins/formswithhidden.py b/src/saml2/s2repoze/plugins/formswithhidden.py index 1483af92..8c120f07 100644 --- a/src/saml2/s2repoze/plugins/formswithhidden.py +++ b/src/saml2/s2repoze/plugins/formswithhidden.py @@ -92,7 +92,7 @@ class FormHiddenPlugin(FormPlugin): query = parse_dict_querystring(environ) hidden = [] for key, val in query.items(): - hidden.append(HIDDEN_PRE_LINE % ("_%s_" % key, val)) + hidden.append(HIDDEN_PRE_LINE % (f"_{key}_", val)) logger.info("hidden: %s", hidden) form = self.formbody or _DEFAULT_FORM diff --git a/src/saml2/s2repoze/plugins/sp.py b/src/saml2/s2repoze/plugins/sp.py index 9d107795..d71541ea 100644 --- a/src/saml2/s2repoze/plugins/sp.py +++ b/src/saml2/s2repoze/plugins/sp.py @@ -65,7 +65,7 @@ def construct_came_from(environ): def exception_trace(tag, exc, log): message = traceback.format_exception(*sys.exc_info()) - log.error("[{}] ExcList: {}".format(tag, "".join(message))) + log.error(f"[{tag}] ExcList: {''.join(message)}") log.error(f"[{tag}] Exception: {exc}") @@ -247,7 +247,7 @@ class SAML2Plugin: 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_ + ret += f"?sid={sid_}" loc = _cli.create_discovery_service_request(self.discosrv, eid, **{"return": ret}) return -1, SeeOther(loc) @@ -343,7 +343,7 @@ class SAML2Plugin: sign=False, extensions=extensions, ) - msg_str = "%s" % req + msg_str = f"{req}" _sid = req_id if cert is not None: @@ -359,8 +359,8 @@ class SAML2Plugin: logger.debug("ht_args: %s", ht_args) except Exception as exc: - logger.exception("Failed to construct the AuthnRequest: %s" % str(exc)) - raise Exception("Failed to construct the AuthnRequest: %s" % exc) + logger.exception(f"Failed to construct the AuthnRequest: {str(exc)}") + raise Exception(f"Failed to construct the AuthnRequest: {exc}") try: path_info = environ.get("PATH_INFO") diff --git a/src/saml2/s_utils.py b/src/saml2/s_utils.py index e8fadfa1..1284e3e9 100644 --- a/src/saml2/s_utils.py +++ b/src/saml2/s_utils.py @@ -318,7 +318,7 @@ def do_ava(val, typ=""): elif val is None: attrval = None else: - raise OtherError("strange value type on: %s" % val) + raise OtherError(f"strange value type on: {val}") if typ: for ava in attrval: @@ -417,9 +417,9 @@ def exception_trace(exc): message = traceback.format_exception(*sys.exc_info()) try: - _exc = "Exception: %s" % exc + _exc = f"Exception: {exc}" except UnicodeEncodeError: - _exc = "Exception: %s" % exc.message.encode("utf-8", "replace") + _exc = f"Exception: {exc.message.encode('utf-8', 'replace')}" return {"message": _exc, "content": "".join(message)} diff --git a/src/saml2/sigver.py b/src/saml2/sigver.py index cae27914..01a12a71 100644 --- a/src/saml2/sigver.py +++ b/src/saml2/sigver.py @@ -70,7 +70,7 @@ from saml2.xmlenc import EncryptionMethod logger = logging.getLogger(__name__) -SIG = "{{{ns}#}}{attribute}".format(ns=ds.NAMESPACE, attribute="Signature") +SIG = f"{{{ds.NAMESPACE}#}}Signature" # RSA_1_5 is considered deprecated RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5" @@ -568,7 +568,7 @@ def verify_redirect_signature(saml_msg, crypto, cert=None, sigkey=None): try: signer = crypto.get_signer(saml_msg["SigAlg"], sigkey) except KeyError: - raise Unsupported("Signature algorithm: {alg}".format(alg=saml_msg["SigAlg"])) + raise Unsupported(f"Signature algorithm: {saml_msg['SigAlg']}") else: if saml_msg["SigAlg"] in SIGNER_ALGS: if "SAMLRequest" in saml_msg: @@ -846,9 +846,7 @@ class CryptoBackendXmlSec1(CryptoBackend): p_err = p_err.decode() if pof.returncode != 0: - errmsg = "returncode={code}\nerror={err}\noutput={out}".format( - code=pof.returncode, err=p_err, out=p_out - ) + errmsg = f"returncode={pof.returncode}\nerror={p_err}\noutput={p_out}" logger.error(errmsg) raise XmlsecError(errmsg) diff --git a/src/saml2/soap.py b/src/saml2/soap.py index 866bff14..14593afb 100644 --- a/src/saml2/soap.py +++ b/src/saml2/soap.py @@ -188,7 +188,7 @@ def class_instances_from_soap_enveloped_saml_thingies(text, modules): try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: - raise XmlParseError("%s" % exc) + raise XmlParseError(f"{exc}") envelope_tag = "{%s}Envelope" % soapenv.NAMESPACE if envelope.tag != envelope_tag: @@ -220,7 +220,7 @@ def open_soap_envelope(text): try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: - raise XmlParseError("%s" % exc) + raise XmlParseError(f"{exc}") envelope_tag = "{%s}Envelope" % soapenv.NAMESPACE if envelope.tag != envelope_tag: @@ -261,7 +261,7 @@ def make_soap_enveloped_saml_thingy(thingy, headers=None): soap_envelope.body = soapenv.Body() soap_envelope.body.add_extension_element(thingy) - return "%s" % soap_envelope + return f"{soap_envelope}" def soap_fault(message=None, actor=None, code=None, detail=None): @@ -291,4 +291,4 @@ def soap_fault(message=None, actor=None, code=None, detail=None): detail=_detail, ) - return "%s" % fault + return f"{fault}" diff --git a/src/saml2/tools/parse_xsd2.py b/src/saml2/tools/parse_xsd2.py index 432f25a7..49aa84fa 100644 --- a/src/saml2/tools/parse_xsd2.py +++ b/src/saml2/tools/parse_xsd2.py @@ -54,7 +54,7 @@ PROTECTED_KEYWORDS = ["import", "def", "if", "else", "return", "for", "while", " def def_init(imports, attributes): indent = INDENT + INDENT indent3 = INDENT + INDENT + INDENT - line = ["%sdef __init__(self," % INDENT] + line = [f"{INDENT}def __init__(self,"] for elem in attributes: if elem[0] in PROTECTED_KEYWORDS: @@ -75,10 +75,10 @@ def def_init(imports, attributes): _name = elem line.append(f"{indent3}{_name}=None,") - line.append("%stext=None," % indent3) - line.append("%sextension_elements=None," % indent3) - line.append("%sextension_attributes=None," % indent3) - line.append("%s):" % indent) + line.append(f"{indent3}text=None,") + line.append(f"{indent3}extension_elements=None,") + line.append(f"{indent3}extension_attributes=None,") + line.append(f"{indent}):") return line @@ -86,14 +86,14 @@ def base_init(imports): line = [] indent4 = INDENT + INDENT + INDENT + INDENT if not imports: - line.append("%sSamlBase.__init__(self, " % (INDENT + INDENT)) + line.append(f"{INDENT + INDENT}SamlBase.__init__(self, ") for attr in BASE_ELEMENT: if attr in PROTECTED_KEYWORDS: _name = attr + "_" else: _name = attr line.append(f"{indent4}{_name}={_name},") - line.append("%s)" % indent4) + line.append(f"{indent4})") else: # TODO have to keep apart which properties come from which superior for sup, elems in imports.items(): @@ -106,7 +106,7 @@ def base_init(imports): else: _name = attr line.append(f"{indent4}{_name}={_name},") - line.append("%s)" % indent4) + line.append(f"{indent4})") return line @@ -341,7 +341,7 @@ class PyObj: if not superior: line.append(f"class {c_name}(SamlBase):") else: - line.append("class {}({}):".format(c_name, ",".join(sups))) + line.append(f"class {c_name}({','.join(sups)}):") if hasattr(self, "scoped"): pass @@ -383,7 +383,7 @@ class PyObj: line.append("") if not self.abstract or not self.class_name.endswith("_"): - line.append("def %s_from_string(xml_string):" % pyify(self.class_name)) + line.append(f"def {pyify(self.class_name)}_from_string(xml_string):") line.append(f"{INDENT}return saml2.create_class_from_xml_string({self.class_name}, xml_string)") line.append("") @@ -800,12 +800,12 @@ def _spec(elem): name = elem.name except AttributeError: name = "anonymous" - txt = "%s" % name + txt = f"{name}" try: - txt += " ref: %s" % elem.ref + txt += f" ref: {elem.ref}" except AttributeError: try: - txt += " type: %s" % elem.type + txt += f" type: {elem.type}" except AttributeError: pass @@ -825,7 +825,7 @@ def _spec(elem): def _do_from_string(name): print - print("def %s_from_string(xml_string):" % pyify(name)) + print(f"def {pyify(name)}_from_string(xml_string):") print(f"{INDENT}return saml2.create_class_from_xml_string({name}, xml_string)") @@ -917,7 +917,7 @@ class Attribute(Simple): name = self.ref pyname = pyify(name) else: # referering to what - raise Exception("Strange reference: %s" % self.ref) + raise Exception(f"Strange reference: {self.ref}") objekt = PyAttribute(name, pyname, external=external, root=top) @@ -1085,7 +1085,7 @@ class Complex: if DEBUG: print(self.__dict__) - print("#-- %d parts" % len(self.parts)) + print(f"#-- {len(self.parts)} parts") self._extend(top, sup, argv, parent) @@ -1307,7 +1307,7 @@ class Sequence(Complex): argv_copy[key] = val if DEBUG: - print("#Sequence: %s" % argv) + print(f"#Sequence: {argv}") return Complex.collect(self, top, sup, argv_copy, parent) @@ -1371,7 +1371,7 @@ class Choice(Complex): argv_copy["minOccurs"] = 0 if DEBUG: - print("#Choice: %s" % argv) + print(f"#Choice: {argv}") return Complex.collect(self, top, sup, argv_copy, parent=parent) @@ -1664,16 +1664,15 @@ def output(elem, target_namespace, eldict, ignore=None): def intro(): print( - """#!/usr/bin/env python + f"""#!/usr/bin/env python # -# Generated %s by parse_xsd.py version %s. +# Generated {time.ctime()} by parse_xsd.py version {__version__}. # import saml2 from saml2 import SamlBase """ - % (time.ctime(), __version__) ) @@ -1887,12 +1886,12 @@ class Schema(Complex): intro() for modul in self.add: - print("from %s import *" % modul) + print(f"from {modul} import *") for _namespace, (mod, namn) in self.impo.items(): if namn: print(f"import {mod} as {namn}") print() - print("NAMESPACE = '%s'" % self.target_namespace) + print(f"NAMESPACE = '{self.target_namespace}'") print for defs in self.defs: @@ -1923,7 +1922,7 @@ class Schema(Complex): print for attrgrp in self.attrgrp: - print("AG_%s = [" % attrgrp.name) + print(f"AG_{attrgrp.name} = [") for prop in attrgrp.properties[0]: if isinstance(prop.type, PyObj): print(f"{INDENT}('{prop.name}', {prop.type.name}_, {prop.required}),") @@ -2110,7 +2109,7 @@ def read_schema(doc, add, defs, impo, modul, ignore, sdir): elif namespace in ignore: continue else: - raise Exception("Undefined namespace: %s" % namespace) + raise Exception(f"Undefined namespace: {namespace}") _schema = Schema(tree._root, impo, add, modul, defs) _included_parts = [] @@ -2175,7 +2174,7 @@ def main(): elif opt in ("-I", "--ignore"): ignore.append(arg) else: - raise Exception("unhandled option %s" % opt) + raise Exception(f"unhandled option {opt}") if not args: print("No XSD-file specified") diff --git a/src/saml2/tools/sync_attrmaps.py b/src/saml2/tools/sync_attrmaps.py index f20e2d6c..1a3743de 100644 --- a/src/saml2/tools/sync_attrmaps.py +++ b/src/saml2/tools/sync_attrmaps.py @@ -59,14 +59,14 @@ class AMap: try: assert self.mod.MAP["to"][val] == key except KeyError: # missing value - print("# Added {}={}".format(self.mod.MAP["to"][val], key)) + print(f"# Added {self.mod.MAP['to'][val]}={key}") self.mod.MAP["to"][val] = key except AssertionError: - raise Exception("Mismatch key:{} '{}' != '{}'".format(key, val, self.mod.MAP["to"][val])) + raise Exception(f"Mismatch key:{key} '{val}' != '{self.mod.MAP['to'][val]}'") for val in self.mod.MAP["to"].values(): if val not in self.mod.MAP["fro"]: - print("# Missing URN '%s'" % val) + print(f"# Missing URN '{val}'") def do_fro(self): txt = ["%s'fro': {" % self.indent] @@ -107,7 +107,7 @@ class AMap: text.extend(["", ""]) text.append("MAP = {") - text.append("{}'identifier': '{}',".format(self.indent, self.mod.MAP["identifier"])) + text.append(f"{self.indent}'identifier': '{self.mod.MAP['identifier']}',") text.extend(self.do_fro()) text.extend(self.do_to()) @@ -122,7 +122,7 @@ if __name__ == "__main__": directory, fname = os.path.split(_name) amap = AMap(directory, fname, 4 * " ") f = open(_name, "w") - f.write("%s" % amap) + f.write(f"{amap}") f.close() elif os.path.isdir(_name): for fname in os.listdir(_name): @@ -133,5 +133,5 @@ if __name__ == "__main__": print(10 * "=" + fname + 10 * "=") amap = AMap(_name, fname, 4 * " ") f = open(fname, "w") - f.write("%s" % amap) + f.write(f"{amap}") f.close() diff --git a/src/saml2/validate.py b/src/saml2/validate.py index 33083886..ae66504b 100644 --- a/src/saml2/validate.py +++ b/src/saml2/validate.py @@ -359,7 +359,7 @@ def valid_instance(instance): for (name, typ, required) in instclass.c_attributes.values(): value = getattr(instance, name, "") if required and not value: - txt = "Required value on property '%s' missing" % name + txt = f"Required value on property '{name}' missing" raise MustValueError(f"Class '{class_name}' instance: {txt}") if value: @@ -404,13 +404,9 @@ def valid_instance(instance): if _card: if _cmin is not None and _cmin > vlen: - raise NotValid( - "Class '%s' instance cardinality error: %s" % (class_name, f"less then min ({vlen}<{_cmin})") - ) + raise NotValid(f"Class '{class_name}' instance cardinality error: less then min ({vlen}<{_cmin})") if _cmax is not None and vlen > _cmax: - raise NotValid( - "Class '%s' instance cardinality error: %s" % (class_name, f"more then max ({vlen}>{_cmax})") - ) + raise NotValid(f"Class '{class_name}' instance cardinality error: more then max ({vlen}>{_cmax})") if _list: for val in value: @@ -420,9 +416,7 @@ def valid_instance(instance): _valid_instance(instance, value) else: if _cmin: - raise NotValid( - "Class '{}' instance cardinality error: {}".format(class_name, "too few values on %s" % name) - ) + raise NotValid(f"Class '{class_name}' instance cardinality error: too few values on {name}") return True diff --git a/src/saml2test/__init__.py b/src/saml2test/__init__.py index 81eace7f..e4f1d6bf 100644 --- a/src/saml2test/__init__.py +++ b/src/saml2test/__init__.py @@ -88,9 +88,9 @@ def exception_trace(tag, exc, log=None): message = traceback.format_exception(*sys.exc_info()) try: - _exc = "Exception: %s" % exc + _exc = f"Exception: {exc}" except UnicodeEncodeError: - _exc = "Exception: %s" % exc.message.encode("utf-8", "replace") + _exc = f"Exception: {exc.message.encode('utf-8', 'replace')}" return {"status": CRITICAL, "message": _exc, "content": "".join(message)} diff --git a/src/saml2test/check.py b/src/saml2test/check.py index 47ea170c..158397fb 100644 --- a/src/saml2test/check.py +++ b/src/saml2test/check.py @@ -164,7 +164,7 @@ class VerifyError(Error): try: assert item["error"] in self._kwargs["error"] except AssertionError: - self._message = "Wrong type of error, got %s" % item["error"] + self._message = f"Wrong type of error, got {item['error']}" self._status = self.status return {} diff --git a/src/saml2test/opfunc.py b/src/saml2test/opfunc.py index 78096c2e..51b01b0c 100644 --- a/src/saml2test/opfunc.py +++ b/src/saml2test/opfunc.py @@ -212,9 +212,7 @@ def do_click(client, form, **kwargs): else: _nr += 1 except ControlNotFoundError: - raise Exception( - "No submit control with the name='%s' and " "value='%s' could be found" % (_name, _val) - ) + raise Exception(f"No submit control with the name='{_name}' and value='{_val}' could be found") else: request = form.click() diff --git a/src/saml2test/tool.py b/src/saml2test/tool.py index b0bbf66c..fa600955 100644 --- a/src/saml2test/tool.py +++ b/src/saml2test/tool.py @@ -87,7 +87,7 @@ class Conversation: chk = self.check_factory(test)() chk(self, self.test_output) if bryt: - e = FatalError("%s" % err) + e = FatalError(f"{err}") e.trace = "".join(traceback.format_exception(*sys.exc_info())) raise e @@ -125,7 +125,7 @@ class Conversation: else: rdseq.append(url) if len(rdseq) > 8: - raise FatalError("Too long sequence of redirects: %s" % rdseq) + raise FatalError(f"Too long sequence of redirects: {rdseq}") logger.info("HTTP %d Location: %s", _response.status_code, url) # If back to me @@ -153,7 +153,7 @@ class Conversation: logger.info("GET %s", url) _response = self.client.send(url, "GET") except Exception as err: - raise FatalError("%s" % err) + raise FatalError(f"{err}") content = _response.text logger.info("<-- CONTENT: %s", content) |