Projet

Général

Profil

0002-misc-use-new-signing.dumps-loads-implementation-6113.patch

Benjamin Dauvergne, 26 janvier 2022 22:01

Télécharger (16,2 ko)

Voir les différences:

Subject: [PATCH 2/2] misc: use new signing.dumps/loads implementation (#61130)

 src/authentic2/backends/ldap_backend.py |  3 ++-
 src/authentic2/manager/role_views.py    |  6 +++---
 src/authentic2/manager/views.py         |  6 +++---
 src/authentic2/manager/widgets.py       |  4 ++--
 src/authentic2/models.py                |  2 +-
 src/authentic2/utils/misc.py            |  8 ++++----
 src/authentic2/views.py                 | 18 +++++++++---------
 src/authentic2_auth_fc/views.py         |  2 +-
 src/authentic2_auth_oidc/backends.py    |  2 +-
 src/authentic2_auth_oidc/views.py       |  8 ++++----
 src/authentic2_idp_oidc/utils.py        |  3 ++-
 tests/test_ldap.py                      |  4 ++--
 12 files changed, 34 insertions(+), 32 deletions(-)
src/authentic2/backends/ldap_backend.py
42 42
from ldap.filter import filter_format
43 43
from ldap.ldapobject import ReconnectLDAPObject as NativeLDAPObject
44 44

  
45
from authentic2 import app_settings, crypto
45
from authentic2 import app_settings
46 46
from authentic2.a2_rbac.models import OrganizationalUnit, Role
47 47
from authentic2.a2_rbac.utils import get_default_ou
48 48
from authentic2.backends import is_user_authenticable
......
51 51
from authentic2.middleware import StoreRequestMiddleware
52 52
from authentic2.models import UserExternalId
53 53
from authentic2.user_login_failure import user_login_failure, user_login_success
54
from authentic2.utils import crypto
54 55
from authentic2.utils.misc import PasswordChangeError, to_list
55 56

  
56 57
# code originaly copied from by now merely inspired by
src/authentic2/manager/role_views.py
20 20
from django.contrib import messages
21 21
from django.contrib.auth import get_user_model
22 22
from django.contrib.contenttypes.models import ContentType
23
from django.core import signing
24 23
from django.core.exceptions import PermissionDenied, ValidationError
25 24
from django.core.paginator import EmptyPage, Paginator
26 25
from django.db import transaction
......
39 38
from authentic2.a2_rbac.utils import get_default_ou
40 39
from authentic2.apps.journal.views import JournalViewWithContext
41 40
from authentic2.forms.profile import modelform_factory
41
from authentic2.utils import crypto
42 42
from authentic2.utils.misc import redirect
43 43

  
44 44
from . import forms, resources, tables, views
......
820 820

  
821 821
        field_id = self.kwargs.get('field_id', self.request.GET.get('field_id', None))
822 822
        try:
823
            signing.loads(field_id)
824
        except (signing.SignatureExpired, signing.BadSignature):
823
            crypto.loads(field_id)
824
        except (crypto.SignatureExpired, crypto.BadSignature):
825 825
            raise Http404('Invalid or expired signature.')
826 826

  
827 827
        search_term = request.GET.get('term', '')
src/authentic2/manager/views.py
21 21
import pickle
22 22

  
23 23
from django.contrib.messages.views import SuccessMessageMixin
24
from django.core import signing
25 24
from django.core.exceptions import PermissionDenied, ValidationError
26 25
from django.db import transaction
27 26
from django.forms import MediaDefiningClass
......
44 43
from authentic2.data_transfer import ImportContext, export_site, import_site
45 44
from authentic2.decorators import json as json_view
46 45
from authentic2.forms.profile import modelform_factory
46
from authentic2.utils import crypto
47 47
from authentic2.utils.misc import batch_queryset, redirect
48 48

  
49 49
from . import app_settings, forms, utils, widgets
......
745 745
            raise Http404('Invalid user')
746 746
        field_data = self.kwargs.get('field_id', self.request.GET.get('field_id', None))
747 747
        try:
748
            field_data = signing.loads(field_data)
749
        except (signing.SignatureExpired, signing.BadSignature):
748
            field_data = crypto.loads(field_data)
749
        except (crypto.SignatureExpired, crypto.BadSignature):
750 750
            raise Http404('Invalid or expired signature.')
751 751
        widget_class = field_data.get('class')
752 752
        if not widget_class or not hasattr(widgets, widget_class):
src/authentic2/manager/widgets.py
20 20
import pickle
21 21

  
22 22
from django.contrib.auth import get_user_model
23
from django.core import signing
24 23
from django.utils.encoding import force_text
25 24
from django_select2.forms import ModelSelect2MultipleWidget, ModelSelect2Widget
26 25

  
27 26
from authentic2.a2_rbac.models import Role
27
from authentic2.utils import crypto
28 28
from authentic2_idp_oidc.models import OIDCAuthorization
29 29

  
30 30
from . import utils
......
57 57
            'class': self.__class__.__name__,
58 58
            'where_clause': force_text(base64.b64encode(pickle.dumps(self.queryset.query.where))),
59 59
        }
