Projet

Général

Profil

0001-python3-migrate-authentic-40407.patch

Benjamin Dauvergne, 05 mars 2020 17:37

Télécharger (9,21 ko)

Voir les différences:

Subject: [PATCH] python3: migrate authentic (#40407)

 hobo/agent/authentic2/provisionning.py      | 25 +++++++++++----------
 hobo/multitenant/settings_loaders.py        |  9 ++++----
 tests_authentic/test_hobo_deploy.py         | 21 +++++++++--------
 tests_authentic/test_rest_authentication.py |  2 +-
 4 files changed, 30 insertions(+), 27 deletions(-)
hobo/agent/authentic2/provisionning.py
1 1
import json
2
from urlparse import urljoin
2
from django.utils.six.moves.urllib.parse import urljoin
3 3
import threading
4 4
import copy
5 5
import logging
......
8 8
from django.db import connection
9 9
from django.core.urlresolvers import reverse
10 10
from django.conf import settings
11
from django.utils.encoding import force_text
11 12

  
12 13
from django_rbac.utils import get_role_model, get_ou_model, get_role_parenting_model
13 14
from hobo.agent.common import notify_agents
......
25 26

  
26 27
class Provisionning(threading.local):
27 28
    __slots__ = ['threads']
28
    threads = set()
29 29

  
30 30
    def __init__(self):
31
        self.threads = set()
31 32
        self.stack = []
32 33

  
33 34
    def start(self):
......
100 101
        def is_forbidden_technical_role(role):
101 102
            return role.slug.startswith('_') and not role.slug.startswith(tuple(allowed_technical_roles_prefixes))
102 103

  
103
        issuer = unicode(self.get_entity_id())
104
        issuer = force_text(self.get_entity_id())
104 105
        if mode == 'provision':
105 106

  
106 107
            def user_to_json(ou, service, user, user_roles):
......
151 152
            for rp in RoleParenting.objects.filter(child__in=all_roles):
152 153
                parents.setdefault(rp.child.id, []).append(rp.parent.id)
153 154
            Through = Role.members.through
154
            for u_id, r_id in Through.objects.filter(role__members__in=users).values_list('user_id',
155
                                                                                      'role_id'):
155
            qs = Through.objects.filter(role__members__in=users).values_list('user_id', 'role_id')
156
            for u_id, r_id in qs:
156 157
                user_roles.setdefault(u_id, set()).add(roles[r_id])
157 158
                for p_id in parents.get(r_id, []):
158 159
                    user_roles[u_id].add(roles[p_id])
......
163 164
                    ous.setdefault(r.ou, set()).add(user)
164 165

  
165 166
            if roles_with_attributes:
166
                for ou, users in ous.iteritems():
167
                for ou, users in ous.items():
167 168
                    for service, audience in self.get_audience(ou):
168 169
                        for user in users:
169 170
                            logger.info(u'provisionning user %s to %s', user, audience)
......
178 179
                                }
179 180
                            })
180 181
            else:
181
                for ou, users in ous.iteritems():
182
                for ou, users in ous.items():
182 183
                    audience = [a for service, a in self.get_audience(ou)]
183 184
                    if not audience:
184 185
                        continue
185
                    logger.info(u'provisionning users %s to %s',
186
                                     u', '.join(map(unicode, users)), u', '.join(audience))
186
                    logger.info(u'provisionning users %s to %s', u', '.join(
187
                        map(force_text, users)), u', '.join(audience))
