Skip to content

Commit bc96c38

Browse files
committed
Replace assert with proper checks
Signed-off-by: Ivan Kanakarakis <ivan.kanak@gmail.com>
1 parent 7b1b52e commit bc96c38

File tree

15 files changed

+173
-97
lines changed

15 files changed

+173
-97
lines changed

src/saml2/assertion.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -296,9 +296,7 @@ def post_entity_categories(maps, **kwargs):
296296
else:
297297
attrs = atlist
298298
for _key in key:
299-
try:
300-
assert _key in ecs
301-
except AssertionError:
299+
if _key not in ecs:
302300
attrs = []
303301
break
304302
elif key in ecs:

src/saml2/authn_context/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,9 @@ def add(self, spec, method, level=0, authn_authority="", reference=None):
9090
if _ref is None:
9191
_ref = str(self.next)
9292

93-
assert _ref not in self.db["info"]
93+
if _ref in self.db["info"]:
94+
raise Exception("Internal error: reference is not unique")
95+
9496
self.db["info"][_ref] = _info
9597
try:
9698
self.db["key"][key].append(_ref)

src/saml2/client.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,12 @@ def prepare_for_authenticate(
7575
response_binding=response_binding,
7676
**kwargs)
7777

78-
assert negotiated_binding == binding
78+
if negotiated_binding != binding:
79+
raise ValueError(
80+
"Negotiated binding '{}' does not match binding to use '{}'".format(
81+
negotiated_binding, binding
82+
)
83+
)
7984

8085
return reqid, info
8186