60
        attrs['data-field_id'] = signing.dumps(field_data)
60
        attrs['data-field_id'] = crypto.dumps(field_data)
61 61
        return attrs
62 62

  
63 63
    @classmethod
src/authentic2/models.py
36 36
from model_utils.managers import QueryManager
37 37

  
38 38
from authentic2.a2_rbac.models import Role
39
from authentic2.crypto import base64url_decode, base64url_encode
39
from authentic2.utils.crypto import base64url_decode, base64url_encode
40 40

  
41 41
# install our natural_key implementation
42 42
from . import managers
src/authentic2/utils/misc.py
32 32
from django.contrib.auth import authenticate as dj_authenticate
33 33
from django.contrib.auth import get_user_model
34 34
from django.contrib.auth import login as auth_login
35
from django.core import signing
36 35
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
37 36
from django.core.mail import EmailMessage, send_mail
38 37
from django.forms.utils import ErrorList, to_current_timezone
......
48 47
from django.utils.translation import ungettext
49 48

  
50 49
from authentic2.saml.saml2utils import filter_attribute_private_key, filter_element_private_key
50
from authentic2.utils import crypto
51 51

  
52
from .. import app_settings, constants, crypto, plugins
52
from .. import app_settings, constants, plugins
53 53
from .service import set_service_ref
54 54

  
55 55

  
......
774 774
def build_deletion_url(request, **kwargs):
775 775
    data = kwargs.copy()
776 776
    data['user_pk'] = request.user.pk
777
    deletion_token = signing.dumps(data)
777
    deletion_token = crypto.dumps(data)
778 778
    delete_url = request.build_absolute_uri(
779 779
        reverse('validate_deletion', kwargs={'deletion_token': deletion_token})
780 780
    )
......
1176 1176
        legacy_body_templates = None
1177 1177

  
1178 1178
    # build verify email URL containing a signed token