187 188
                    notify_agents({
188 189
                        '@type': 'provision',
189 190
                        'issuer': issuer,
......
197 198
        elif users:
198 199
            audience = [audience for ou in OU.objects.all()
199 200
                        for s, audience in self.get_audience(ou)]
200
            logger.info(u'deprovisionning users %s from %s', u', '.join(map(unicode, users)),
201
                             u', '.join(audience))
201
            logger.info(u'deprovisionning users %s from %s', u', '.join(
202
                map(force_text, users)), u', '.join(audience))
202 203
            notify_agents({
203 204
                '@type': 'deprovision',
204 205
                'issuer': issuer,
......
263 264
            })
264 265

  
265 266
        global_roles = set(ous.get(None, []))
266
        for ou, ou_roles in ous.iteritems():
267
        for ou, ou_roles in ous.items():
267 268
            sent_roles = set(ou_roles) | global_roles
268 269
            helper(ou, sent_roles)
269 270

  
hobo/multitenant/settings_loaders.py
1 1
import os
2 2
import json
3 3
import hashlib
4
from importlib import import_module
5 4

  
6 5
from django.conf import settings
7
from django.utils.encoding import smart_bytes
6
from django.utils.encoding import force_bytes
8 7
from django.utils.http import urlencode
9 8
from django.utils.six.moves.urllib import parse as urlparse
10 9

  
......
277 276
        return 0
278 277

  
279 278
    def update_settings(self, tenant_settings, tenant):
280
        domain_hash = hashlib.md5(smart_bytes(tenant.domain_url)).hexdigest()[:6]
279
        domain_hash = hashlib.md5(force_bytes(tenant.domain_url)).hexdigest()[:6]
281 280
        tenant_settings.CSRF_COOKIE_NAME = 'csrftoken-%s' % domain_hash
282 281
        tenant_settings.SESSION_COOKIE_NAME = 'sessionid-%s' % domain_hash
283 282
        # unique but common name for authentic opened session cookie name
284 283
        if getattr(tenant_settings, 'TEMPLATE_VARS', None):
285 284
            idp_url = tenant_settings.TEMPLATE_VARS.get('idp_url')
286 285
            if idp_url:
287
                idp_hash = hashlib.md5(smart_bytes(idp_url)).hexdigest()[:6]
286
                idp_hash = hashlib.md5(force_bytes(idp_url)).hexdigest()[:6]
288 287
                cookie_name = 'a2-opened-session-%s' % idp_hash
289 288
                tenant_settings.A2_OPENED_SESSION_COOKIE_NAME = cookie_name
290 289
                tenant_settings.MELLON_OPENED_SESSION_COOKIE_NAME = cookie_name
......
308 307
            if not getattr(tenant_settings, 'A2_IDP_OIDC_JWKSET', None):
309 308
                from jwcrypto import jwk
310 309
                jwkkey = jwk.JWK.from_pem(
311
                        tenant_settings.A2_IDP_SAML2_SIGNATURE_PRIVATE_KEY)
310
                    force_bytes(tenant_settings.A2_IDP_SAML2_SIGNATURE_PRIVATE_KEY))
312 311
                jwkset = jwk.JWKSet()
313 312
                jwkset['keys'].add(jwkkey)
314 313
                tenant_settings.A2_IDP_OIDC_JWKSET = json.loads(jwkset.export())
tests_authentic/test_hobo_deploy.py
308 308
        ]
309 309
    }
310 310
    hobo_json_content = json.dumps(env)
311
    hobo_json = tempfile.NamedTemporaryFile()
311
    hobo_json = tempfile.NamedTemporaryFile(mode='w')
312 312
    hobo_json.write(hobo_json_content)
313 313
    hobo_json.flush()
314 314

  
......
465 465
def test_import_template(db, tenant_base):
466 466
    def with_uuid_removed(input):
467 467
        if isinstance(input, dict):
468
            for key in input.keys():
468
            for key in list(input.keys()):
469 469
                if key == 'uuid':
470 470
                    input.pop('uuid')
471
            return {k: with_uuid_removed(v) for k, v in input.iteritems()}
471
            return {k: with_uuid_removed(v) for k, v in input.items()}
472 472
        elif isinstance(input, list):
473 473
            return [with_uuid_removed(e) for e in input]
474 474
        else:
475 475
            return input
476 476

  
477
    def with_lists_sorted(input):
478
        if isinstance(input, dict):
479
            return {k: with_lists_sorted(v) for k, v in input.iteritems()}
480
        if isinstance(input, list):
481
            return with_lists_sorted(input.sort())
477
    def with_lists_sorted(value):
478
        if isinstance(value, dict):
479
            return {k: with_lists_sorted(v) for k, v in value.items()}
480
        if isinstance(value, list):
481
            value = [with_lists_sorted(elt) for elt in value]
482
            value.sort(key=lambda l: sorted(tuple(
483
                d.items()) if isinstance(d, dict) else d for d in l))
484
            return value
482 485
        else:
483
            return input
486
            return value
484 487

  
485 488
    call_command('create_tenant', 'authentic.example.net')
486 489
    tenant = TenantMiddleware.get_tenant_by_hostname('authentic.example.net')
tests_authentic/test_rest_authentication.py
1 1
import pytest
2
import urllib
2
from django.utils.six.moves.urllib import parse as urllib
3 3

  
4 4
from rest_framework.exceptions import AuthenticationFailed
5 5

  
6
-