Projet

Général

Profil

0001-python3-adapt-exception-raising-and-handling-31137.patch

Paul Marillonnet, 06 mars 2019 15:54

Télécharger (19,8 ko)

Voir les différences:

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    | 22 +++++++++----------
 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, 41 insertions(+), 41 deletions(-)
debian-wheezy/debian_config.py
256 256
    if 'LDAP_AUTH_SETTINGS' in os.environ:
257 257
        try:
258 258
            LDAP_AUTH_SETTINGS = json.loads(os.environ['LDAP_AUTH_SETTINGS'])
259
        except Exception, e:
259
        except Exception as e:
260 260
            raise ImproperlyConfigured('LDAP_AUTH_SETTINGS is not a JSON document', e)
261 261

  
262 262
    if 'CACHE_BACKEND' in os.environ:
debian/debian_config.py
257 257
    if 'LDAP_AUTH_SETTINGS' in os.environ:
258 258
        try:
259 259
            LDAP_AUTH_SETTINGS = json.loads(os.environ['LDAP_AUTH_SETTINGS'])
260
        except Exception, e:
260
        except Exception as e:
261 261
            raise ImproperlyConfigured('LDAP_AUTH_SETTINGS is not a JSON document', e)
262 262

  
263 263
    if 'CACHE_BACKEND' in os.environ:
src/authentic2/auth2_auth/auth2_ssl/util.py
46 46
        elif name == 'ModPythonRequest':
47 47
            env = request._req.subprocess_env
48 48
        else:
49
            raise EnvironmentError, 'The SSL authentication currently only \
50
                works with mod_python or wsgi requests'
49
            raise EnvironmentError('The SSL authentication currently only \
50
                works with mod_python or wsgi requests')
51 51
        self.read_env(env);
52 52
        pass
53 53

  
......
77 77
        if attr in self.__dict__:
78 78
            return self.__dict__[attr]
79 79
        else:
80
            raise AttributeError, 'SSLInfo does not contain key %s' % attr
80
            raise AttributeError('SSLInfo does not contain key %s' % attr)
81 81

  
82 82
    def __setattr__(self, attr, value):
83
        raise AttributeError, 'SSL vars are read only!'
83
        raise AttributeError('SSL vars are read only!')
84 84

  
85 85
    def __repr__(self):
86 86
        return '<SSLInfo %s>' % self.__dict__
src/authentic2/backends/ldap_backend.py
313 313
            connection.simple_bind_s(self.dn, raw_password)
314 314
        except ldap.INVALID_CREDENTIALS:
315 315
            return False
316
        except ldap.LDAPError, e:
316
        except ldap.LDAPError as e:
317 317
            log.error('LDAPUser.check_password() failed: %s', e)
318 318
            return False
319 319
        self._current_password = raw_password
......
538 538
                            n = len(user_filter.split('%s')) - 1
539 539
                            try:
540 540
                                query = filter_format(user_filter, (username,) * n)
541
                            except TypeError, e:
541
                            except TypeError as e:
542 542
                                log.error('user_filter syntax error %r: %s', block['user_filter'],
543 543
                                          e)
544 544
                                return
......
562 562
                        if block['replicas']:
563 563
                            break
564 564
                        continue
565
                    except ldap.LDAPError, e:
565
                    except ldap.LDAPError as e:
566 566
                        log.error('user lookup failed: with query %r got error %s: %s', username,
567 567
                                  query, e)
568 568
                        continue
src/authentic2/decorators.py
261 261
def errorcollector(error_dict):
262 262
    try:
263 263
        yield
264
    except ValidationError, e:
264
    except ValidationError as e:
265 265
        e.update_error_dict(error_dict)
266 266

  
267 267

  
src/authentic2/idp/saml/common.py
23 23
            store = engine.SessionStore(key)
24 24
            logging.debug('Killing session %s', key)
25 25
            store.delete()
26
    except Exception, e:
26
    except Exception as e:
27 27
        logging.error(e)
src/authentic2/idp/saml/saml2_endpoints.py
114 114
    def f(request, *args, **kwargs):
115 115
        try:
116 116
            return func(request, *args, **kwargs)
117
        except exception_classes, e:
117
        except exception_classes as e:
118 118
            return error_redirect(request, e.message or repr(e))
119 119
    return f
120 120

  
......
449 449
            request.session['saml:authnRequest'] = login.request.getOriginalXmlnode()
450 450
            break
451 451
        except (lasso.ProfileInvalidMsgError,
452
            lasso.ProfileMissingIssuerError,), e:
452
            lasso.ProfileMissingIssuerError,) as e:
453 453
            logger.warning('invalid message for WebSSO profile with '
454 454
                          'HTTP-Redirect binding: %r exception: %s' \
455 455
                          % (message, e),
......
464 464
            logger.warning("the request cannot be answered because no "
465 465
                "valid protocol binding could be found")
466 466
            return HttpResponseBadRequest(message, content_type='text/plain')
467
        except lasso.ProviderMissingPublicKeyError, e:
467
        except lasso.ProviderMissingPublicKeyError as e:
468 468
            log_info_authn_request_details(login)
469 469
            logger.warning('no public key found: %s', e)
470 470
            login.response.status.statusMessage = 'The public key is unknown'
471 471
            return return_login_response(request, login)
472
        except lasso.DsError, e:
472
        except lasso.DsError as e:
473 473
            log_info_authn_request_details(login)
474 474
            logger.warning('digital signature treatment error: %s', e)
475 475
            login.response.status.statusMessage = 'Signature validation failed'
......
938 938
            logger.error('provider loading failure')
939 939
        try:
940 940
            login.processRequestMsg(soap_message)
941
        except lasso.DsError, e:
941
        except lasso.DsError as e:
942 942
            logger.error('signature error for %s: %s'
943 943
                    % (e, login.remoteProviderId))
944 944
        else:
......
1056 1056
        # SP sent us a logout request but we do not know its Response endpoint, just continue to the
1057 1057
        # homepage
1058 1058
        return redirect('auth_homepage')
1059
    except lasso.Error, e:
1059
    except lasso.Error as e:
1060 1060
        logger.warning('logout.buildResponseMsg() failed: %s', e)
1061 1061
        return redirect('auth_homepage')
1062 1062
    if all_sessions.exists():
......
1308 1308
            '''
1309 1309
            logger.error('one provider does \
1310 1310
                not support SOAP %s' % [s.provider_id for s in lib_sessions])
1311
        except Exception, e:
1311
        except Exception as e:
1312 1312
            logger.exception('slo, unknown error %s' % str(e))
1313 1313
            logout.buildResponseMsg()
1314 1314
            provider = LibertyProvider.objects.get(entity_id=logout.remoteProviderId)
......
1391 1391
            load_provider(request, logout.remoteProviderId,
1392 1392
                    server=logout.server)
1393 1393
            logout.processRequestMsg(message)
1394
    except lasso.DsError, e:
1394
    except lasso.DsError as e:
1395 1395
        logger.exception('signature error %s' % e)
1396 1396
        logout.buildResponseMsg()
1397 1397
        provider = LibertyProvider.objects.get(entity_id=logout.remoteProviderId)
1398 1398
        return return_saml2_response(request, logout,
1399 1399
            title=_('You are being redirected to "%s"') % provider.name)
1400 1400
    except (lasso.ProfileInvalidMsgError,
1401
        lasso.ProfileMissingIssuerError), e:
1401
        lasso.ProfileMissingIssuerError) as e:
1402 1402
        return error_page(request, _('Invalid logout request'), logger=logger, warning=True)
1403 1403
    session_indexes = logout.request.sessionIndexes
1404 1404
    if len(session_indexes) == 0:
......
1427 1427
    set_session_dump_from_liberty_sessions(logout, [last_session])
1428 1428
    try:
1429 1429
        logout.validateRequest()
1430
    except lasso.Error, e:
1430
    except lasso.Error as e:
1431 1431
        logger.warning('logout request validation failed: %s', e)
1432 1432
        return return_logout_error(request, logout,
1433 1433
                AUTHENTIC_STATUS_CODE_INTERNAL_SERVER_ERROR)
......
1532 1532
        logger.info('slo by SOAP')
1533 1533
        try:
1534 1534
            soap_response = send_soap_request(request, logout)
1535
        except Exception, e:
1535
        except Exception as e:
1536 1536
            logger.exception('slo SOAP failure due to %s' % str(e))
1537 1537
            return redirect_next(request, next) or ko_icon(request)
1538 1538
        return process_logout_response(request, logout, soap_response, next)
src/authentic2/nonce/utils.py
31 31
def unlink_if_exists(path):
32 32
    try:
33 33
        os.unlink(path)
34
    except OSError, e:
34
    except OSError as e:
35 35
        if e.errno != errno.ENOENT:
36 36
            raise
37 37

  
......
47 47
    # test if the file exists
48 48
    try:
49 49
        stat = os.stat(file_path)
50
    except OSError, e:
50
    except OSError as e:
51 51
        # test if it doesnt exit or if another error happened
52 52
        if e.errno != errno.ENOENT:
53 53
            raise
......
75 75
        raise
76 76
    try:
77 77
        os.link(temp_file.name, file_path)
78
    except OSError, e:
78
    except OSError as e:
79 79
        if e.errno == errno.EEXIST:
80 80
            unlink_if_exists(temp_file.name)
81 81
        return False
......
100 100
        now_time = timegm(now.utctimetuple())
101 101
        try:
102 102
            stat = os.stat(nonce_path)
103
        except OSError, e:
103
        except OSError as e:
104 104
            if e.errno == errno.ENOENT:
105 105
                continue
106 106
            raise
107 107
        if stat.st_mtime < now_time:
108 108
            try:
109 109
                os.unlink(nonce_path)
110
            except OSError, e:
110
            except OSError as e:
111 111
                if e.errno == errno.ENOENT:
112 112
                    continue
113 113
                raise
src/authentic2/plugins.py
33 33
    for entrypoint in pkg_resources.iter_entry_points(group_name):
34 34
        try:
35 35
            plugin_callable = entrypoint.load()
36
        except Exception, e:
36
        except Exception as e:
37 37
            logger.exception('unable to load entrypoint %s', entrypoint)
38 38
            raise PluginError('unable to load entrypoint %s' % entrypoint, e)
39 39
        plugins.append(plugin_callable(*args, **kwargs))
src/authentic2/saml/admin.py
90 90
    for provider in qs:
91 91
        try:
92 92
            provider.update_metadata()
93
        except ValidationError, e:
93
        except ValidationError as e:
94 94
            params = {
95 95
                    'name': provider,
96 96
                    'error_msg': u', '.join(e.messages)
src/authentic2/saml/common.py
313 313
    # Try the WKL
314 314
    try:
315 315
        metadata = get_url(provider_id)
316
    except Exception, e:
316
    except Exception as e:
317 317
        logging.error('SAML metadata autoload: failure to retrieve metadata '
318 318
                      'for entity id %s: %s', provider_id, e)
319 319
        return None
......
327 327
    p = LibertyProvider(metadata=metadata)
328 328
    try:
329 329
        p.full_clean(exclude=['entity_id', 'protocol_conformance'])
330
    except ValidationError, e:
330
    except ValidationError as e:
331 331
        logging.error('SAML metadata autoload: retrieved metadata for entity '
332 332
                      'id %s are invalid, %s', provider_id, e.args)
333 333
        return None
......
453 453
        logger.debug('SOAP call to %r with data %r', url, msg[:10000])
454 454
        response = requests.post(url, data=msg, headers={'Content-Type': 'text/xml'})
455 455
        response.raise_for_status()
456
    except requests.RequestException, e:
456
    except requests.RequestException as e:
457 457
        logging.error('SOAP call to %r error %s with data %r', url, e, msg[:10000])
458 458
        raise SOAPException(url, e)
459 459
    logger.debug('SOAP call response %r', response.content[:10000])
src/authentic2/saml/forms.py
36 36
                response = requests.get(url)
37 37
                response.raise_for_status()
38 38
                content = response.content
39
            except requests.RequestException, e:
39
            except requests.RequestException as e:
40 40
                raise ValidationError(_('Retrieval of %(url)s failed: %(exception)s') % {
41 41
                    'url': url,
42 42
                    'exception': e
src/authentic2/saml/management/commands/sync-metadata.py
312 312

  
313 313
        try:
314 314
            doc = etree.parse(metadata_file)
315
        except Exception, e:
315
        except Exception as e:
316 316
            raise CommandError('XML parsing error: %s' % str(e))
317 317
        if doc.getroot().tag == ENTITY_DESCRIPTOR_TN:
318 318
            load_one_entity(doc.getroot(), options)
......
353 353
                        sp_policy=sp_policy,
354 354
                        afp=afp)
355 355
                    loaded.append(entity_descriptor.get(ENTITY_ID))
356
                except Exception, e:
356
                except Exception as e:
357 357
                    if not options['ignore-errors']:
358 358
                        raise
359 359
                    if verbosity > 0:
src/authentic2/saml/models.py
358 358
            if not self.metadata_url:
359 359
                raise ValidationError(_('No metadata URL'))
360 360
            response = requests.get(self.metadata_url)
361
        except requests.RequestException, e:
361
        except requests.RequestException as e:
362 362
            raise ValidationError(_('Retrieval of metadata failed: %s') % e)
363 363
        else:
364 364
            self.metadata = response.content
src/authentic2/saml/saml2utils.py
395 395
                        format = attribute.nameFormat.decode('ascii')
396 396
                    if attribute.friendlyName:
397 397
                        nickname = attribute.friendlyName
398
                except Exception, e:
398
                except Exception as e:
399 399
                    message = 'get_attributes_from_assertion: name or format of an \
400 400
                        attribute failed to decode as ascii: %s due to %s'
401 401
                    logger.warning(message % (attribute.dump(), str(e)))
......
410 410
                        content = ''.join(content)
411 411
                        attributes[(name, format)].append(content.\
412 412
                            decode('utf8'))
413
                except Exception, e:
413
                except Exception as e:
414 414
                    message = 'get_attributes_from_assertion: value of an \
415 415
                        attribute failed to decode as ascii: %s due to %s'
416 416
                    logger.warning(message % (attribute.dump(), str(e)))
src/authentic2/utils.py
138 138
    module, attr = path[:i], path[i + 1:]
139 139
    try:
140 140
        mod = import_module(module)
141
    except ImportError, e:
141
    except ImportError as e:
142 142
        raise ImproperlyConfigured('Error importing idp backend %s: "%s"' % (module, e))
143
    except ValueError, e:
143
    except ValueError as e:
144 144
        raise ImproperlyConfigured('Error importing idp backends. Is IDP_BACKENDS a correctly '
145 145
                                   'defined list or tuple?')
146 146
    try:
src/authentic2_auth_saml/adapters.py
41 41
            try:
42 42
                value = saml_attributes[saml_attribute]
43 43
                self.set_user_attribute(user, attribute, value)
44
            except Exception, e:
44
            except Exception as e:
45 45
                log.error(u'failed to set attribute %r from saml attribute %r with value %r: %s',
46 46
                          attribute, saml_attribute, value, e,
47 47
                          extra={'attributes': repr(saml_attributes)})
48
-