1179
    token = signing.dumps(
1179
    token = crypto.dumps(
1180 1180
        {
1181 1181
            'email': email,
1182 1182
            'user_pk': user.pk,
src/authentic2/views.py
26 26
from django.contrib.auth import logout as auth_logout
27 27
from django.contrib.auth.decorators import login_required
28 28
from django.contrib.auth.views import PasswordChangeView as DjPasswordChangeView
29
from django.core import signing
30 29
from django.core.exceptions import ValidationError
31 30
from django.db.models.fields import FieldDoesNotExist
32 31
from django.db.models.query import Q
......
60 59
from .forms import passwords as passwords_forms
61 60
from .forms import profile as profile_forms
62 61
from .forms import registration as registration_forms
62
from .utils import crypto
63 63
from .utils import misc as utils_misc
64 64
from .utils import switch_user as utils_switch_user
65 65
from .utils.evaluate import make_condition_context
......
229 229
    def get(self, request, *args, **kwargs):
230 230
        if 'token' in request.GET:
231 231
            try:
232
                token = signing.loads(
232
                token = crypto.loads(
233 233
                    request.GET['token'], max_age=app_settings.A2_EMAIL_CHANGE_TOKEN_LIFETIME
234 234
                )
235 235
                user_pk = token['user_pk']
......
260 260
                    old_email=old_email,
261 261
                    new_email=user.email,
262 262
                )
263
            except signing.SignatureExpired:
263
            except crypto.SignatureExpired:
264 264
                messages.error(request, _('your request for changing your email is too old, try again'))
265
            except signing.BadSignature:
265
            except crypto.BadSignature:
266 266
                messages.error(request, _('your request for changing your email is invalid, try again'))
267 267
            except ValueError:
268 268
                messages.error(
......
903 903
        # load pre-filled values
904 904
        if request.GET.get('token'):
905 905
            try:
906
                self.token = signing.loads(
906
                self.token = crypto.loads(
907 907
                    request.GET.get('token'), max_age=settings.ACCOUNT_ACTIVATION_DAYS * 3600 * 24
908 908
                )
909
            except (TypeError, ValueError, signing.BadSignature) as e:
909
            except (TypeError, ValueError, crypto.BadSignature) as e:
910 910
                logger.warning('registration_view: invalid token: %s', e)
911 911
                return HttpResponseBadRequest('invalid token', content_type='text/plain')
912 912
            if 'ou' in self.token:
......
1348 1348

  
1349 1349
    def dispatch(self, request, *args, **kwargs):
1350 1350
        try:
1351
            deletion_token = signing.loads(
1351
            deletion_token = crypto.loads(
1352 1352
                kwargs['deletion_token'], max_age=app_settings.A2_DELETION_REQUEST_LIFETIME
1353 1353
            )
1354 1354
            user_pk = deletion_token['user_pk']
......
1357 1357
            if not self.user.is_active:
1358 1358
                raise ValidationError(_('This account is inactive, it cannot be deleted.'))
1359 1359
            logger.info('user %s confirmed the deletion of their own account', self.user)
1360
        except signing.SignatureExpired:
1360
        except crypto.SignatureExpired:
1361 1361
            error = _('The account deletion request is too old, try again')
1362
        except signing.BadSignature:
1362
        except crypto.BadSignature:
1363 1363
            error = _('The account deletion request is invalid, try again')
1364 1364
        except ValueError:
1365 1365
            error = _('The account deletion request was not on this site, try again')
src/authentic2_auth_fc/views.py
37 37
from authentic2 import constants, hooks
38 38
from authentic2 import models as a2_models
39 39
from authentic2.a2_rbac.utils import get_default_ou
40
from authentic2.crypto import check_hmac_url, hash_chain, hmac_url
41 40
from authentic2.forms.passwords import SetPasswordForm
42 41
from authentic2.utils import misc as utils_misc
43 42
from authentic2.utils import views as utils_views
43
from authentic2.utils.crypto import check_hmac_url, hash_chain, hmac_url
44 44
from authentic2.utils.models import safe_get_or_create
45 45
from authentic2.utils.service import get_service_from_ref, get_service_from_request, service_ref
46 46

  
src/authentic2_auth_oidc/backends.py
26 26

  
27 27
from authentic2 import app_settings, hooks
28 28
from authentic2.a2_rbac.models import OrganizationalUnit
29
from authentic2.crypto import base64url_encode
29
from authentic2.utils.crypto import base64url_encode
30 30
from authentic2.utils.template import Template
31 31

  
32 32
from . import models, utils
src/authentic2_auth_oidc/views.py
23 23
from django.conf import settings
24 24
from django.contrib import messages
25 25
from django.contrib.auth import REDIRECT_FIELD_NAME
26
from django.core import signing
27 26
from django.http import HttpResponseBadRequest
28 27
from django.urls import reverse
29 28
from django.utils.translation import get_language
......
31 30
from django.views.generic.base import View
32 31

  
33 32
from authentic2.decorators import setting_enabled
33
from authentic2.utils import crypto
34 34
from authentic2.utils.misc import authenticate, good_next_url, login, redirect
35 35

  
36 36
from . import app_settings, models
......
65 65
        'scope': ' '.join(scopes),
66 66
        'response_type': 'code',
67 67
        'redirect_uri': request.build_absolute_uri(reverse('oidc-login-callback')),
68
        'state': signing.dumps(state_content),
68
        'state': crypto.dumps(state_content),
69 69
        'nonce': nonce,
70 70
    }
71 71
    if provider.claims_parameter_supported:
......
140 140
        if not raw_state:
141 141
            return redirect(request, settings.LOGIN_REDIRECT_URL)
142 142
        try:
143
            state_content = signing.loads(raw_state)
144
        except signing.BadSignature:
143
            state_content = crypto.loads(raw_state)
144
        except crypto.BadSignature:
145 145
            return redirect(request, settings.LOGIN_REDIRECT_URL)
146 146

  
147 147
        state = state_content['state_id']
src/authentic2_idp_oidc/utils.py
27 27
from jwcrypto.jwk import JWK, InvalidJWKValue, JWKSet
28 28
from jwcrypto.jwt import JWT
29 29

  
30
from authentic2 import crypto, hooks
30
from authentic2 import hooks
31 31
from authentic2.attributes_ng.engine import get_attributes
32 32
from authentic2.decorators import GlobalCache
33
from authentic2.utils import crypto
33 34
from authentic2.utils.template import Template
34 35

  
35 36
from . import app_settings
tests/test_ldap.py
32 32
from ldap.dn import escape_dn_chars
33 33
from ldaptools.slapd import Slapd, has_slapd
34 34

  
35
from authentic2 import crypto, models
35
from authentic2 import models
36 36
from authentic2.a2_rbac.models import OrganizationalUnit, Role
37 37
from authentic2.a2_rbac.utils import get_default_ou
38 38
from authentic2.backends import ldap_backend
39 39
from authentic2.models import Service
40
from authentic2.utils import switch_user
40
from authentic2.utils import crypto, switch_user
41 41
from authentic2.utils.misc import PasswordChangeError, authenticate
42 42

  
43 43
from . import utils
44
-