From f6fa7f7c5623a98291e65d79d16df9dc96a23cfd Mon Sep 17 00:00:00 2001 From: Paul Marillonnet Date: Thu, 24 Jan 2019 11:20:52 +0100 Subject: [PATCH] python3: adapt exception raising and handling (#31137) --- debian-wheezy/debian_config.py | 2 +- debian/debian_config.py | 2 +- src/authentic2/auth2_auth/auth2_ssl/util.py | 8 +++---- src/authentic2/backends/ldap_backend.py | 6 ++--- src/authentic2/decorators.py | 2 +- src/authentic2/idp/saml/common.py | 2 +- src/authentic2/idp/saml/saml2_endpoints.py | 24 +++++++++---------- src/authentic2/nonce/utils.py | 10 ++++---- src/authentic2/plugins.py | 2 +- src/authentic2/saml/admin.py | 2 +- src/authentic2/saml/common.py | 6 ++--- src/authentic2/saml/forms.py | 2 +- .../saml/management/commands/sync-metadata.py | 4 ++-- src/authentic2/saml/models.py | 2 +- src/authentic2/saml/saml2utils.py | 4 ++-- src/authentic2/utils.py | 4 ++-- src/authentic2_auth_saml/adapters.py | 2 +- 17 files changed, 42 insertions(+), 42 deletions(-) diff --git a/debian-wheezy/debian_config.py b/debian-wheezy/debian_config.py index be1f5dd60..c52e41bbd 100644 --- a/debian-wheezy/debian_config.py +++ b/debian-wheezy/debian_config.py @@ -256,7 +256,7 @@ def extract_settings_from_environ(): if 'LDAP_AUTH_SETTINGS' in os.environ: try: LDAP_AUTH_SETTINGS = json.loads(os.environ['LDAP_AUTH_SETTINGS']) - except Exception, e: + except Exception as e: raise ImproperlyConfigured('LDAP_AUTH_SETTINGS is not a JSON document', e) if 'CACHE_BACKEND' in os.environ: diff --git a/debian/debian_config.py b/debian/debian_config.py index 7f9ab4caf..9a29da088 100644 --- a/debian/debian_config.py +++ b/debian/debian_config.py @@ -257,7 +257,7 @@ def extract_settings_from_environ(): if 'LDAP_AUTH_SETTINGS' in os.environ: try: LDAP_AUTH_SETTINGS = json.loads(os.environ['LDAP_AUTH_SETTINGS']) - except Exception, e: + except Exception as e: raise ImproperlyConfigured('LDAP_AUTH_SETTINGS is not a JSON document', e) if 'CACHE_BACKEND' in os.environ: diff --git a/src/authentic2/auth2_auth/auth2_ssl/util.py b/src/authentic2/auth2_auth/auth2_ssl/util.py index 0b95c38ae..87bd72128 100644 --- a/src/authentic2/auth2_auth/auth2_ssl/util.py +++ b/src/authentic2/auth2_auth/auth2_ssl/util.py @@ -46,8 +46,8 @@ class SSLInfo(object): elif name == 'ModPythonRequest': env = request._req.subprocess_env else: - raise EnvironmentError, 'The SSL authentication currently only \ - works with mod_python or wsgi requests' + raise EnvironmentError('The SSL authentication currently only \ + works with mod_python or wsgi requests') self.read_env(env); pass @@ -77,10 +77,10 @@ class SSLInfo(object): if attr in self.__dict__: return self.__dict__[attr] else: - raise AttributeError, 'SSLInfo does not contain key %s' % attr + raise AttributeError('SSLInfo does not contain key %s' % attr) def __setattr__(self, attr, value): - raise AttributeError, 'SSL vars are read only!' + raise AttributeError('SSL vars are read only!') def __repr__(self): return '' % self.__dict__ diff --git a/src/authentic2/backends/ldap_backend.py b/src/authentic2/backends/ldap_backend.py index ae6929039..9fdc976cf 100644 --- a/src/authentic2/backends/ldap_backend.py +++ b/src/authentic2/backends/ldap_backend.py @@ -313,7 +313,7 @@ class LDAPUser(get_user_model()): connection.simple_bind_s(self.dn, raw_password) except ldap.INVALID_CREDENTIALS: return False - except ldap.LDAPError, e: + except ldap.LDAPError as e: log.error('LDAPUser.check_password() failed: %s', e) return False self._current_password = raw_password @@ -538,7 +538,7 @@ class LDAPBackend(object): n = len(user_filter.split('%s')) - 1 try: query = filter_format(user_filter, (username,) * n) - except TypeError, e: + except TypeError as e: log.error('user_filter syntax error %r: %s', block['user_filter'], e) return @@ -562,7 +562,7 @@ class LDAPBackend(object): if block['replicas']: break continue - except ldap.LDAPError, e: + except ldap.LDAPError as e: log.error('user lookup failed: with query %r got error %s: %s', username, query, e) continue diff --git a/src/authentic2/decorators.py b/src/authentic2/decorators.py index 675226d41..21eaa93fe 100644 --- a/src/authentic2/decorators.py +++ b/src/authentic2/decorators.py @@ -261,7 +261,7 @@ class SessionCache(PickleCacheMixin, SimpleDictionnaryCacheMixin, def errorcollector(error_dict): try: yield - except ValidationError, e: + except ValidationError as e: e.update_error_dict(error_dict) diff --git a/src/authentic2/idp/saml/common.py b/src/authentic2/idp/saml/common.py index f983249b9..84a231355 100644 --- a/src/authentic2/idp/saml/common.py +++ b/src/authentic2/idp/saml/common.py @@ -23,5 +23,5 @@ def kill_django_sessions(session_key): store = engine.SessionStore(key) logging.debug('Killing session %s', key) store.delete() - except Exception, e: + except Exception as e: logging.error(e) diff --git a/src/authentic2/idp/saml/saml2_endpoints.py b/src/authentic2/idp/saml/saml2_endpoints.py index cda431dc2..ffe9766b8 100644 --- a/src/authentic2/idp/saml/saml2_endpoints.py +++ b/src/authentic2/idp/saml/saml2_endpoints.py @@ -114,7 +114,7 @@ def log_assert(func, exception_classes=(AssertionError,)): def f(request, *args, **kwargs): try: return func(request, *args, **kwargs) - except exception_classes, e: + except exception_classes as e: return error_redirect(request, e.message or repr(e)) return f @@ -449,7 +449,7 @@ def sso(request): request.session['saml:authnRequest'] = login.request.getOriginalXmlnode() break except (lasso.ProfileInvalidMsgError, - lasso.ProfileMissingIssuerError,), e: + lasso.ProfileMissingIssuerError,) as e: logger.warning('invalid message for WebSSO profile with ' 'HTTP-Redirect binding: %r exception: %s' \ % (message, e), @@ -464,12 +464,12 @@ def sso(request): logger.warning("the request cannot be answered because no " "valid protocol binding could be found") return HttpResponseBadRequest(message, content_type='text/plain') - except lasso.ProviderMissingPublicKeyError, e: + except lasso.ProviderMissingPublicKeyError as e: log_info_authn_request_details(login) logger.warning('no public key found: %s', e) login.response.status.statusMessage = 'The public key is unknown' return return_login_response(request, login) - except lasso.DsError, e: + except lasso.DsError as e: log_info_authn_request_details(login) logger.warning('digital signature treatment error: %s', e) login.response.status.statusMessage = 'Signature validation failed' @@ -938,7 +938,7 @@ def artifact(request): logger.error('provider loading failure') try: login.processRequestMsg(soap_message) - except lasso.DsError, e: + except lasso.DsError as e: logger.error('signature error for %s: %s' % (e, login.remoteProviderId)) else: @@ -1056,7 +1056,7 @@ def finish_slo(request): # SP sent us a logout request but we do not know its Response endpoint, just continue to the # homepage return redirect('auth_homepage') - except lasso.Error, e: + except lasso.Error as e: logger.warning('logout.buildResponseMsg() failed: %s', e) return redirect('auth_homepage') if all_sessions.exists(): @@ -1308,7 +1308,7 @@ def slo_soap(request): ''' logger.error('one provider does \ not support SOAP %s' % [s.provider_id for s in lib_sessions]) - except Exception, e: + except Exception as e: logger.exception('slo, unknown error %s' % str(e)) logout.buildResponseMsg() provider = LibertyProvider.objects.get(entity_id=logout.remoteProviderId) @@ -1387,18 +1387,18 @@ def slo(request): try: logout.processRequestMsg(message) except (lasso.ServerProviderNotFoundError, - lasso.ProfileUnknownProviderError), e: + lasso.ProfileUnknownProviderError) as e: load_provider(request, logout.remoteProviderId, server=logout.server) logout.processRequestMsg(message) - except lasso.DsError, e: + except lasso.DsError as e: logger.exception('signature error %s' % e) logout.buildResponseMsg() provider = LibertyProvider.objects.get(entity_id=logout.remoteProviderId) return return_saml2_response(request, logout, title=_('You are being redirected to "%s"') % provider.name) except (lasso.ProfileInvalidMsgError, - lasso.ProfileMissingIssuerError), e: + lasso.ProfileMissingIssuerError) as e: return error_page(request, _('Invalid logout request'), logger=logger, warning=True) session_indexes = logout.request.sessionIndexes if len(session_indexes) == 0: @@ -1427,7 +1427,7 @@ def slo(request): set_session_dump_from_liberty_sessions(logout, [last_session]) try: logout.validateRequest() - except lasso.Error, e: + except lasso.Error as e: logger.warning('logout request validation failed: %s', e) return return_logout_error(request, logout, AUTHENTIC_STATUS_CODE_INTERNAL_SERVER_ERROR) @@ -1532,7 +1532,7 @@ def idp_slo(request, provider_id=None): logger.info('slo by SOAP') try: soap_response = send_soap_request(request, logout) - except Exception, e: + except Exception as e: logger.exception('slo SOAP failure due to %s' % str(e)) return redirect_next(request, next) or ko_icon(request) return process_logout_response(request, logout, soap_response, next) diff --git a/src/authentic2/nonce/utils.py b/src/authentic2/nonce/utils.py index b7fde9987..14f2003bc 100644 --- a/src/authentic2/nonce/utils.py +++ b/src/authentic2/nonce/utils.py @@ -31,7 +31,7 @@ def compute_not_on_or_after(now, not_on_or_after): def unlink_if_exists(path): try: os.unlink(path) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -47,7 +47,7 @@ def accept_nonce_file_storage(path, now, value, context=None, # test if the file exists try: stat = os.stat(file_path) - except OSError, e: + except OSError as e: # test if it doesnt exit or if another error happened if e.errno != errno.ENOENT: raise @@ -75,7 +75,7 @@ def accept_nonce_file_storage(path, now, value, context=None, raise try: os.link(temp_file.name, file_path) - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST: unlink_if_exists(temp_file.name) return False @@ -100,14 +100,14 @@ def cleanup_nonces_file_storage(dir_path, now): now_time = timegm(now.utctimetuple()) try: stat = os.stat(nonce_path) - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: continue raise if stat.st_mtime < now_time: try: os.unlink(nonce_path) - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: continue raise diff --git a/src/authentic2/plugins.py b/src/authentic2/plugins.py index 19c5fb665..5ff026bf6 100644 --- a/src/authentic2/plugins.py +++ b/src/authentic2/plugins.py @@ -33,7 +33,7 @@ def get_plugins(group_name=DEFAULT_GROUP_NAME, use_cache=True, *args, **kwargs): for entrypoint in pkg_resources.iter_entry_points(group_name): try: plugin_callable = entrypoint.load() - except Exception, e: + except Exception as e: logger.exception('unable to load entrypoint %s', entrypoint) raise PluginError('unable to load entrypoint %s' % entrypoint, e) plugins.append(plugin_callable(*args, **kwargs)) diff --git a/src/authentic2/saml/admin.py b/src/authentic2/saml/admin.py index bb00de6cc..3698ce3ca 100644 --- a/src/authentic2/saml/admin.py +++ b/src/authentic2/saml/admin.py @@ -90,7 +90,7 @@ def update_metadata(modeladmin, request, queryset): for provider in qs: try: provider.update_metadata() - except ValidationError, e: + except ValidationError as e: params = { 'name': provider, 'error_msg': u', '.join(e.messages) diff --git a/src/authentic2/saml/common.py b/src/authentic2/saml/common.py index d1052c985..a19658ac3 100644 --- a/src/authentic2/saml/common.py +++ b/src/authentic2/saml/common.py @@ -313,7 +313,7 @@ def retrieve_metadata_and_create(request, provider_id, sp_or_idp): # Try the WKL try: metadata = get_url(provider_id) - except Exception, e: + except Exception as e: logging.error('SAML metadata autoload: failure to retrieve metadata ' 'for entity id %s: %s', provider_id, e) return None @@ -327,7 +327,7 @@ def retrieve_metadata_and_create(request, provider_id, sp_or_idp): p = LibertyProvider(metadata=metadata) try: p.full_clean(exclude=['entity_id', 'protocol_conformance']) - except ValidationError, e: + except ValidationError as e: logging.error('SAML metadata autoload: retrieved metadata for entity ' 'id %s are invalid, %s', provider_id, e.args) return None @@ -453,7 +453,7 @@ def soap_call(url, msg): logger.debug('SOAP call to %r with data %r', url, msg[:10000]) response = requests.post(url, data=msg, headers={'Content-Type': 'text/xml'}) response.raise_for_status() - except requests.RequestException, e: + except requests.RequestException as e: logging.error('SOAP call to %r error %s with data %r', url, e, msg[:10000]) raise SOAPException(url, e) logger.debug('SOAP call response %r', response.content[:10000]) diff --git a/src/authentic2/saml/forms.py b/src/authentic2/saml/forms.py index bac5777be..779bb6681 100644 --- a/src/authentic2/saml/forms.py +++ b/src/authentic2/saml/forms.py @@ -36,7 +36,7 @@ class AddLibertyProviderFromUrlForm(forms.Form): response = requests.get(url) response.raise_for_status() content = response.content - except requests.RequestException, e: + except requests.RequestException as e: raise ValidationError(_('Retrieval of %(url)s failed: %(exception)s') % { 'url': url, 'exception': e diff --git a/src/authentic2/saml/management/commands/sync-metadata.py b/src/authentic2/saml/management/commands/sync-metadata.py index 8897b2f0c..dcc5b2933 100644 --- a/src/authentic2/saml/management/commands/sync-metadata.py +++ b/src/authentic2/saml/management/commands/sync-metadata.py @@ -314,7 +314,7 @@ Any other kind of attribute filter policy is unsupported. try: doc = etree.parse(metadata_file) - except Exception, e: + except Exception as e: raise CommandError('XML parsing error: %s' % str(e)) if doc.getroot().tag == ENTITY_DESCRIPTOR_TN: load_one_entity(doc.getroot(), options) @@ -356,7 +356,7 @@ Any other kind of attribute filter policy is unsupported. sp_policy=sp_policy, afp=afp) loaded.append(entity_descriptor.get(ENTITY_ID)) - except Exception, e: + except Exception as e: if not options['ignore-errors']: raise if verbosity > 0: diff --git a/src/authentic2/saml/models.py b/src/authentic2/saml/models.py index f03a9ec23..726e2faa3 100644 --- a/src/authentic2/saml/models.py +++ b/src/authentic2/saml/models.py @@ -358,7 +358,7 @@ class LibertyProvider(Service): if not self.metadata_url: raise ValidationError(_('No metadata URL')) response = requests.get(self.metadata_url) - except requests.RequestException, e: + except requests.RequestException as e: raise ValidationError(_('Retrieval of metadata failed: %s') % e) else: self.metadata = response.content diff --git a/src/authentic2/saml/saml2utils.py b/src/authentic2/saml/saml2utils.py index e444c0197..8fe4bf695 100644 --- a/src/authentic2/saml/saml2utils.py +++ b/src/authentic2/saml/saml2utils.py @@ -397,7 +397,7 @@ def get_attributes_from_assertion(assertion, logger): format = attribute.nameFormat.decode('ascii') if attribute.friendlyName: nickname = attribute.friendlyName - except Exception, e: + except Exception as e: message = 'get_attributes_from_assertion: name or format of an \ attribute failed to decode as ascii: %s due to %s' logger.warning(message % (attribute.dump(), str(e))) @@ -412,7 +412,7 @@ def get_attributes_from_assertion(assertion, logger): content = ''.join(content) attributes[(name, format)].append(content.\ decode('utf8')) - except Exception, e: + except Exception as e: message = 'get_attributes_from_assertion: value of an \ attribute failed to decode as ascii: %s due to %s' logger.warning(message % (attribute.dump(), str(e))) diff --git a/src/authentic2/utils.py b/src/authentic2/utils.py index 5f4948448..473ceb869 100644 --- a/src/authentic2/utils.py +++ b/src/authentic2/utils.py @@ -138,9 +138,9 @@ def load_backend(path): module, attr = path[:i], path[i + 1:] try: mod = import_module(module) - except ImportError, e: + except ImportError as e: raise ImproperlyConfigured('Error importing idp backend %s: "%s"' % (module, e)) - except ValueError, e: + except ValueError as e: raise ImproperlyConfigured('Error importing idp backends. Is IDP_BACKENDS a correctly ' 'defined list or tuple?') try: diff --git a/src/authentic2_auth_saml/adapters.py b/src/authentic2_auth_saml/adapters.py index 3af307757..3f23fde4b 100644 --- a/src/authentic2_auth_saml/adapters.py +++ b/src/authentic2_auth_saml/adapters.py @@ -41,7 +41,7 @@ class AuthenticAdapter(DefaultAdapter): try: value = saml_attributes[saml_attribute] self.set_user_attribute(user, attribute, value) - except Exception, e: + except Exception as e: log.error(u'failed to set attribute %r from saml attribute %r with value %r: %s', attribute, saml_attribute, value, e, extra={'attributes': repr(saml_attributes)})