Project

General

Profile

0003-use-force_str-only-when-necessary-64309.patch

Paul Marillonnet, 20 April 2022 10:14 AM

Download (10.2 KB)

View differences:

Subject: [PATCH 3/6] use force_str only when necessary (#64309)

 mellon/adapters.py    |  5 ++---
 mellon/utils.py       | 10 +++++-----
 mellon/views.py       | 16 ++++++++--------
 tests/test_sso_slo.py | 12 ++++++------
 tests/test_views.py   |  4 ++--
 5 files changed, 23 insertions(+), 24 deletions(-)
mellon/adapters.py
32 32
from django.contrib.auth.models import Group
33 33
from django.core.exceptions import FieldDoesNotExist, PermissionDenied
34 34
from django.core.files.storage import default_storage
35
from django.utils.encoding import force_text
36 35
from django.utils.translation import gettext as _
37 36

  
38 37
from . import app_settings, models, models_utils, utils
......
276 275
        realm = utils.get_setting(idp, 'REALM')
277 276
        username_template = utils.get_setting(idp, 'USERNAME_TEMPLATE')
278 277
        try:
279
            username = force_text(username_template).format(realm=realm, attributes=saml_attributes, idp=idp)[
278
            username = username_template.format(realm=realm, attributes=saml_attributes, idp=idp)[
280 279
                : self.user_class._meta.get_field('username').max_length
281 280
            ]
282 281
        except ValueError:
......
476 475
        attribute_set = False
477 476
        for field, tpl in attribute_mapping.items():
478 477
            try:
479
                value = force_text(tpl).format(realm=realm, attributes=saml_attributes, idp=idp)
478
                value = tpl.format(realm=realm, attributes=saml_attributes, idp=idp)
480 479
            except ValueError:
481 480
                logger.warning('mellon: invalid attribute mapping template %r', tpl)
482 481
            except (AttributeError, KeyError, IndexError, ValueError) as e:
mellon/utils.py
27 27
from django.contrib import auth
28 28
from django.template.loader import render_to_string
29 29
from django.urls import reverse
30
from django.utils.encoding import force_text
30
from django.utils.encoding import force_str
31 31
from django.utils.timezone import get_default_timezone, is_aware, make_aware, make_naive, now
32 32

  
33 33
from . import app_settings
......
213 213

  
214 214
def make_session_dump(lasso_name_id, indexes):
215 215
    session_infos = []
216
    name_id = force_text(lasso_name_id.content)
217
    name_id_format = force_text(lasso_name_id.format)
218
    name_qualifier = lasso_name_id.nameQualifier and force_text(lasso_name_id.nameQualifier)
219
    sp_name_qualifier = lasso_name_id.spNameQualifier and force_text(lasso_name_id.spNameQualifier)
216
    name_id = force_str(lasso_name_id.content)
217
    name_id_format = force_str(lasso_name_id.format)
218
    name_qualifier = lasso_name_id.nameQualifier and force_str(lasso_name_id.nameQualifier)
219
    sp_name_qualifier = lasso_name_id.spNameQualifier and force_str(lasso_name_id.spNameQualifier)
220 220
    for index in indexes:
221 221
        issuer = index.saml_identifier.issuer.entity_id
222 222
        session_infos.append(
mellon/views.py
32 32
from django.http import Http404, HttpResponse, HttpResponseForbidden, HttpResponseRedirect
33 33
from django.shortcuts import render, resolve_url
34 34
from django.urls import reverse
35
from django.utils.encoding import force_str, force_text
35
from django.utils.encoding import force_str
36 36
from django.utils.http import urlencode
37 37
from django.utils.translation import gettext as _
38 38
from django.views.decorators.csrf import csrf_exempt
......
264 264

  
265 265
        if login.nameIdentifier:
266 266
            name_id = login.nameIdentifier
267
            name_id_format = force_text(name_id.format or lasso.SAML2_NAME_IDENTIFIER_FORMAT_UNSPECIFIED)
267
            name_id_format = force_str(name_id.format or lasso.SAML2_NAME_IDENTIFIER_FORMAT_UNSPECIFIED)
268 268
            attributes.update(
269 269
                {'name_id_content': lasso_decode(name_id.content), 'name_id_format': name_id_format}
270 270
            )
271 271
            if name_id.nameQualifier:
272
                attributes['name_id_name_qualifier'] = force_text(name_id.nameQualifier)
272
                attributes['name_id_name_qualifier'] = force_str(name_id.nameQualifier)
273 273
            if name_id.spNameQualifier:
274
                attributes['name_id_sp_name_qualifier'] = force_text(name_id.spNameQualifier)
274
                attributes['name_id_sp_name_qualifier'] = force_str(name_id.spNameQualifier)
275 275
        authn_statement = login.assertion.authnStatement[0]
276 276
        if authn_statement.authnInstant:
277 277
            attributes['authn_instant'] = utils.iso8601_to_datetime(authn_statement.authnInstant)
......
663 663
        except lasso.Error as e:
664 664
            return HttpResponseBadRequest('error processing logout request: %r' % e)
665 665

  
666
        entity_id = force_text(logout.remoteProviderId)
667
        session_indexes = {force_text(sessionIndex) for sessionIndex in logout.request.sessionIndexes}
666
        entity_id = force_str(logout.remoteProviderId)
667
        session_indexes = {force_str(sessionIndex) for sessionIndex in logout.request.sessionIndexes}
668 668

  
669 669
        saml_identifier = (
670 670
            models.UserSAMLIdentifier.objects.filter(
671
                name_id=force_text(logout.nameIdentifier.content),
671
                name_id=force_str(logout.nameIdentifier.content),
672 672
                issuer=models_utils.get_issuer(entity_id),
673 673
            )
674 674
            .select_related('user', 'issuer')
......
708 708
        except lasso.Error as e:
709 709
            return HttpResponseBadRequest('error processing logout request: %r' % e)
710 710
        if logout.msgBody:
711
            return HttpResponse(force_text(logout.msgBody), content_type='text/xml')
711
            return HttpResponse(force_str(logout.msgBody), content_type='text/xml')
712 712
        else:
713 713
            return HttpResponseRedirect(logout.msgUrl)
714 714

  
tests/test_sso_slo.py
210 210
        if body:
211 211
            logout.processResponseMsg(force_str(body))
212 212
        else:
213
            logout.processResponseMsg(force_str(url.split('?', 1)[-1]))
213
            logout.processResponseMsg(url.split('?', 1)[-1])
214 214

  
215 215
    def process_logout_request_redirect(self, url):
216 216
        logout = lasso.Logout(self.server)
......
346 346
    app.cookiejar.clear()
347 347

  
348 348
    url, body, relay_state = idp.init_slo(method=lasso.HTTP_METHOD_SOAP)
349
    response = app.post(url, params=body, headers={'Content-Type': force_str('text/xml')})
349
    response = app.post(url, params=body, headers={'Content-Type': 'text/xml'})
350 350
    assert Session.objects.count() == 1
351 351
    idp.check_slo_return(body=response.content)
352 352

  
......
424 424
    # idp logout
425 425
    app.cookiejar.clear()
426 426
    url, body, relay_state = idp.init_slo(method=lasso.HTTP_METHOD_SOAP, full=True)
427
    response = app.post(url, params=body, headers={'Content-Type': force_str('text/xml')})
427
    response = app.post(url, params=body, headers={'Content-Type': 'text/xml'})
428 428
    assert Session.objects.count() == 0
429 429
    idp.check_slo_return(body=response.content)
430 430

  
......
677 677
    assert 'MELLON_PASSIVE_TRIED' not in app.cookies
678 678
    # webtest-lint is against unicode
679 679
    app.set_cookie('IDP_SESSION', '1')
680
    response = app.get('/', headers={'Accept': force_str('text/html')}, status=302)
680
    response = app.get('/', headers={'Accept': 'text/html'}, status=302)
681 681
    assert urlparse.urlparse(response.location).path == '/login/'
682 682
    assert urlparse.parse_qs(urlparse.urlparse(response.location).query, keep_blank_values=True) == {
683 683
        'next': ['http://testserver/'],
......
695 695

  
696 696
    # check passive authentication is tried again
697 697
    app.set_cookie('IDP_SESSION', '1')
698
    response = app.get('/', headers={'Accept': force_str('text/html')}, status=302)
698
    response = app.get('/', headers={'Accept': 'text/html'}, status=302)
699 699
    assert urlparse.urlparse(response.location).path == '/login/'
700 700
    assert urlparse.parse_qs(urlparse.urlparse(response.location).query, keep_blank_values=True) == {
701 701
        'next': ['http://testserver/'],
......
709 709
    assert 'MELLON_PASSIVE_TRIED' not in app.cookies
710 710
    # webtest-lint is against unicode
711 711
    app.set_cookie('IDP_SESSION', '1')
712
    app.get('/?no-passive-auth', headers={'Accept': force_str('text/html')}, status=200)
712
    app.get('/?no-passive-auth', headers={'Accept': 'text/html'}, status=200)
713 713

  
714 714

  
715 715
def test_sso_user_change(db, app, idp, caplog, sp_settings):
tests/test_views.py
22 22
import lasso
23 23
import pytest
24 24
from django.urls import reverse
25
from django.utils.encoding import force_text
25
from django.utils.encoding import force_str
26 26
from django.utils.http import urlencode
27 27
from httmock import HTTMock
28 28
from utils import error_500, html_response
......
271 271
def artifact():
272 272
    entity_id = b'http://idp5/metadata'
273 273
    token = b'x' * 20
274
    return force_text(base64.b64encode(b'\x00\x04\x00\x00' + hashlib.sha1(entity_id).digest() + token))
274
    return force_str(base64.b64encode(b'\x00\x04\x00\x00' + hashlib.sha1(entity_id).digest() + token))
275 275

  
276 276

  
277 277
def test_error_500_on_artifact_resolve(private_settings, client, caplog, artifact):
278
-