src/saml2/client_base.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -646,8 +646,10 @@ def create_name_id_mapping_request(self, name_id_policy,
646646
:return:
647647
"""
648648

649-
# One of them must be present
650-
assert name_id or base_id or encrypted_id
649+
if not name_id and not base_id and not encrypted_id:
650+
raise ValueError(
651+
"At least one of name_id, base_id or encrypted_id must be present."
652+
)
651653

652654
if name_id:
653655
return self._message(NameIDMappingRequest, destination, message_id,

src/saml2/discovery.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ def parse_discovery_service_request(self, url="", query=""):
2424

2525
# verify
2626

27-
for key in ["isPassive", "return", "returnIDParam", "policy",
28-
'entityID']:
27+
for key in ["isPassive", "return", "returnIDParam", "policy", 'entityID']:
2928
try:
30-
assert len(dsr[key]) == 1
29+
if len(dsr[key]) != 1:
30+
raise Exception("Invalid DS request keys: {k}".format(k=key))
3131
dsr[key] = dsr[key][0]
3232
except KeyError:
3333
pass
@@ -37,20 +37,27 @@ def parse_discovery_service_request(self, url="", query=""):
3737
if part.query:
3838
qp = parse.parse_qs(part.query)
3939
if "returnIDParam" in dsr:
40-
assert dsr["returnIDParam"] not in qp.keys()
40+
if dsr["returnIDParam"] in qp.keys():
41+
raise Exception(
42+
"returnIDParam value should not be in the query params"
43+
)
4144
else:
42-
assert "entityID" not in qp.keys()
45+
if "entityID" in qp.keys():
46+
raise Exception("entityID should not be in the query params")
4347
else:
4448
# If metadata not used this is mandatory
4549
raise VerificationError("Missing mandatory parameter 'return'")
4650

4751
if "policy" not in dsr:
4852
dsr["policy"] = IDPDISC_POLICY
4953

50-
try:
51-
assert dsr["isPassive"] in ["true", "false"]
52-
except KeyError:
53-
pass
54+
is_passive = dsr.get("isPassive")
55+
if is_passive not in ["true", "false"]:
56+
raise ValueError(
57+
"Invalid value '{v}' for attribute '{attr}'".format(
58+
v=is_passive, attr="isPassive"
59+
)
60+
)
5461

5562
if "isPassive" in dsr and dsr["isPassive"] == "true":
5663
dsr["isPassive"] = True
@@ -93,10 +100,6 @@ def verify_sp_in_metadata(self, entity_id):
93100

94101
def verify_return(self, entity_id, return_url):
95102
for endp in self.metadata.discovery_response(entity_id):
96-
try:
97-
assert return_url.startswith(endp["location"])
98-
except AssertionError:
99-
pass
100-
else:
103+
if not return_url.startswith(endp["location"]):
101104
return True
102105
return False

src/saml2/ecp_client.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,14 @@ def phase2(self, authn_request, rc_url, idp_entity_id, headers=None,
136136
logger.debug("[P2] IdP response dict: %s", respdict)
137137

138138
idp_response = respdict["body"]
139-
assert idp_response.c_tag == "Response"
139+
140+
expected_tag = "Response"
141+
if idp_response.c_tag != expected_tag:
142+
raise ValueError(
143+
"Invalid Response tag '{invalid}' should be '{valid}'".format(
144+
invalid=idp_response.c_tag, valid=expected_tag
145+
)
146+
)
140147

141148
logger.debug("[P2] IdP AUTHN response: %s", idp_response)
142149

@@ -165,7 +172,14 @@ def parse_sp_ecp_response(respdict):
165172

166173
# AuthnRequest in the body or not
167174
authn_request = respdict["body"]
168-
assert authn_request.c_tag == "AuthnRequest"
175+
176+
expected_tag = "AuthnRequest"
177+
if authn_request.c_tag != expected_tag:
178+
raise ValueError(
179+
"Invalid AuthnRequest tag '{invalid}' should be '{valid}'".format(
180+
invalid=authn_request.c_tag, valid=expected_tag
181+
)
182+
)
169183

170184
# ecp.RelayState among headers
171185
_relay_state = None

src/saml2/entity.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -848,7 +848,7 @@ def _parse_request(self, enc_request, request_cls, service, binding):
848848
_log_debug("Loaded request")
849849

850850
if _request:
851-
_request = _request.verify()
851+
_request.verify()
852852
_log_debug("Verified request")
853853

854854
if not _request:
@@ -1192,14 +1192,14 @@ def _parse_response(self, xmlstr, response_cls, service, binding,
11921192
response.require_signature = True
11931193
# Verify that the assertion is syntactically correct and the
11941194
# signature on the assertion is correct if present.
1195-
response = response.verify(keys)
1195+
response.verify(keys)
11961196
except SignatureError as err:
11971197
if require_signature:
11981198
logger.error("Signature Error: %s", err)
11991199
raise
12001200
else:
12011201
response.require_signature = require_signature
1202-
response = response.verify(keys)
1202+
response.verify(keys)
12031203
else:
12041204
assertions_are_signed = True
12051205
finally:
@@ -1260,7 +1260,13 @@ def artifact2destination(self, artifact, descriptor):
12601260

12611261
_art = base64.b64decode(artifact)
12621262

1263-
assert _art[:2] == ARTIFACT_TYPECODE
1263+
typecode = _art[:2]
1264+
if typecode != ARTIFACT_TYPECODE:
1265+
raise ValueError(
1266+
"Invalid artifact typecode '{invalid}' should be {valid}".format(
1267+
invalid=typecode, valid=ARTIFACT_TYPECODE
1268+
)
1269+
)
12641270

12651271
try:
12661272
endpoint_index = str(int(_art[2:4]))

src/saml2/mdstore.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -405,9 +405,7 @@ def entity_categories(self, entity_id):
405405
return res
406406

407407
def __eq__(self, other):
408-
try:
409-
assert isinstance(other, MetaData)
410-
except AssertionError:
408+
if not isinstance(other, MetaData):
411409
return False
412410

413411
if len(self.entity) != len(other.entity):
@@ -417,9 +415,7 @@ def __eq__(self, other):
417415
return False
418416

419417
for key, item in self.entity.items():
420-
try:
421-
assert item == other[key]
422-
except AssertionError:
418+
if item != other[key]:
423419
return False
424420

425421
return True

src/saml2/pack.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,10 @@ def http_redirect_message(message, location, relay_state="", typ="SAMLRequest",
179179

180180
if signer:
181181
# sigalgs, should be one defined in xmldsig
182-
assert sigalg in [b for a, b in SIG_ALLOWED_ALG]
182+
if sigalg not in [long_name for short_name, long_name in SIG_ALLOWED_ALG]:
183+
raise Exception(
184+
"Signature algo not in allowed list: {algo}".format(algo=sigalg)
185+
)
183186
args["SigAlg"] = sigalg
184187

185188
string = "&".join([urlencode({k: args[k]})
@@ -269,7 +272,14 @@ def parse_soap_enveloped_saml(text, body_class, header_class=None):
269272
:return: header parts and body as saml.samlbase instances
270273
"""
271274
envelope = defusedxml.ElementTree.fromstring(text)
272-
assert envelope.tag == '{%s}Envelope' % NAMESPACE
275+
276+
envelope_tag = "{%s}Envelope" % NAMESPACE
277+
if envelope.tag != envelope_tag:
278+
raise ValueError(
279+
"Invalid envelope tag '{invalid}' should be '{valid}'".format(
280+
invalid=envelope.tag, valid=envelope_tag
281+
)
282+
)
273283

274284
# print(len(envelope))
275285
body = None

src/saml2/request.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,15 +80,21 @@ def issue_instant_ok(self):
8080
return issued_at > lower and issued_at < upper
8181

8282
def _verify(self):
83-
assert self.message.version == "2.0"
83+
valid_version = "2.0"
84+
if self.message.version != valid_version:
85+
raise VersionMismatch(
86+
"Invalid version {invalid} should be {valid}".format(
87+
invalid=self.message.version, valid=valid_version
88+
)
89+
)
90+
8491
if self.message.destination and self.receiver_addrs and \
8592
self.message.destination not in self.receiver_addrs:
86-
logger.error("%s not in %s", self.message.destination,
87-
self.receiver_addrs)
93+
logger.error("%s not in %s", self.message.destination, self.receiver_addrs)
8894
raise OtherError("Not destined for me!")
8995

90-
assert self.issue_instant_ok()
91-
return self
96+
valid = self.issue_instant_ok()
97+
return valid
9298

9399
def loads(self, xmldata, binding, origdoc=None, must=None,
94100
only_valid_cert=False):

0 commit comments

Comments
 (0)