Initial commit
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
# Copyright (c) 2015 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
|
||||
default_app_config = 'awx.sso.apps.SSOConfig'
|
||||
@@ -0,0 +1,9 @@
|
||||
# Django
|
||||
from django.apps import AppConfig
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
|
||||
class SSOConfig(AppConfig):
|
||||
|
||||
name = 'awx.sso'
|
||||
verbose_name = _('Single Sign-On')
|
||||
@@ -0,0 +1,398 @@
|
||||
# Copyright (c) 2015 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
|
||||
# Python
|
||||
from collections import OrderedDict
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
import ldap
|
||||
|
||||
# Django
|
||||
from django.dispatch import receiver
|
||||
from django.contrib.auth.models import User
|
||||
from django.conf import settings as django_settings
|
||||
from django.core.signals import setting_changed
|
||||
from django.utils.encoding import force_text
|
||||
|
||||
# django-auth-ldap
|
||||
from django_auth_ldap.backend import LDAPSettings as BaseLDAPSettings
|
||||
from django_auth_ldap.backend import LDAPBackend as BaseLDAPBackend
|
||||
from django_auth_ldap.backend import populate_user
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
# radiusauth
|
||||
from radiusauth.backends import RADIUSBackend as BaseRADIUSBackend
|
||||
|
||||
# tacacs+ auth
|
||||
import tacacs_plus
|
||||
|
||||
# social
|
||||
from social_core.backends.saml import OID_USERID
|
||||
from social_core.backends.saml import SAMLAuth as BaseSAMLAuth
|
||||
from social_core.backends.saml import SAMLIdentityProvider as BaseSAMLIdentityProvider
|
||||
|
||||
# Ansible Tower
|
||||
from awx.sso.models import UserEnterpriseAuth
|
||||
|
||||
logger = logging.getLogger('awx.sso.backends')
|
||||
|
||||
|
||||
class LDAPSettings(BaseLDAPSettings):
|
||||
|
||||
defaults = dict(list(BaseLDAPSettings.defaults.items()) + list({
|
||||
'ORGANIZATION_MAP': {},
|
||||
'TEAM_MAP': {},
|
||||
'GROUP_TYPE_PARAMS': {},
|
||||
}.items()))
|
||||
|
||||
def __init__(self, prefix='AUTH_LDAP_', defaults={}):
|
||||
super(LDAPSettings, self).__init__(prefix, defaults)
|
||||
|
||||
# If a DB-backed setting is specified that wipes out the
|
||||
# OPT_NETWORK_TIMEOUT, fall back to a sane default
|
||||
if ldap.OPT_NETWORK_TIMEOUT not in getattr(self, 'CONNECTION_OPTIONS', {}):
|
||||
options = getattr(self, 'CONNECTION_OPTIONS', {})
|
||||
options[ldap.OPT_NETWORK_TIMEOUT] = 30
|
||||
self.CONNECTION_OPTIONS = options
|
||||
|
||||
# when specifying `.set_option()` calls for TLS in python-ldap, the
|
||||
# *order* in which you invoke them *matters*, particularly in Python3,
|
||||
# where dictionary insertion order is persisted
|
||||
#
|
||||
# specifically, it is *critical* that `ldap.OPT_X_TLS_NEWCTX` be set *last*
|
||||
# this manual sorting puts `OPT_X_TLS_NEWCTX` *after* other TLS-related
|
||||
# options
|
||||
#
|
||||
# see: https://github.com/python-ldap/python-ldap/issues/55
|
||||
newctx_option = self.CONNECTION_OPTIONS.pop(ldap.OPT_X_TLS_NEWCTX, None)
|
||||
self.CONNECTION_OPTIONS = OrderedDict(self.CONNECTION_OPTIONS)
|
||||
if newctx_option is not None:
|
||||
self.CONNECTION_OPTIONS[ldap.OPT_X_TLS_NEWCTX] = newctx_option
|
||||
|
||||
|
||||
class LDAPBackend(BaseLDAPBackend):
|
||||
'''
|
||||
Custom LDAP backend for AWX.
|
||||
'''
|
||||
|
||||
settings_prefix = 'AUTH_LDAP_'
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._dispatch_uid = uuid.uuid4()
|
||||
super(LDAPBackend, self).__init__(*args, **kwargs)
|
||||
setting_changed.connect(self._on_setting_changed, dispatch_uid=self._dispatch_uid)
|
||||
|
||||
def _on_setting_changed(self, sender, **kwargs):
|
||||
# If any AUTH_LDAP_* setting changes, force settings to be reloaded for
|
||||
# this backend instance.
|
||||
if kwargs.get('setting', '').startswith(self.settings_prefix):
|
||||
self._settings = None
|
||||
|
||||
def _get_settings(self):
|
||||
if self._settings is None:
|
||||
self._settings = LDAPSettings(self.settings_prefix)
|
||||
return self._settings
|
||||
|
||||
def _set_settings(self, settings):
|
||||
self._settings = settings
|
||||
|
||||
settings = property(_get_settings, _set_settings)
|
||||
|
||||
def authenticate(self, request, username, password):
|
||||
if self.settings.START_TLS and ldap.OPT_X_TLS_REQUIRE_CERT in self.settings.CONNECTION_OPTIONS:
|
||||
# with python-ldap, if you want to set connection-specific TLS
|
||||
# parameters, you must also specify OPT_X_TLS_NEWCTX = 0
|
||||
# see: https://stackoverflow.com/a/29722445
|
||||
# see: https://stackoverflow.com/a/38136255
|
||||
self.settings.CONNECTION_OPTIONS[ldap.OPT_X_TLS_NEWCTX] = 0
|
||||
|
||||
if not self.settings.SERVER_URI:
|
||||
return None
|
||||
try:
|
||||
user = User.objects.get(username=username)
|
||||
if user and (not user.profile or not user.profile.ldap_dn):
|
||||
return None
|
||||
except User.DoesNotExist:
|
||||
pass
|
||||
|
||||
try:
|
||||
for setting_name, type_ in [
|
||||
('GROUP_SEARCH', 'LDAPSearch'),
|
||||
('GROUP_TYPE', 'LDAPGroupType'),
|
||||
]:
|
||||
if getattr(self.settings, setting_name) is None:
|
||||
raise ImproperlyConfigured(
|
||||
"{} must be an {} instance.".format(setting_name, type_)
|
||||
)
|
||||
return super(LDAPBackend, self).authenticate(request, username, password)
|
||||
except Exception:
|
||||
logger.exception("Encountered an error authenticating to LDAP")
|
||||
return None
|
||||
|
||||
def get_user(self, user_id):
|
||||
if not self.settings.SERVER_URI:
|
||||
return None
|
||||
return super(LDAPBackend, self).get_user(user_id)
|
||||
|
||||
# Disable any LDAP based authorization / permissions checking.
|
||||
|
||||
def has_perm(self, user, perm, obj=None):
|
||||
return False
|
||||
|
||||
def has_module_perms(self, user, app_label):
|
||||
return False
|
||||
|
||||
def get_all_permissions(self, user, obj=None):
|
||||
return set()
|
||||
|
||||
def get_group_permissions(self, user, obj=None):
|
||||
return set()
|
||||
|
||||
|
||||
class LDAPBackend1(LDAPBackend):
|
||||
settings_prefix = 'AUTH_LDAP_1_'
|
||||
|
||||
|
||||
class LDAPBackend2(LDAPBackend):
|
||||
settings_prefix = 'AUTH_LDAP_2_'
|
||||
|
||||
|
||||
class LDAPBackend3(LDAPBackend):
|
||||
settings_prefix = 'AUTH_LDAP_3_'
|
||||
|
||||
|
||||
class LDAPBackend4(LDAPBackend):
|
||||
settings_prefix = 'AUTH_LDAP_4_'
|
||||
|
||||
|
||||
class LDAPBackend5(LDAPBackend):
|
||||
settings_prefix = 'AUTH_LDAP_5_'
|
||||
|
||||
|
||||
def _decorate_enterprise_user(user, provider):
|
||||
user.set_unusable_password()
|
||||
user.save()
|
||||
enterprise_auth, _ = UserEnterpriseAuth.objects.get_or_create(user=user, provider=provider)
|
||||
return enterprise_auth
|
||||
|
||||
|
||||
def _get_or_set_enterprise_user(username, password, provider):
|
||||
created = False
|
||||
try:
|
||||
user = User.objects.prefetch_related('enterprise_auth').get(username=username)
|
||||
except User.DoesNotExist:
|
||||
user = User(username=username)
|
||||
enterprise_auth = _decorate_enterprise_user(user, provider)
|
||||
logger.debug("Created enterprise user %s via %s backend." %
|
||||
(username, enterprise_auth.get_provider_display()))
|
||||
created = True
|
||||
if created or user.is_in_enterprise_category(provider):
|
||||
return user
|
||||
logger.warn("Enterprise user %s already defined in Tower." % username)
|
||||
|
||||
|
||||
class RADIUSBackend(BaseRADIUSBackend):
|
||||
'''
|
||||
Custom Radius backend to verify license status
|
||||
'''
|
||||
|
||||
def authenticate(self, request, username, password):
|
||||
if not django_settings.RADIUS_SERVER:
|
||||
return None
|
||||
return super(RADIUSBackend, self).authenticate(request, username, password)
|
||||
|
||||
def get_user(self, user_id):
|
||||
if not django_settings.RADIUS_SERVER:
|
||||
return None
|
||||
user = super(RADIUSBackend, self).get_user(user_id)
|
||||
if not user.has_usable_password():
|
||||
return user
|
||||
|
||||
def get_django_user(self, username, password=None):
|
||||
return _get_or_set_enterprise_user(force_text(username), force_text(password), 'radius')
|
||||
|
||||
|
||||
class TACACSPlusBackend(object):
|
||||
'''
|
||||
Custom TACACS+ auth backend for AWX
|
||||
'''
|
||||
|
||||
def authenticate(self, request, username, password):
|
||||
if not django_settings.TACACSPLUS_HOST:
|
||||
return None
|
||||
try:
|
||||
# Upstream TACACS+ client does not accept non-string, so convert if needed.
|
||||
auth = tacacs_plus.TACACSClient(
|
||||
django_settings.TACACSPLUS_HOST,
|
||||
django_settings.TACACSPLUS_PORT,
|
||||
django_settings.TACACSPLUS_SECRET,
|
||||
timeout=django_settings.TACACSPLUS_SESSION_TIMEOUT,
|
||||
).authenticate(
|
||||
username, password,
|
||||
authen_type=tacacs_plus.TAC_PLUS_AUTHEN_TYPES[django_settings.TACACSPLUS_AUTH_PROTOCOL],
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("TACACS+ Authentication Error: %s" % str(e))
|
||||
return None
|
||||
if auth.valid:
|
||||
return _get_or_set_enterprise_user(username, password, 'tacacs+')
|
||||
|
||||
def get_user(self, user_id):
|
||||
if not django_settings.TACACSPLUS_HOST:
|
||||
return None
|
||||
try:
|
||||
return User.objects.get(pk=user_id)
|
||||
except User.DoesNotExist:
|
||||
return None
|
||||
|
||||
|
||||
class TowerSAMLIdentityProvider(BaseSAMLIdentityProvider):
|
||||
'''
|
||||
Custom Identity Provider to make attributes to what we expect.
|
||||
'''
|
||||
|
||||
def get_user_permanent_id(self, attributes):
|
||||
uid = attributes[self.conf.get('attr_user_permanent_id', OID_USERID)]
|
||||
if isinstance(uid, str):
|
||||
return uid
|
||||
return uid[0]
|
||||
|
||||
def get_attr(self, attributes, conf_key, default_attribute):
|
||||
"""
|
||||
Get the attribute 'default_attribute' out of the attributes,
|
||||
unless self.conf[conf_key] overrides the default by specifying
|
||||
another attribute to use.
|
||||
"""
|
||||
key = self.conf.get(conf_key, default_attribute)
|
||||
value = attributes[key] if key in attributes else None
|
||||
# In certain implementations (like https://pagure.io/ipsilon) this value is a string, not a list
|
||||
if isinstance(value, (list, tuple)):
|
||||
value = value[0]
|
||||
if conf_key in ('attr_first_name', 'attr_last_name', 'attr_username', 'attr_email') and value is None:
|
||||
logger.warn("Could not map user detail '%s' from SAML attribute '%s'; "
|
||||
"update SOCIAL_AUTH_SAML_ENABLED_IDPS['%s']['%s'] with the correct SAML attribute.",
|
||||
conf_key[5:], key, self.name, conf_key)
|
||||
return str(value) if value is not None else value
|
||||
|
||||
|
||||
class SAMLAuth(BaseSAMLAuth):
|
||||
'''
|
||||
Custom SAMLAuth backend to verify license status
|
||||
'''
|
||||
|
||||
def get_idp(self, idp_name):
|
||||
idp_config = self.setting('ENABLED_IDPS')[idp_name]
|
||||
return TowerSAMLIdentityProvider(idp_name, **idp_config)
|
||||
|
||||
def authenticate(self, request, *args, **kwargs):
|
||||
if not all([django_settings.SOCIAL_AUTH_SAML_SP_ENTITY_ID, django_settings.SOCIAL_AUTH_SAML_SP_PUBLIC_CERT,
|
||||
django_settings.SOCIAL_AUTH_SAML_SP_PRIVATE_KEY, django_settings.SOCIAL_AUTH_SAML_ORG_INFO,
|
||||
django_settings.SOCIAL_AUTH_SAML_TECHNICAL_CONTACT, django_settings.SOCIAL_AUTH_SAML_SUPPORT_CONTACT,
|
||||
django_settings.SOCIAL_AUTH_SAML_ENABLED_IDPS]):
|
||||
return None
|
||||
user = super(SAMLAuth, self).authenticate(request, *args, **kwargs)
|
||||
# Comes from https://github.com/omab/python-social-auth/blob/v0.2.21/social/backends/base.py#L91
|
||||
if getattr(user, 'is_new', False):
|
||||
_decorate_enterprise_user(user, 'saml')
|
||||
elif user and not user.is_in_enterprise_category('saml'):
|
||||
return None
|
||||
return user
|
||||
|
||||
def get_user(self, user_id):
|
||||
if not all([django_settings.SOCIAL_AUTH_SAML_SP_ENTITY_ID, django_settings.SOCIAL_AUTH_SAML_SP_PUBLIC_CERT,
|
||||
django_settings.SOCIAL_AUTH_SAML_SP_PRIVATE_KEY, django_settings.SOCIAL_AUTH_SAML_ORG_INFO,
|
||||
django_settings.SOCIAL_AUTH_SAML_TECHNICAL_CONTACT, django_settings.SOCIAL_AUTH_SAML_SUPPORT_CONTACT,
|
||||
django_settings.SOCIAL_AUTH_SAML_ENABLED_IDPS]):
|
||||
return None
|
||||
return super(SAMLAuth, self).get_user(user_id)
|
||||
|
||||
|
||||
def _update_m2m_from_groups(user, ldap_user, related, opts, remove=True):
|
||||
'''
|
||||
Hepler function to update m2m relationship based on LDAP group membership.
|
||||
'''
|
||||
should_add = False
|
||||
if opts is None:
|
||||
return
|
||||
elif not opts:
|
||||
pass
|
||||
elif opts is True:
|
||||
should_add = True
|
||||
else:
|
||||
if isinstance(opts, str):
|
||||
opts = [opts]
|
||||
for group_dn in opts:
|
||||
if not isinstance(group_dn, str):
|
||||
continue
|
||||
if ldap_user._get_groups().is_member_of(group_dn):
|
||||
should_add = True
|
||||
if should_add:
|
||||
user.save()
|
||||
related.add(user)
|
||||
elif remove and user in related.all():
|
||||
user.save()
|
||||
related.remove(user)
|
||||
|
||||
|
||||
@receiver(populate_user, dispatch_uid='populate-ldap-user')
|
||||
def on_populate_user(sender, **kwargs):
|
||||
'''
|
||||
Handle signal from LDAP backend to populate the user object. Update user
|
||||
organization/team memberships according to their LDAP groups.
|
||||
'''
|
||||
from awx.main.models import Organization, Team
|
||||
user = kwargs['user']
|
||||
ldap_user = kwargs['ldap_user']
|
||||
backend = ldap_user.backend
|
||||
|
||||
# Prefetch user's groups to prevent LDAP queries for each org/team when
|
||||
# checking membership.
|
||||
ldap_user._get_groups().get_group_dns()
|
||||
|
||||
# If the LDAP user has a first or last name > $maxlen chars, truncate it
|
||||
for field in ('first_name', 'last_name'):
|
||||
max_len = User._meta.get_field(field).max_length
|
||||
field_len = len(getattr(user, field))
|
||||
if field_len > max_len:
|
||||
setattr(user, field, getattr(user, field)[:max_len])
|
||||
logger.warn(
|
||||
'LDAP user {} has {} > max {} characters'.format(user.username, field, max_len)
|
||||
)
|
||||
|
||||
# Update organization membership based on group memberships.
|
||||
org_map = getattr(backend.settings, 'ORGANIZATION_MAP', {})
|
||||
for org_name, org_opts in org_map.items():
|
||||
org, created = Organization.objects.get_or_create(name=org_name)
|
||||
remove = bool(org_opts.get('remove', True))
|
||||
admins_opts = org_opts.get('admins', None)
|
||||
remove_admins = bool(org_opts.get('remove_admins', remove))
|
||||
_update_m2m_from_groups(user, ldap_user, org.admin_role.members, admins_opts,
|
||||
remove_admins)
|
||||
auditors_opts = org_opts.get('auditors', None)
|
||||
remove_auditors = bool(org_opts.get('remove_auditors', remove))
|
||||
_update_m2m_from_groups(user, ldap_user, org.auditor_role.members, auditors_opts,
|
||||
remove_auditors)
|
||||
users_opts = org_opts.get('users', None)
|
||||
remove_users = bool(org_opts.get('remove_users', remove))
|
||||
_update_m2m_from_groups(user, ldap_user, org.member_role.members, users_opts,
|
||||
remove_users)
|
||||
|
||||
# Update team membership based on group memberships.
|
||||
team_map = getattr(backend.settings, 'TEAM_MAP', {})
|
||||
for team_name, team_opts in team_map.items():
|
||||
if 'organization' not in team_opts:
|
||||
continue
|
||||
org, created = Organization.objects.get_or_create(name=team_opts['organization'])
|
||||
team, created = Team.objects.get_or_create(name=team_name, organization=org)
|
||||
users_opts = team_opts.get('users', None)
|
||||
remove = bool(team_opts.get('remove', True))
|
||||
_update_m2m_from_groups(user, ldap_user, team.member_role.members, users_opts,
|
||||
remove)
|
||||
|
||||
# Update user profile to store LDAP DN.
|
||||
user.save()
|
||||
profile = user.profile
|
||||
if profile.ldap_dn != ldap_user.dn:
|
||||
profile.ldap_dn = ldap_user.dn
|
||||
profile.save()
|
||||
+1547
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,788 @@
|
||||
import collections
|
||||
import copy
|
||||
import inspect
|
||||
import json
|
||||
import re
|
||||
|
||||
# Python LDAP
|
||||
import ldap
|
||||
import awx
|
||||
|
||||
# Django
|
||||
from django.utils import six
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
# Django Auth LDAP
|
||||
import django_auth_ldap.config
|
||||
from django_auth_ldap.config import (
|
||||
LDAPSearch,
|
||||
LDAPSearchUnion,
|
||||
)
|
||||
|
||||
from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.fields import empty, Field, SkipField
|
||||
|
||||
# This must be imported so get_subclasses picks it up
|
||||
from awx.sso.ldap_group_types import PosixUIDGroupType # noqa
|
||||
|
||||
# Tower
|
||||
from awx.conf import fields
|
||||
from awx.main.validators import validate_certificate
|
||||
from awx.sso.validators import ( # noqa
|
||||
validate_ldap_dn,
|
||||
validate_ldap_bind_dn,
|
||||
validate_ldap_dn_with_user,
|
||||
validate_ldap_filter,
|
||||
validate_ldap_filter_with_user,
|
||||
validate_tacacsplus_disallow_nonascii,
|
||||
)
|
||||
|
||||
|
||||
def get_subclasses(cls):
|
||||
for subclass in cls.__subclasses__():
|
||||
for subsubclass in get_subclasses(subclass):
|
||||
yield subsubclass
|
||||
yield subclass
|
||||
|
||||
|
||||
def find_class_in_modules(class_name):
|
||||
'''
|
||||
Used to find ldap subclasses by string
|
||||
'''
|
||||
module_search_space = [django_auth_ldap.config, awx.sso.ldap_group_types]
|
||||
for m in module_search_space:
|
||||
cls = getattr(m, class_name, None)
|
||||
if cls:
|
||||
return cls
|
||||
return None
|
||||
|
||||
|
||||
class DependsOnMixin():
|
||||
def get_depends_on(self):
|
||||
"""
|
||||
Get the value of the dependent field.
|
||||
First try to find the value in the request.
|
||||
Then fall back to the raw value from the setting in the DB.
|
||||
"""
|
||||
from django.conf import settings
|
||||
dependent_key = next(iter(self.depends_on))
|
||||
|
||||
if self.context:
|
||||
request = self.context.get('request', None)
|
||||
if request and request.data and \
|
||||
request.data.get(dependent_key, None):
|
||||
return request.data.get(dependent_key)
|
||||
res = settings._get_local(dependent_key, validate=False)
|
||||
return res
|
||||
|
||||
|
||||
class _Forbidden(Field):
|
||||
default_error_messages = {
|
||||
'invalid': _('Invalid field.'),
|
||||
}
|
||||
|
||||
def run_validation(self, value):
|
||||
self.fail('invalid')
|
||||
|
||||
|
||||
class HybridDictField(fields.DictField):
|
||||
"""A DictField, but with defined fixed Fields for certain keys.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.allow_blank = kwargs.pop('allow_blank', False)
|
||||
|
||||
fields = [
|
||||
sorted(
|
||||
((field_name, obj) for field_name, obj in cls.__dict__.items()
|
||||
if isinstance(obj, Field) and field_name != 'child'),
|
||||
key=lambda x: x[1]._creation_counter
|
||||
)
|
||||
for cls in reversed(self.__class__.__mro__)
|
||||
]
|
||||
self._declared_fields = collections.OrderedDict(f for group in fields for f in group)
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def to_representation(self, value):
|
||||
fields = copy.deepcopy(self._declared_fields)
|
||||
return {
|
||||
key: field.to_representation(val) if val is not None else None
|
||||
for key, val, field in (
|
||||
(six.text_type(key), val, fields.get(key, self.child))
|
||||
for key, val in value.items()
|
||||
)
|
||||
if not field.write_only
|
||||
}
|
||||
|
||||
def run_child_validation(self, data):
|
||||
result = {}
|
||||
|
||||
if not data and self.allow_blank:
|
||||
return result
|
||||
|
||||
errors = collections.OrderedDict()
|
||||
fields = copy.deepcopy(self._declared_fields)
|
||||
keys = set(fields.keys()) | set(data.keys())
|
||||
|
||||
for key in keys:
|
||||
value = data.get(key, empty)
|
||||
key = six.text_type(key)
|
||||
field = fields.get(key, self.child)
|
||||
try:
|
||||
if field.read_only:
|
||||
continue # Ignore read_only fields, as Serializer seems to do.
|
||||
result[key] = field.run_validation(value)
|
||||
except ValidationError as e:
|
||||
errors[key] = e.detail
|
||||
except SkipField:
|
||||
pass
|
||||
|
||||
if not errors:
|
||||
return result
|
||||
raise ValidationError(errors)
|
||||
|
||||
|
||||
class AuthenticationBackendsField(fields.StringListField):
|
||||
|
||||
# Mapping of settings that must be set in order to enable each
|
||||
# authentication backend.
|
||||
REQUIRED_BACKEND_SETTINGS = collections.OrderedDict([
|
||||
('awx.sso.backends.LDAPBackend', [
|
||||
'AUTH_LDAP_SERVER_URI',
|
||||
]),
|
||||
('awx.sso.backends.LDAPBackend1', [
|
||||
'AUTH_LDAP_1_SERVER_URI',
|
||||
]),
|
||||
('awx.sso.backends.LDAPBackend2', [
|
||||
'AUTH_LDAP_2_SERVER_URI',
|
||||
]),
|
||||
('awx.sso.backends.LDAPBackend3', [
|
||||
'AUTH_LDAP_3_SERVER_URI',
|
||||
]),
|
||||
('awx.sso.backends.LDAPBackend4', [
|
||||
'AUTH_LDAP_4_SERVER_URI',
|
||||
]),
|
||||
('awx.sso.backends.LDAPBackend5', [
|
||||
'AUTH_LDAP_5_SERVER_URI',
|
||||
]),
|
||||
('awx.sso.backends.RADIUSBackend', [
|
||||
'RADIUS_SERVER',
|
||||
]),
|
||||
('social_core.backends.google.GoogleOAuth2', [
|
||||
'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY',
|
||||
'SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET',
|
||||
]),
|
||||
('social_core.backends.github.GithubOAuth2', [
|
||||
'SOCIAL_AUTH_GITHUB_KEY',
|
||||
'SOCIAL_AUTH_GITHUB_SECRET',
|
||||
]),
|
||||
('social_core.backends.github.GithubOrganizationOAuth2', [
|
||||
'SOCIAL_AUTH_GITHUB_ORG_KEY',
|
||||
'SOCIAL_AUTH_GITHUB_ORG_SECRET',
|
||||
'SOCIAL_AUTH_GITHUB_ORG_NAME',
|
||||
]),
|
||||
('social_core.backends.github.GithubTeamOAuth2', [
|
||||
'SOCIAL_AUTH_GITHUB_TEAM_KEY',
|
||||
'SOCIAL_AUTH_GITHUB_TEAM_SECRET',
|
||||
'SOCIAL_AUTH_GITHUB_TEAM_ID',
|
||||
]),
|
||||
('social_core.backends.github_enterprise.GithubEnterpriseOAuth2', [
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_URL',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_API_URL',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_KEY',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_SECRET',
|
||||
]),
|
||||
('social_core.backends.github_enterprise.GithubEnterpriseOrganizationOAuth2', [
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_URL',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_API_URL',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_KEY',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_SECRET',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_NAME',
|
||||
]),
|
||||
('social_core.backends.github_enterprise.GithubEnterpriseTeamOAuth2', [
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_URL',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_API_URL',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_KEY',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_SECRET',
|
||||
'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_ID',
|
||||
]),
|
||||
('social_core.backends.azuread.AzureADOAuth2', [
|
||||
'SOCIAL_AUTH_AZUREAD_OAUTH2_KEY',
|
||||
'SOCIAL_AUTH_AZUREAD_OAUTH2_SECRET',
|
||||
]),
|
||||
('awx.sso.backends.SAMLAuth', [
|
||||
'SOCIAL_AUTH_SAML_SP_ENTITY_ID',
|
||||
'SOCIAL_AUTH_SAML_SP_PUBLIC_CERT',
|
||||
'SOCIAL_AUTH_SAML_SP_PRIVATE_KEY',
|
||||
'SOCIAL_AUTH_SAML_ORG_INFO',
|
||||
'SOCIAL_AUTH_SAML_TECHNICAL_CONTACT',
|
||||
'SOCIAL_AUTH_SAML_SUPPORT_CONTACT',
|
||||
'SOCIAL_AUTH_SAML_ENABLED_IDPS',
|
||||
]),
|
||||
('django.contrib.auth.backends.ModelBackend', []),
|
||||
])
|
||||
|
||||
@classmethod
|
||||
def get_all_required_settings(cls):
|
||||
all_required_settings = set(['LICENSE'])
|
||||
for required_settings in cls.REQUIRED_BACKEND_SETTINGS.values():
|
||||
all_required_settings.update(required_settings)
|
||||
return all_required_settings
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs.setdefault('default', self._default_from_required_settings)
|
||||
super(AuthenticationBackendsField, self).__init__(*args, **kwargs)
|
||||
|
||||
def _default_from_required_settings(self):
|
||||
from django.conf import settings
|
||||
try:
|
||||
backends = settings._awx_conf_settings._get_default('AUTHENTICATION_BACKENDS')
|
||||
except AttributeError:
|
||||
backends = self.REQUIRED_BACKEND_SETTINGS.keys()
|
||||
# Filter which authentication backends are enabled based on their
|
||||
# required settings being defined and non-empty.
|
||||
for backend, required_settings in self.REQUIRED_BACKEND_SETTINGS.items():
|
||||
if backend not in backends:
|
||||
continue
|
||||
if all([getattr(settings, rs, None) for rs in required_settings]):
|
||||
continue
|
||||
backends = [x for x in backends if x != backend]
|
||||
return backends
|
||||
|
||||
|
||||
class LDAPServerURIField(fields.URLField):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
kwargs.setdefault('schemes', ('ldap', 'ldaps'))
|
||||
kwargs.setdefault('allow_plain_hostname', True)
|
||||
super(LDAPServerURIField, self).__init__(**kwargs)
|
||||
|
||||
def run_validators(self, value):
|
||||
for url in filter(None, re.split(r'[, ]', (value or ''))):
|
||||
super(LDAPServerURIField, self).run_validators(url)
|
||||
return value
|
||||
|
||||
|
||||
class LDAPConnectionOptionsField(fields.DictField):
|
||||
|
||||
default_error_messages = {
|
||||
'invalid_options': _('Invalid connection option(s): {invalid_options}.'),
|
||||
}
|
||||
|
||||
def to_representation(self, value):
|
||||
value = value or {}
|
||||
opt_names = ldap.OPT_NAMES_DICT
|
||||
# Convert integer options to their named constants.
|
||||
repr_value = {}
|
||||
for opt, opt_value in value.items():
|
||||
if opt in opt_names:
|
||||
repr_value[opt_names[opt]] = opt_value
|
||||
return repr_value
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = super(LDAPConnectionOptionsField, self).to_internal_value(data)
|
||||
valid_options = dict([(v, k) for k, v in ldap.OPT_NAMES_DICT.items()])
|
||||
invalid_options = set(data.keys()) - set(valid_options.keys())
|
||||
if invalid_options:
|
||||
invalid_options = sorted(list(invalid_options))
|
||||
options_display = json.dumps(invalid_options).lstrip('[').rstrip(']')
|
||||
self.fail('invalid_options', invalid_options=options_display)
|
||||
# Convert named options to their integer constants.
|
||||
internal_data = {}
|
||||
for opt_name, opt_value in data.items():
|
||||
internal_data[valid_options[opt_name]] = opt_value
|
||||
return internal_data
|
||||
|
||||
|
||||
class LDAPDNField(fields.CharField):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(LDAPDNField, self).__init__(**kwargs)
|
||||
self.validators.append(validate_ldap_dn)
|
||||
|
||||
def run_validation(self, data=empty):
|
||||
value = super(LDAPDNField, self).run_validation(data)
|
||||
# django-auth-ldap expects DN fields (like AUTH_LDAP_REQUIRE_GROUP)
|
||||
# to be either a valid string or ``None`` (not an empty string)
|
||||
return None if value == '' else value
|
||||
|
||||
|
||||
class LDAPDNListField(fields.StringListField):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(LDAPDNListField, self).__init__(**kwargs)
|
||||
self.validators.append(lambda dn: list(map(validate_ldap_dn, dn)))
|
||||
|
||||
def run_validation(self, data=empty):
|
||||
if not isinstance(data, (list, tuple)):
|
||||
data = [data]
|
||||
return super(LDAPDNListField, self).run_validation(data)
|
||||
|
||||
|
||||
class LDAPDNWithUserField(fields.CharField):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(LDAPDNWithUserField, self).__init__(**kwargs)
|
||||
self.validators.append(validate_ldap_dn_with_user)
|
||||
|
||||
def run_validation(self, data=empty):
|
||||
value = super(LDAPDNWithUserField, self).run_validation(data)
|
||||
# django-auth-ldap expects DN fields (like AUTH_LDAP_USER_DN_TEMPLATE)
|
||||
# to be either a valid string or ``None`` (not an empty string)
|
||||
return None if value == '' else value
|
||||
|
||||
|
||||
class LDAPFilterField(fields.CharField):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(LDAPFilterField, self).__init__(**kwargs)
|
||||
self.validators.append(validate_ldap_filter)
|
||||
|
||||
|
||||
class LDAPFilterWithUserField(fields.CharField):
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super(LDAPFilterWithUserField, self).__init__(**kwargs)
|
||||
self.validators.append(validate_ldap_filter_with_user)
|
||||
|
||||
|
||||
class LDAPScopeField(fields.ChoiceField):
|
||||
|
||||
def __init__(self, choices=None, **kwargs):
|
||||
choices = choices or [
|
||||
('SCOPE_BASE', _('Base')),
|
||||
('SCOPE_ONELEVEL', _('One Level')),
|
||||
('SCOPE_SUBTREE', _('Subtree')),
|
||||
]
|
||||
super(LDAPScopeField, self).__init__(choices, **kwargs)
|
||||
|
||||
def to_representation(self, value):
|
||||
for choice in self.choices.keys():
|
||||
if value == getattr(ldap, choice):
|
||||
return choice
|
||||
return super(LDAPScopeField, self).to_representation(value)
|
||||
|
||||
def to_internal_value(self, data):
|
||||
value = super(LDAPScopeField, self).to_internal_value(data)
|
||||
return getattr(ldap, value)
|
||||
|
||||
|
||||
class LDAPSearchField(fields.ListField):
|
||||
|
||||
default_error_messages = {
|
||||
'invalid_length': _('Expected a list of three items but got {length} instead.'),
|
||||
'type_error': _('Expected an instance of LDAPSearch but got {input_type} instead.'),
|
||||
}
|
||||
ldap_filter_field_class = LDAPFilterField
|
||||
|
||||
def to_representation(self, value):
|
||||
if not value:
|
||||
return []
|
||||
if not isinstance(value, LDAPSearch):
|
||||
self.fail('type_error', input_type=type(value))
|
||||
return [
|
||||
LDAPDNField().to_representation(value.base_dn),
|
||||
LDAPScopeField().to_representation(value.scope),
|
||||
self.ldap_filter_field_class().to_representation(value.filterstr),
|
||||
]
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = super(LDAPSearchField, self).to_internal_value(data)
|
||||
if len(data) == 0:
|
||||
return None
|
||||
if len(data) != 3:
|
||||
self.fail('invalid_length', length=len(data))
|
||||
return LDAPSearch(
|
||||
LDAPDNField().run_validation(data[0]),
|
||||
LDAPScopeField().run_validation(data[1]),
|
||||
self.ldap_filter_field_class().run_validation(data[2]),
|
||||
)
|
||||
|
||||
|
||||
class LDAPSearchWithUserField(LDAPSearchField):
|
||||
|
||||
ldap_filter_field_class = LDAPFilterWithUserField
|
||||
|
||||
|
||||
class LDAPSearchUnionField(fields.ListField):
|
||||
|
||||
default_error_messages = {
|
||||
'type_error': _('Expected an instance of LDAPSearch or LDAPSearchUnion but got {input_type} instead.'),
|
||||
}
|
||||
ldap_search_field_class = LDAPSearchWithUserField
|
||||
|
||||
def to_representation(self, value):
|
||||
if not value:
|
||||
return []
|
||||
elif isinstance(value, LDAPSearchUnion):
|
||||
return [self.ldap_search_field_class().to_representation(s) for s in value.searches]
|
||||
elif isinstance(value, LDAPSearch):
|
||||
return self.ldap_search_field_class().to_representation(value)
|
||||
else:
|
||||
self.fail('type_error', input_type=type(value))
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = super(LDAPSearchUnionField, self).to_internal_value(data)
|
||||
if len(data) == 0:
|
||||
return None
|
||||
if len(data) == 3 and isinstance(data[0], str):
|
||||
return self.ldap_search_field_class().run_validation(data)
|
||||
else:
|
||||
search_args = []
|
||||
for i in range(len(data)):
|
||||
if not isinstance(data[i], list):
|
||||
raise ValidationError('In order to ultilize LDAP Union, input element No. %d'
|
||||
' should be a search query array.' % (i + 1))
|
||||
try:
|
||||
search_args.append(self.ldap_search_field_class().run_validation(data[i]))
|
||||
except Exception as e:
|
||||
if hasattr(e, 'detail') and isinstance(e.detail, list):
|
||||
e.detail.insert(0, "Error parsing LDAP Union element No. %d:" % (i + 1))
|
||||
raise e
|
||||
return LDAPSearchUnion(*search_args)
|
||||
|
||||
|
||||
class LDAPUserAttrMapField(fields.DictField):
|
||||
|
||||
default_error_messages = {
|
||||
'invalid_attrs': _('Invalid user attribute(s): {invalid_attrs}.'),
|
||||
}
|
||||
valid_user_attrs = {'first_name', 'last_name', 'email'}
|
||||
child = fields.CharField()
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = super(LDAPUserAttrMapField, self).to_internal_value(data)
|
||||
invalid_attrs = (set(data.keys()) - self.valid_user_attrs)
|
||||
if invalid_attrs:
|
||||
invalid_attrs = sorted(list(invalid_attrs))
|
||||
attrs_display = json.dumps(invalid_attrs).lstrip('[').rstrip(']')
|
||||
self.fail('invalid_attrs', invalid_attrs=attrs_display)
|
||||
return data
|
||||
|
||||
|
||||
class LDAPGroupTypeField(fields.ChoiceField, DependsOnMixin):
|
||||
|
||||
default_error_messages = {
|
||||
'type_error': _('Expected an instance of LDAPGroupType but got {input_type} instead.'),
|
||||
'missing_parameters': _('Missing required parameters in {dependency}.'),
|
||||
'invalid_parameters': _('Invalid group_type parameters. Expected instance of dict but got {parameters_type} instead.')
|
||||
}
|
||||
|
||||
def __init__(self, choices=None, **kwargs):
|
||||
group_types = get_subclasses(django_auth_ldap.config.LDAPGroupType)
|
||||
choices = choices or [(x.__name__, x.__name__) for x in group_types]
|
||||
super(LDAPGroupTypeField, self).__init__(choices, **kwargs)
|
||||
|
||||
def to_representation(self, value):
|
||||
if not value:
|
||||
return 'MemberDNGroupType'
|
||||
if not isinstance(value, django_auth_ldap.config.LDAPGroupType):
|
||||
self.fail('type_error', input_type=type(value))
|
||||
return value.__class__.__name__
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = super(LDAPGroupTypeField, self).to_internal_value(data)
|
||||
if not data:
|
||||
return None
|
||||
|
||||
cls = find_class_in_modules(data)
|
||||
if not cls:
|
||||
return None
|
||||
|
||||
# Per-group type parameter validation and handling here
|
||||
|
||||
# Backwords compatability. Before AUTH_LDAP_GROUP_TYPE_PARAMS existed
|
||||
# MemberDNGroupType was the only group type, of the underlying lib, that
|
||||
# took a parameter.
|
||||
params = self.get_depends_on() or {}
|
||||
params_sanitized = dict()
|
||||
|
||||
cls_args = inspect.getargspec(cls.__init__).args[1:]
|
||||
|
||||
if cls_args:
|
||||
if not isinstance(params, dict):
|
||||
self.fail('invalid_parameters', parameters_type=type(params))
|
||||
|
||||
for attr in cls_args:
|
||||
if attr in params:
|
||||
params_sanitized[attr] = params[attr]
|
||||
|
||||
try:
|
||||
return cls(**params_sanitized)
|
||||
except TypeError:
|
||||
self.fail('missing_parameters', dependency=list(self.depends_on)[0])
|
||||
|
||||
|
||||
class LDAPGroupTypeParamsField(fields.DictField, DependsOnMixin):
|
||||
default_error_messages = {
|
||||
'invalid_keys': _('Invalid key(s): {invalid_keys}.'),
|
||||
}
|
||||
|
||||
def to_internal_value(self, value):
|
||||
value = super(LDAPGroupTypeParamsField, self).to_internal_value(value)
|
||||
if not value:
|
||||
return value
|
||||
group_type_str = self.get_depends_on()
|
||||
group_type_str = group_type_str or ''
|
||||
|
||||
group_type_cls = find_class_in_modules(group_type_str)
|
||||
if not group_type_cls:
|
||||
# Fail safe
|
||||
return {}
|
||||
|
||||
invalid_keys = set(value.keys()) - set(inspect.getargspec(group_type_cls.__init__).args[1:])
|
||||
if invalid_keys:
|
||||
invalid_keys = sorted(list(invalid_keys))
|
||||
keys_display = json.dumps(invalid_keys).lstrip('[').rstrip(']')
|
||||
self.fail('invalid_keys', invalid_keys=keys_display)
|
||||
return value
|
||||
|
||||
|
||||
class LDAPUserFlagsField(fields.DictField):
|
||||
|
||||
default_error_messages = {
|
||||
'invalid_flag': _('Invalid user flag: "{invalid_flag}".'),
|
||||
}
|
||||
valid_user_flags = {'is_superuser', 'is_system_auditor'}
|
||||
child = LDAPDNListField()
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = super(LDAPUserFlagsField, self).to_internal_value(data)
|
||||
invalid_flags = (set(data.keys()) - self.valid_user_flags)
|
||||
if invalid_flags:
|
||||
self.fail('invalid_flag', invalid_flag=list(invalid_flags)[0])
|
||||
return data
|
||||
|
||||
|
||||
class LDAPDNMapField(fields.StringListBooleanField):
|
||||
|
||||
child = LDAPDNField()
|
||||
|
||||
|
||||
class LDAPSingleOrganizationMapField(HybridDictField):
|
||||
|
||||
admins = LDAPDNMapField(allow_null=True, required=False)
|
||||
users = LDAPDNMapField(allow_null=True, required=False)
|
||||
auditors = LDAPDNMapField(allow_null=True, required=False)
|
||||
remove_admins = fields.BooleanField(required=False)
|
||||
remove_users = fields.BooleanField(required=False)
|
||||
remove_auditors = fields.BooleanField(required=False)
|
||||
|
||||
child = _Forbidden()
|
||||
|
||||
|
||||
class LDAPOrganizationMapField(fields.DictField):
|
||||
|
||||
child = LDAPSingleOrganizationMapField()
|
||||
|
||||
|
||||
class LDAPSingleTeamMapField(HybridDictField):
|
||||
|
||||
organization = fields.CharField()
|
||||
users = LDAPDNMapField(allow_null=True, required=False)
|
||||
remove = fields.BooleanField(required=False)
|
||||
|
||||
child = _Forbidden()
|
||||
|
||||
|
||||
class LDAPTeamMapField(fields.DictField):
|
||||
|
||||
child = LDAPSingleTeamMapField()
|
||||
|
||||
|
||||
class SocialMapStringRegexField(fields.CharField):
|
||||
|
||||
def to_representation(self, value):
|
||||
if isinstance(value, type(re.compile(''))):
|
||||
flags = []
|
||||
if value.flags & re.I:
|
||||
flags.append('i')
|
||||
if value.flags & re.M:
|
||||
flags.append('m')
|
||||
return '/{}/{}'.format(value.pattern, ''.join(flags))
|
||||
else:
|
||||
return super(SocialMapStringRegexField, self).to_representation(value)
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = super(SocialMapStringRegexField, self).to_internal_value(data)
|
||||
match = re.match(r'^/(?P<pattern>.*)/(?P<flags>[im]+)?$', data)
|
||||
if match:
|
||||
flags = 0
|
||||
if match.group('flags'):
|
||||
if 'i' in match.group('flags'):
|
||||
flags |= re.I
|
||||
if 'm' in match.group('flags'):
|
||||
flags |= re.M
|
||||
try:
|
||||
return re.compile(match.group('pattern'), flags)
|
||||
except re.error as e:
|
||||
raise ValidationError('{}: {}'.format(e, data))
|
||||
return data
|
||||
|
||||
|
||||
class SocialMapField(fields.ListField):
|
||||
|
||||
default_error_messages = {
|
||||
'type_error': _('Expected None, True, False, a string or list of strings but got {input_type} instead.'),
|
||||
}
|
||||
child = SocialMapStringRegexField()
|
||||
|
||||
def to_representation(self, value):
|
||||
if isinstance(value, (list, tuple)):
|
||||
return super(SocialMapField, self).to_representation(value)
|
||||
elif value in fields.NullBooleanField.TRUE_VALUES:
|
||||
return True
|
||||
elif value in fields.NullBooleanField.FALSE_VALUES:
|
||||
return False
|
||||
elif value in fields.NullBooleanField.NULL_VALUES:
|
||||
return None
|
||||
elif isinstance(value, (str, type(re.compile('')))):
|
||||
return self.child.to_representation(value)
|
||||
else:
|
||||
self.fail('type_error', input_type=type(value))
|
||||
|
||||
def to_internal_value(self, data):
|
||||
if isinstance(data, (list, tuple)):
|
||||
return super(SocialMapField, self).to_internal_value(data)
|
||||
elif data in fields.NullBooleanField.TRUE_VALUES:
|
||||
return True
|
||||
elif data in fields.NullBooleanField.FALSE_VALUES:
|
||||
return False
|
||||
elif data in fields.NullBooleanField.NULL_VALUES:
|
||||
return None
|
||||
elif isinstance(data, str):
|
||||
return self.child.run_validation(data)
|
||||
else:
|
||||
self.fail('type_error', input_type=type(data))
|
||||
|
||||
|
||||
class SocialSingleOrganizationMapField(HybridDictField):
|
||||
|
||||
admins = SocialMapField(allow_null=True, required=False)
|
||||
users = SocialMapField(allow_null=True, required=False)
|
||||
remove_admins = fields.BooleanField(required=False)
|
||||
remove_users = fields.BooleanField(required=False)
|
||||
|
||||
child = _Forbidden()
|
||||
|
||||
|
||||
class SocialOrganizationMapField(fields.DictField):
|
||||
|
||||
child = SocialSingleOrganizationMapField()
|
||||
|
||||
|
||||
class SocialSingleTeamMapField(HybridDictField):
|
||||
|
||||
organization = fields.CharField()
|
||||
users = SocialMapField(allow_null=True, required=False)
|
||||
remove = fields.BooleanField(required=False)
|
||||
|
||||
child = _Forbidden()
|
||||
|
||||
|
||||
class SocialTeamMapField(fields.DictField):
|
||||
|
||||
child = SocialSingleTeamMapField()
|
||||
|
||||
|
||||
class SAMLOrgInfoValueField(HybridDictField):
|
||||
|
||||
name = fields.CharField()
|
||||
displayname = fields.CharField()
|
||||
url = fields.URLField()
|
||||
|
||||
|
||||
class SAMLOrgInfoField(fields.DictField):
|
||||
|
||||
default_error_messages = {
|
||||
'invalid_lang_code': _('Invalid language code(s) for org info: {invalid_lang_codes}.'),
|
||||
}
|
||||
child = SAMLOrgInfoValueField()
|
||||
|
||||
def to_internal_value(self, data):
|
||||
data = super(SAMLOrgInfoField, self).to_internal_value(data)
|
||||
invalid_keys = set()
|
||||
for key in data.keys():
|
||||
if not re.match(r'^[a-z]{2}(?:-[a-z]{2})??$', key, re.I):
|
||||
invalid_keys.add(key)
|
||||
if invalid_keys:
|
||||
invalid_keys = sorted(list(invalid_keys))
|
||||
keys_display = json.dumps(invalid_keys).lstrip('[').rstrip(']')
|
||||
self.fail('invalid_lang_code', invalid_lang_codes=keys_display)
|
||||
return data
|
||||
|
||||
|
||||
class SAMLContactField(HybridDictField):
|
||||
|
||||
givenName = fields.CharField()
|
||||
emailAddress = fields.EmailField()
|
||||
|
||||
|
||||
class SAMLIdPField(HybridDictField):
|
||||
|
||||
entity_id = fields.CharField()
|
||||
url = fields.URLField()
|
||||
x509cert = fields.CharField(validators=[validate_certificate])
|
||||
attr_user_permanent_id = fields.CharField(required=False)
|
||||
attr_first_name = fields.CharField(required=False)
|
||||
attr_last_name = fields.CharField(required=False)
|
||||
attr_username = fields.CharField(required=False)
|
||||
attr_email = fields.CharField(required=False)
|
||||
|
||||
|
||||
class SAMLEnabledIdPsField(fields.DictField):
|
||||
|
||||
child = SAMLIdPField()
|
||||
|
||||
|
||||
class SAMLSecurityField(HybridDictField):
|
||||
|
||||
nameIdEncrypted = fields.BooleanField(required=False)
|
||||
authnRequestsSigned = fields.BooleanField(required=False)
|
||||
logoutRequestSigned = fields.BooleanField(required=False)
|
||||
logoutResponseSigned = fields.BooleanField(required=False)
|
||||
signMetadata = fields.BooleanField(required=False)
|
||||
wantMessagesSigned = fields.BooleanField(required=False)
|
||||
wantAssertionsSigned = fields.BooleanField(required=False)
|
||||
wantAssertionsEncrypted = fields.BooleanField(required=False)
|
||||
wantNameId = fields.BooleanField(required=False)
|
||||
wantNameIdEncrypted = fields.BooleanField(required=False)
|
||||
wantAttributeStatement = fields.BooleanField(required=False)
|
||||
requestedAuthnContext = fields.StringListBooleanField(required=False)
|
||||
requestedAuthnContextComparison = fields.CharField(required=False)
|
||||
metadataValidUntil = fields.CharField(allow_null=True, required=False)
|
||||
metadataCacheDuration = fields.CharField(allow_null=True, required=False)
|
||||
signatureAlgorithm = fields.CharField(allow_null=True, required=False)
|
||||
digestAlgorithm = fields.CharField(allow_null=True, required=False)
|
||||
|
||||
|
||||
class SAMLOrgAttrField(HybridDictField):
|
||||
|
||||
remove = fields.BooleanField(required=False)
|
||||
saml_attr = fields.CharField(required=False, allow_null=True)
|
||||
remove_admins = fields.BooleanField(required=False)
|
||||
saml_admin_attr = fields.CharField(required=False, allow_null=True)
|
||||
remove_auditors = fields.BooleanField(required=False)
|
||||
saml_auditor_attr = fields.CharField(required=False, allow_null=True)
|
||||
|
||||
child = _Forbidden()
|
||||
|
||||
|
||||
class SAMLTeamAttrTeamOrgMapField(HybridDictField):
|
||||
|
||||
team = fields.CharField(required=True, allow_null=False)
|
||||
team_alias = fields.CharField(required=False, allow_null=True)
|
||||
organization = fields.CharField(required=True, allow_null=False)
|
||||
organization_alias = fields.CharField(required=False, allow_null=True)
|
||||
|
||||
child = _Forbidden()
|
||||
|
||||
|
||||
class SAMLTeamAttrField(HybridDictField):
|
||||
|
||||
team_org_map = fields.ListField(required=False, child=SAMLTeamAttrTeamOrgMapField(), allow_null=True)
|
||||
remove = fields.BooleanField(required=False)
|
||||
saml_attr = fields.CharField(required=False, allow_null=True)
|
||||
|
||||
child = _Forbidden()
|
||||
@@ -0,0 +1,75 @@
|
||||
# Copyright (c) 2018 Ansible by Red Hat
|
||||
# All Rights Reserved.
|
||||
|
||||
# Python
|
||||
import ldap
|
||||
|
||||
# Django
|
||||
from django.utils.encoding import force_str
|
||||
|
||||
# 3rd party
|
||||
from django_auth_ldap.config import LDAPGroupType
|
||||
|
||||
|
||||
class PosixUIDGroupType(LDAPGroupType):
|
||||
|
||||
def __init__(self, name_attr='cn', ldap_group_user_attr='uid'):
|
||||
self.ldap_group_user_attr = ldap_group_user_attr
|
||||
super(PosixUIDGroupType, self).__init__(name_attr)
|
||||
|
||||
"""
|
||||
An LDAPGroupType subclass that handles non-standard DS.
|
||||
"""
|
||||
def user_groups(self, ldap_user, group_search):
|
||||
"""
|
||||
Searches for any group that is either the user's primary or contains the
|
||||
user as a member.
|
||||
"""
|
||||
groups = []
|
||||
|
||||
try:
|
||||
user_uid = ldap_user.attrs[self.ldap_group_user_attr][0]
|
||||
|
||||
if 'gidNumber' in ldap_user.attrs:
|
||||
user_gid = ldap_user.attrs['gidNumber'][0]
|
||||
filterstr = u'(|(gidNumber=%s)(memberUid=%s))' % (
|
||||
self.ldap.filter.escape_filter_chars(user_gid),
|
||||
self.ldap.filter.escape_filter_chars(user_uid)
|
||||
)
|
||||
else:
|
||||
filterstr = u'(memberUid=%s)' % (
|
||||
self.ldap.filter.escape_filter_chars(user_uid),
|
||||
)
|
||||
|
||||
search = group_search.search_with_additional_term_string(filterstr)
|
||||
search.attrlist = [str(self.name_attr)]
|
||||
groups = search.execute(ldap_user.connection)
|
||||
except (KeyError, IndexError):
|
||||
pass
|
||||
|
||||
return groups
|
||||
|
||||
def is_member(self, ldap_user, group_dn):
|
||||
"""
|
||||
Returns True if the group is the user's primary group or if the user is
|
||||
listed in the group's memberUid attribute.
|
||||
"""
|
||||
is_member = False
|
||||
try:
|
||||
user_uid = ldap_user.attrs[self.ldap_group_user_attr][0]
|
||||
|
||||
try:
|
||||
is_member = ldap_user.connection.compare_s(force_str(group_dn), 'memberUid', force_str(user_uid))
|
||||
except (ldap.UNDEFINED_TYPE, ldap.NO_SUCH_ATTRIBUTE):
|
||||
is_member = False
|
||||
|
||||
if not is_member:
|
||||
try:
|
||||
user_gid = ldap_user.attrs['gidNumber'][0]
|
||||
is_member = ldap_user.connection.compare_s(force_str(group_dn), 'gidNumber', force_str(user_gid))
|
||||
except (ldap.UNDEFINED_TYPE, ldap.NO_SUCH_ATTRIBUTE):
|
||||
is_member = False
|
||||
except (KeyError, IndexError):
|
||||
is_member = False
|
||||
|
||||
return is_member
|
||||
@@ -0,0 +1,81 @@
|
||||
# Copyright (c) 2015 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
|
||||
# Python
|
||||
import urllib.parse
|
||||
|
||||
# Django
|
||||
from django.conf import settings
|
||||
from django.utils.functional import LazyObject
|
||||
from django.shortcuts import redirect
|
||||
|
||||
# Python Social Auth
|
||||
from social_core.exceptions import SocialAuthBaseException
|
||||
from social_core.utils import social_logger
|
||||
from social_django import utils
|
||||
from social_django.middleware import SocialAuthExceptionMiddleware
|
||||
|
||||
|
||||
class SocialAuthMiddleware(SocialAuthExceptionMiddleware):
|
||||
|
||||
def process_request(self, request):
|
||||
if request.path.startswith('/sso'):
|
||||
# See upgrade blocker note in requirements/README.md
|
||||
utils.BACKENDS = settings.AUTHENTICATION_BACKENDS
|
||||
token_key = request.COOKIES.get('token', '')
|
||||
token_key = urllib.parse.quote(urllib.parse.unquote(token_key).strip('"'))
|
||||
|
||||
if not hasattr(request, 'successful_authenticator'):
|
||||
request.successful_authenticator = None
|
||||
|
||||
if not request.path.startswith('/sso/') and 'migrations_notran' not in request.path:
|
||||
if request.user and request.user.is_authenticated:
|
||||
# The rest of the code base rely hevily on type/inheritance checks,
|
||||
# LazyObject sent from Django auth middleware can be buggy if not
|
||||
# converted back to its original object.
|
||||
if isinstance(request.user, LazyObject) and request.user._wrapped:
|
||||
request.user = request.user._wrapped
|
||||
request.session.pop('social_auth_error', None)
|
||||
request.session.pop('social_auth_last_backend', None)
|
||||
return self.get_response(request)
|
||||
|
||||
def process_view(self, request, callback, callback_args, callback_kwargs):
|
||||
if request.path.startswith('/sso/login/'):
|
||||
request.session['social_auth_last_backend'] = callback_kwargs['backend']
|
||||
|
||||
def process_exception(self, request, exception):
|
||||
strategy = getattr(request, 'social_strategy', None)
|
||||
if strategy is None or self.raise_exception(request, exception):
|
||||
return
|
||||
|
||||
if isinstance(exception, SocialAuthBaseException) or request.path.startswith('/sso/'):
|
||||
backend = getattr(request, 'backend', None)
|
||||
backend_name = getattr(backend, 'name', 'unknown-backend')
|
||||
|
||||
message = self.get_message(request, exception)
|
||||
if request.session.get('social_auth_last_backend') != backend_name:
|
||||
backend_name = request.session.get('social_auth_last_backend')
|
||||
message = request.GET.get('error_description', message)
|
||||
|
||||
full_backend_name = backend_name
|
||||
try:
|
||||
idp_name = strategy.request_data()['RelayState']
|
||||
full_backend_name = '%s:%s' % (backend_name, idp_name)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
social_logger.error(message)
|
||||
|
||||
url = self.get_redirect_uri(request, exception)
|
||||
request.session['social_auth_error'] = (full_backend_name, message)
|
||||
return redirect(url)
|
||||
|
||||
def get_message(self, request, exception):
|
||||
msg = str(exception)
|
||||
if msg and msg[-1] not in '.?!':
|
||||
msg = msg + '.'
|
||||
return msg
|
||||
|
||||
def get_redirect_uri(self, request, exception):
|
||||
strategy = getattr(request, 'social_strategy', None)
|
||||
return strategy.session_get('next', '') or strategy.setting('LOGIN_ERROR_URL')
|
||||
@@ -0,0 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserEnterpriseAuth',
|
||||
fields=[
|
||||
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
|
||||
('provider', models.CharField(max_length=32, choices=[(b'radius', 'RADIUS'), (b'tacacs+', 'TACACS+')])),
|
||||
('user', models.ForeignKey(related_name='enterprise_auth', on_delete=models.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.AlterUniqueTogether(
|
||||
name='userenterpriseauth',
|
||||
unique_together=set([('user', 'provider')]),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('sso', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='userenterpriseauth',
|
||||
name='provider',
|
||||
field=models.CharField(max_length=32, choices=[('radius', 'RADIUS'), ('tacacs+', 'TACACS+'), ('saml', 'SAML')]),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
# Copyright (c) 2015 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
|
||||
# Django
|
||||
from django.db import models
|
||||
from django.contrib.auth.models import User
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
|
||||
class UserEnterpriseAuth(models.Model):
|
||||
"""Tower Enterprise Auth association model"""
|
||||
|
||||
PROVIDER_CHOICES = (
|
||||
('radius', _('RADIUS')),
|
||||
('tacacs+', _('TACACS+')),
|
||||
('saml', _('SAML')),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
unique_together = ('user', 'provider')
|
||||
|
||||
user = models.ForeignKey(
|
||||
User, related_name='enterprise_auth', on_delete=models.CASCADE
|
||||
)
|
||||
provider = models.CharField(
|
||||
max_length=32, choices=PROVIDER_CHOICES
|
||||
)
|
||||
@@ -0,0 +1,234 @@
|
||||
# Copyright (c) 2015 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
|
||||
# Python
|
||||
import re
|
||||
import logging
|
||||
|
||||
|
||||
# Python Social Auth
|
||||
from social_core.exceptions import AuthException
|
||||
|
||||
# Django
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
logger = logging.getLogger('awx.sso.pipeline')
|
||||
|
||||
|
||||
class AuthNotFound(AuthException):
|
||||
|
||||
def __init__(self, backend, email_or_uid, *args, **kwargs):
|
||||
self.email_or_uid = email_or_uid
|
||||
super(AuthNotFound, self).__init__(backend, *args, **kwargs)
|
||||
|
||||
def __str__(self):
|
||||
return _('An account cannot be found for {0}').format(self.email_or_uid)
|
||||
|
||||
|
||||
class AuthInactive(AuthException):
|
||||
|
||||
def __str__(self):
|
||||
return _('Your account is inactive')
|
||||
|
||||
|
||||
def check_user_found_or_created(backend, details, user=None, *args, **kwargs):
|
||||
if not user:
|
||||
email_or_uid = details.get('email') or kwargs.get('email') or kwargs.get('uid') or '???'
|
||||
raise AuthNotFound(backend, email_or_uid)
|
||||
|
||||
|
||||
def set_is_active_for_new_user(strategy, details, user=None, *args, **kwargs):
|
||||
if kwargs.get('is_new', False):
|
||||
details['is_active'] = True
|
||||
return {'details': details}
|
||||
|
||||
|
||||
def prevent_inactive_login(backend, details, user=None, *args, **kwargs):
|
||||
if user and not user.is_active:
|
||||
raise AuthInactive(backend)
|
||||
|
||||
|
||||
def _update_m2m_from_expression(user, related, expr, remove=True):
|
||||
'''
|
||||
Helper function to update m2m relationship based on user matching one or
|
||||
more expressions.
|
||||
'''
|
||||
should_add = False
|
||||
if expr is None:
|
||||
return
|
||||
elif not expr:
|
||||
pass
|
||||
elif expr is True:
|
||||
should_add = True
|
||||
else:
|
||||
if isinstance(expr, (str, type(re.compile('')))):
|
||||
expr = [expr]
|
||||
for ex in expr:
|
||||
if isinstance(ex, str):
|
||||
if user.username == ex or user.email == ex:
|
||||
should_add = True
|
||||
elif isinstance(ex, type(re.compile(''))):
|
||||
if ex.match(user.username) or ex.match(user.email):
|
||||
should_add = True
|
||||
if should_add:
|
||||
related.add(user)
|
||||
elif remove:
|
||||
related.remove(user)
|
||||
|
||||
|
||||
def _update_org_from_attr(user, related, attr, remove, remove_admins, remove_auditors):
|
||||
from awx.main.models import Organization
|
||||
from django.conf import settings
|
||||
|
||||
org_ids = []
|
||||
|
||||
for org_name in attr:
|
||||
try:
|
||||
if settings.SAML_AUTO_CREATE_OBJECTS:
|
||||
org = Organization.objects.get_or_create(name=org_name)[0]
|
||||
else:
|
||||
org = Organization.objects.get(name=org_name)
|
||||
except ObjectDoesNotExist:
|
||||
continue
|
||||
|
||||
org_ids.append(org.id)
|
||||
getattr(org, related).members.add(user)
|
||||
|
||||
if remove:
|
||||
[o.member_role.members.remove(user) for o in
|
||||
Organization.objects.filter(Q(member_role__members=user) & ~Q(id__in=org_ids))]
|
||||
|
||||
if remove_admins:
|
||||
[o.admin_role.members.remove(user) for o in
|
||||
Organization.objects.filter(Q(admin_role__members=user) & ~Q(id__in=org_ids))]
|
||||
|
||||
if remove_auditors:
|
||||
[o.auditor_role.members.remove(user) for o in
|
||||
Organization.objects.filter(Q(auditor_role__members=user) & ~Q(id__in=org_ids))]
|
||||
|
||||
|
||||
def update_user_orgs(backend, details, user=None, *args, **kwargs):
|
||||
'''
|
||||
Update organization memberships for the given user based on mapping rules
|
||||
defined in settings.
|
||||
'''
|
||||
if not user:
|
||||
return
|
||||
from awx.main.models import Organization
|
||||
org_map = backend.setting('ORGANIZATION_MAP') or {}
|
||||
for org_name, org_opts in org_map.items():
|
||||
org = Organization.objects.get_or_create(name=org_name)[0]
|
||||
|
||||
|
||||
# Update org admins from expression(s).
|
||||
remove = bool(org_opts.get('remove', True))
|
||||
admins_expr = org_opts.get('admins', None)
|
||||
remove_admins = bool(org_opts.get('remove_admins', remove))
|
||||
_update_m2m_from_expression(user, org.admin_role.members, admins_expr, remove_admins)
|
||||
|
||||
# Update org users from expression(s).
|
||||
users_expr = org_opts.get('users', None)
|
||||
remove_users = bool(org_opts.get('remove_users', remove))
|
||||
_update_m2m_from_expression(user, org.member_role.members, users_expr, remove_users)
|
||||
|
||||
|
||||
def update_user_teams(backend, details, user=None, *args, **kwargs):
|
||||
'''
|
||||
Update team memberships for the given user based on mapping rules defined
|
||||
in settings.
|
||||
'''
|
||||
if not user:
|
||||
return
|
||||
from awx.main.models import Organization, Team
|
||||
team_map = backend.setting('TEAM_MAP') or {}
|
||||
for team_name, team_opts in team_map.items():
|
||||
# Get or create the org to update.
|
||||
if 'organization' not in team_opts:
|
||||
continue
|
||||
org = Organization.objects.get_or_create(name=team_opts['organization'])[0]
|
||||
|
||||
|
||||
# Update team members from expression(s).
|
||||
team = Team.objects.get_or_create(name=team_name, organization=org)[0]
|
||||
users_expr = team_opts.get('users', None)
|
||||
remove = bool(team_opts.get('remove', True))
|
||||
_update_m2m_from_expression(user, team.member_role.members, users_expr, remove)
|
||||
|
||||
|
||||
def update_user_orgs_by_saml_attr(backend, details, user=None, *args, **kwargs):
|
||||
if not user:
|
||||
return
|
||||
from django.conf import settings
|
||||
org_map = settings.SOCIAL_AUTH_SAML_ORGANIZATION_ATTR
|
||||
if org_map.get('saml_attr') is None and org_map.get('saml_admin_attr') is None and org_map.get('saml_auditor_attr') is None:
|
||||
return
|
||||
|
||||
remove = bool(org_map.get('remove', True))
|
||||
remove_admins = bool(org_map.get('remove_admins', True))
|
||||
remove_auditors = bool(org_map.get('remove_auditors', True))
|
||||
|
||||
attr_values = kwargs.get('response', {}).get('attributes', {}).get(org_map.get('saml_attr'), [])
|
||||
attr_admin_values = kwargs.get('response', {}).get('attributes', {}).get(org_map.get('saml_admin_attr'), [])
|
||||
attr_auditor_values = kwargs.get('response', {}).get('attributes', {}).get(org_map.get('saml_auditor_attr'), [])
|
||||
|
||||
_update_org_from_attr(user, "member_role", attr_values, remove, False, False)
|
||||
_update_org_from_attr(user, "admin_role", attr_admin_values, False, remove_admins, False)
|
||||
_update_org_from_attr(user, "auditor_role", attr_auditor_values, False, False, remove_auditors)
|
||||
|
||||
|
||||
def update_user_teams_by_saml_attr(backend, details, user=None, *args, **kwargs):
|
||||
if not user:
|
||||
return
|
||||
from awx.main.models import Organization, Team
|
||||
from django.conf import settings
|
||||
team_map = settings.SOCIAL_AUTH_SAML_TEAM_ATTR
|
||||
if team_map.get('saml_attr') is None:
|
||||
return
|
||||
|
||||
saml_team_names = set(kwargs
|
||||
.get('response', {})
|
||||
.get('attributes', {})
|
||||
.get(team_map['saml_attr'], []))
|
||||
|
||||
team_ids = []
|
||||
for team_name_map in team_map.get('team_org_map', []):
|
||||
team_name = team_name_map.get('team', None)
|
||||
team_alias = team_name_map.get('team_alias', None)
|
||||
organization_name = team_name_map.get('organization', None)
|
||||
organization_alias = team_name_map.get('organization_alias', None)
|
||||
if team_name in saml_team_names:
|
||||
if not organization_name:
|
||||
# Settings field validation should prevent this.
|
||||
logger.error("organization name invalid for team {}".format(team_name))
|
||||
continue
|
||||
|
||||
if organization_alias:
|
||||
organization_name = organization_alias
|
||||
|
||||
try:
|
||||
if settings.SAML_AUTO_CREATE_OBJECTS:
|
||||
org = Organization.objects.get_or_create(name=organization_name)[0]
|
||||
else:
|
||||
org = Organization.objects.get(name=organization_name)
|
||||
except ObjectDoesNotExist:
|
||||
continue
|
||||
|
||||
if team_alias:
|
||||
team_name = team_alias
|
||||
try:
|
||||
if settings.SAML_AUTO_CREATE_OBJECTS:
|
||||
team = Team.objects.get_or_create(name=team_name, organization=org)[0]
|
||||
else:
|
||||
team = Team.objects.get(name=team_name, organization=org)
|
||||
except ObjectDoesNotExist:
|
||||
continue
|
||||
|
||||
team_ids.append(team.id)
|
||||
team.member_role.members.add(user)
|
||||
|
||||
if team_map.get('remove', True):
|
||||
[t.member_role.members.remove(user) for t in
|
||||
Team.objects.filter(Q(member_role__members=user) & ~Q(id__in=team_ids))]
|
||||
@@ -0,0 +1,34 @@
|
||||
import pytest
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
from awx.sso.backends import TACACSPlusBackend
|
||||
from awx.sso.models import UserEnterpriseAuth
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tacacsplus_backend():
|
||||
return TACACSPlusBackend()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def existing_normal_user():
|
||||
try:
|
||||
user = User.objects.get(username="alice")
|
||||
except User.DoesNotExist:
|
||||
user = User(username="alice", password="password")
|
||||
user.save()
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def existing_tacacsplus_user():
|
||||
try:
|
||||
user = User.objects.get(username="foo")
|
||||
except User.DoesNotExist:
|
||||
user = User(username="foo")
|
||||
user.set_unusable_password()
|
||||
user.save()
|
||||
enterprise_auth = UserEnterpriseAuth(user=user, provider='tacacs+')
|
||||
enterprise_auth.save()
|
||||
return user
|
||||
@@ -0,0 +1,41 @@
|
||||
# Python
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
# Tower
|
||||
from awx.sso.backends import _get_or_set_enterprise_user
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_fetch_user_if_exist(existing_tacacsplus_user):
|
||||
with mock.patch('awx.sso.backends.logger') as mocked_logger:
|
||||
new_user = _get_or_set_enterprise_user("foo", "password", "tacacs+")
|
||||
mocked_logger.debug.assert_not_called()
|
||||
mocked_logger.warn.assert_not_called()
|
||||
assert new_user == existing_tacacsplus_user
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_create_user_if_not_exist(existing_tacacsplus_user):
|
||||
with mock.patch('awx.sso.backends.logger') as mocked_logger:
|
||||
new_user = _get_or_set_enterprise_user("bar", "password", "tacacs+")
|
||||
mocked_logger.debug.assert_called_once_with(
|
||||
u'Created enterprise user bar via TACACS+ backend.'
|
||||
)
|
||||
assert new_user != existing_tacacsplus_user
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_created_user_has_no_usable_password():
|
||||
new_user = _get_or_set_enterprise_user("bar", "password", "tacacs+")
|
||||
assert not new_user.has_usable_password()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_non_enterprise_user_does_not_get_pass(existing_normal_user):
|
||||
with mock.patch('awx.sso.backends.logger') as mocked_logger:
|
||||
new_user = _get_or_set_enterprise_user("alice", "password", "tacacs+")
|
||||
mocked_logger.warn.assert_called_once_with(
|
||||
u'Enterprise user alice already defined in Tower.'
|
||||
)
|
||||
assert new_user is None
|
||||
@@ -0,0 +1,24 @@
|
||||
from django.test.utils import override_settings
|
||||
import ldap
|
||||
import pytest
|
||||
|
||||
from awx.sso.backends import LDAPSettings
|
||||
|
||||
|
||||
@override_settings(AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_NETWORK_TIMEOUT: 60})
|
||||
@pytest.mark.django_db
|
||||
def test_ldap_with_custom_timeout():
|
||||
settings = LDAPSettings()
|
||||
assert settings.CONNECTION_OPTIONS == {
|
||||
ldap.OPT_NETWORK_TIMEOUT: 60
|
||||
}
|
||||
|
||||
|
||||
@override_settings(AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0})
|
||||
@pytest.mark.django_db
|
||||
def test_ldap_with_missing_timeout():
|
||||
settings = LDAPSettings()
|
||||
assert settings.CONNECTION_OPTIONS == {
|
||||
ldap.OPT_REFERRALS: 0,
|
||||
ldap.OPT_NETWORK_TIMEOUT: 30
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
|
||||
import pytest
|
||||
import re
|
||||
from unittest import mock
|
||||
|
||||
from awx.sso.pipeline import (
|
||||
update_user_orgs,
|
||||
update_user_teams,
|
||||
update_user_orgs_by_saml_attr,
|
||||
update_user_teams_by_saml_attr,
|
||||
)
|
||||
|
||||
from awx.main.models import (
|
||||
User,
|
||||
Team,
|
||||
Organization
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def users():
|
||||
u1 = User.objects.create(username='user1@foo.com', last_name='foo', first_name='bar', email='user1@foo.com')
|
||||
u2 = User.objects.create(username='user2@foo.com', last_name='foo', first_name='bar', email='user2@foo.com')
|
||||
u3 = User.objects.create(username='user3@foo.com', last_name='foo', first_name='bar', email='user3@foo.com')
|
||||
return (u1, u2, u3)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSAMLMap():
|
||||
|
||||
@pytest.fixture
|
||||
def backend(self):
|
||||
class Backend:
|
||||
s = {
|
||||
'ORGANIZATION_MAP': {
|
||||
'Default': {
|
||||
'remove': True,
|
||||
'admins': 'foobar',
|
||||
'remove_admins': True,
|
||||
'users': 'foo',
|
||||
'remove_users': True,
|
||||
}
|
||||
},
|
||||
'TEAM_MAP': {
|
||||
'Blue': {
|
||||
'organization': 'Default',
|
||||
'remove': True,
|
||||
'users': '',
|
||||
},
|
||||
'Red': {
|
||||
'organization': 'Default',
|
||||
'remove': True,
|
||||
'users': '',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def setting(self, key):
|
||||
return self.s[key]
|
||||
|
||||
return Backend()
|
||||
|
||||
@pytest.fixture
|
||||
def org(self):
|
||||
return Organization.objects.create(name="Default")
|
||||
|
||||
def test_update_user_orgs(self, org, backend, users):
|
||||
u1, u2, u3 = users
|
||||
|
||||
# Test user membership logic with regular expressions
|
||||
backend.setting('ORGANIZATION_MAP')['Default']['admins'] = re.compile('.*')
|
||||
backend.setting('ORGANIZATION_MAP')['Default']['users'] = re.compile('.*')
|
||||
|
||||
update_user_orgs(backend, None, u1)
|
||||
update_user_orgs(backend, None, u2)
|
||||
update_user_orgs(backend, None, u3)
|
||||
|
||||
assert org.admin_role.members.count() == 3
|
||||
assert org.member_role.members.count() == 3
|
||||
|
||||
# Test remove feature enabled
|
||||
backend.setting('ORGANIZATION_MAP')['Default']['admins'] = ''
|
||||
backend.setting('ORGANIZATION_MAP')['Default']['users'] = ''
|
||||
backend.setting('ORGANIZATION_MAP')['Default']['remove_admins'] = True
|
||||
backend.setting('ORGANIZATION_MAP')['Default']['remove_users'] = True
|
||||
update_user_orgs(backend, None, u1)
|
||||
|
||||
assert org.admin_role.members.count() == 2
|
||||
assert org.member_role.members.count() == 2
|
||||
|
||||
# Test remove feature disabled
|
||||
backend.setting('ORGANIZATION_MAP')['Default']['remove_admins'] = False
|
||||
backend.setting('ORGANIZATION_MAP')['Default']['remove_users'] = False
|
||||
update_user_orgs(backend, None, u2)
|
||||
|
||||
assert org.admin_role.members.count() == 2
|
||||
assert org.member_role.members.count() == 2
|
||||
|
||||
def test_update_user_teams(self, backend, users):
|
||||
u1, u2, u3 = users
|
||||
|
||||
# Test user membership logic with regular expressions
|
||||
backend.setting('TEAM_MAP')['Blue']['users'] = re.compile('.*')
|
||||
backend.setting('TEAM_MAP')['Red']['users'] = re.compile('.*')
|
||||
|
||||
update_user_teams(backend, None, u1)
|
||||
update_user_teams(backend, None, u2)
|
||||
update_user_teams(backend, None, u3)
|
||||
|
||||
assert Team.objects.get(name="Red").member_role.members.count() == 3
|
||||
assert Team.objects.get(name="Blue").member_role.members.count() == 3
|
||||
|
||||
# Test remove feature enabled
|
||||
backend.setting('TEAM_MAP')['Blue']['remove'] = True
|
||||
backend.setting('TEAM_MAP')['Red']['remove'] = True
|
||||
backend.setting('TEAM_MAP')['Blue']['users'] = ''
|
||||
backend.setting('TEAM_MAP')['Red']['users'] = ''
|
||||
|
||||
update_user_teams(backend, None, u1)
|
||||
|
||||
assert Team.objects.get(name="Red").member_role.members.count() == 2
|
||||
assert Team.objects.get(name="Blue").member_role.members.count() == 2
|
||||
|
||||
# Test remove feature disabled
|
||||
backend.setting('TEAM_MAP')['Blue']['remove'] = False
|
||||
backend.setting('TEAM_MAP')['Red']['remove'] = False
|
||||
|
||||
update_user_teams(backend, None, u2)
|
||||
|
||||
assert Team.objects.get(name="Red").member_role.members.count() == 2
|
||||
assert Team.objects.get(name="Blue").member_role.members.count() == 2
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestSAMLAttr():
|
||||
|
||||
@pytest.fixture
|
||||
def kwargs(self):
|
||||
return {
|
||||
'username': u'cmeyers@redhat.com',
|
||||
'uid': 'idp:cmeyers@redhat.com',
|
||||
'request': {
|
||||
u'SAMLResponse': [],
|
||||
u'RelayState': [u'idp']
|
||||
},
|
||||
'is_new': False,
|
||||
'response': {
|
||||
'session_index': '_0728f0e0-b766-0135-75fa-02842b07c044',
|
||||
'idp_name': u'idp',
|
||||
'attributes': {
|
||||
'memberOf': ['Default1', 'Default2'],
|
||||
'admins': ['Default3'],
|
||||
'auditors': ['Default4'],
|
||||
'groups': ['Blue', 'Red'],
|
||||
'User.email': ['cmeyers@redhat.com'],
|
||||
'User.LastName': ['Meyers'],
|
||||
'name_id': 'cmeyers@redhat.com',
|
||||
'User.FirstName': ['Chris'],
|
||||
'PersonImmutableID': []
|
||||
}
|
||||
},
|
||||
#'social': <UserSocialAuth: cmeyers@redhat.com>,
|
||||
'social': None,
|
||||
#'strategy': <awx.sso.strategies.django_strategy.AWXDjangoStrategy object at 0x8523a10>,
|
||||
'strategy': None,
|
||||
'new_association': False
|
||||
}
|
||||
|
||||
@pytest.fixture
|
||||
def orgs(self):
|
||||
o1 = Organization.objects.create(name='Default1')
|
||||
o2 = Organization.objects.create(name='Default2')
|
||||
o3 = Organization.objects.create(name='Default3')
|
||||
return (o1, o2, o3)
|
||||
|
||||
@pytest.fixture
|
||||
def mock_settings(self, request):
|
||||
fixture_args = request.node.get_closest_marker('fixture_args')
|
||||
if fixture_args and 'autocreate' in fixture_args.kwargs:
|
||||
autocreate = fixture_args.kwargs['autocreate']
|
||||
else:
|
||||
autocreate = True
|
||||
|
||||
class MockSettings():
|
||||
SAML_AUTO_CREATE_OBJECTS = autocreate
|
||||
SOCIAL_AUTH_SAML_ORGANIZATION_ATTR = {
|
||||
'saml_attr': 'memberOf',
|
||||
'saml_admin_attr': 'admins',
|
||||
'saml_auditor_attr': 'auditors',
|
||||
'remove': True,
|
||||
'remove_admins': True,
|
||||
}
|
||||
SOCIAL_AUTH_SAML_TEAM_ATTR = {
|
||||
'saml_attr': 'groups',
|
||||
'remove': True,
|
||||
'team_org_map': [
|
||||
{'team': 'Blue', 'organization': 'Default1'},
|
||||
{'team': 'Blue', 'organization': 'Default2'},
|
||||
{'team': 'Blue', 'organization': 'Default3'},
|
||||
{'team': 'Red', 'organization': 'Default1'},
|
||||
{'team': 'Green', 'organization': 'Default1'},
|
||||
{'team': 'Green', 'organization': 'Default3'},
|
||||
{
|
||||
'team': 'Yellow', 'team_alias': 'Yellow_Alias',
|
||||
'organization': 'Default4', 'organization_alias': 'Default4_Alias'
|
||||
},
|
||||
]
|
||||
}
|
||||
return MockSettings()
|
||||
|
||||
def test_update_user_orgs_by_saml_attr(self, orgs, users, kwargs, mock_settings):
|
||||
with mock.patch('django.conf.settings', mock_settings):
|
||||
o1, o2, o3 = orgs
|
||||
u1, u2, u3 = users
|
||||
|
||||
# Test getting orgs from attribute
|
||||
update_user_orgs_by_saml_attr(None, None, u1, **kwargs)
|
||||
update_user_orgs_by_saml_attr(None, None, u2, **kwargs)
|
||||
update_user_orgs_by_saml_attr(None, None, u3, **kwargs)
|
||||
|
||||
assert o1.member_role.members.count() == 3
|
||||
assert o2.member_role.members.count() == 3
|
||||
assert o3.member_role.members.count() == 0
|
||||
|
||||
# Test remove logic enabled
|
||||
kwargs['response']['attributes']['memberOf'] = ['Default3']
|
||||
|
||||
update_user_orgs_by_saml_attr(None, None, u1, **kwargs)
|
||||
|
||||
assert o1.member_role.members.count() == 2
|
||||
assert o2.member_role.members.count() == 2
|
||||
assert o3.member_role.members.count() == 1
|
||||
|
||||
# Test remove logic disabled
|
||||
mock_settings.SOCIAL_AUTH_SAML_ORGANIZATION_ATTR['remove'] = False
|
||||
kwargs['response']['attributes']['memberOf'] = ['Default1', 'Default2']
|
||||
|
||||
update_user_orgs_by_saml_attr(None, None, u1, **kwargs)
|
||||
|
||||
assert o1.member_role.members.count() == 3
|
||||
assert o2.member_role.members.count() == 3
|
||||
assert o3.member_role.members.count() == 1
|
||||
|
||||
def test_update_user_teams_by_saml_attr(self, orgs, users, kwargs, mock_settings):
|
||||
with mock.patch('django.conf.settings', mock_settings):
|
||||
o1, o2, o3 = orgs
|
||||
u1, u2, u3 = users
|
||||
|
||||
# Test getting teams from attribute with team->org mapping
|
||||
|
||||
kwargs['response']['attributes']['groups'] = ['Blue', 'Red', 'Green']
|
||||
|
||||
# Ensure basic functionality
|
||||
update_user_teams_by_saml_attr(None, None, u1, **kwargs)
|
||||
update_user_teams_by_saml_attr(None, None, u2, **kwargs)
|
||||
update_user_teams_by_saml_attr(None, None, u3, **kwargs)
|
||||
|
||||
assert Team.objects.get(name='Blue', organization__name='Default1').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Blue', organization__name='Default2').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Blue', organization__name='Default3').member_role.members.count() == 3
|
||||
|
||||
assert Team.objects.get(name='Red', organization__name='Default1').member_role.members.count() == 3
|
||||
|
||||
assert Team.objects.get(name='Green', organization__name='Default1').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Green', organization__name='Default3').member_role.members.count() == 3
|
||||
|
||||
# Test remove logic
|
||||
kwargs['response']['attributes']['groups'] = ['Green']
|
||||
update_user_teams_by_saml_attr(None, None, u1, **kwargs)
|
||||
update_user_teams_by_saml_attr(None, None, u2, **kwargs)
|
||||
update_user_teams_by_saml_attr(None, None, u3, **kwargs)
|
||||
|
||||
assert Team.objects.get(name='Blue', organization__name='Default1').member_role.members.count() == 0
|
||||
assert Team.objects.get(name='Blue', organization__name='Default2').member_role.members.count() == 0
|
||||
assert Team.objects.get(name='Blue', organization__name='Default3').member_role.members.count() == 0
|
||||
|
||||
assert Team.objects.get(name='Red', organization__name='Default1').member_role.members.count() == 0
|
||||
|
||||
assert Team.objects.get(name='Green', organization__name='Default1').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Green', organization__name='Default3').member_role.members.count() == 3
|
||||
|
||||
# Test remove logic disabled
|
||||
mock_settings.SOCIAL_AUTH_SAML_TEAM_ATTR['remove'] = False
|
||||
kwargs['response']['attributes']['groups'] = ['Blue']
|
||||
|
||||
update_user_teams_by_saml_attr(None, None, u1, **kwargs)
|
||||
update_user_teams_by_saml_attr(None, None, u2, **kwargs)
|
||||
update_user_teams_by_saml_attr(None, None, u3, **kwargs)
|
||||
|
||||
assert Team.objects.get(name='Blue', organization__name='Default1').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Blue', organization__name='Default2').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Blue', organization__name='Default3').member_role.members.count() == 3
|
||||
|
||||
assert Team.objects.get(name='Red', organization__name='Default1').member_role.members.count() == 0
|
||||
|
||||
assert Team.objects.get(name='Green', organization__name='Default1').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Green', organization__name='Default3').member_role.members.count() == 3
|
||||
|
||||
def test_update_user_teams_alias_by_saml_attr(self, orgs, users, kwargs, mock_settings):
|
||||
with mock.patch('django.conf.settings', mock_settings):
|
||||
u1 = users[0]
|
||||
|
||||
# Test getting teams from attribute with team->org mapping
|
||||
kwargs['response']['attributes']['groups'] = ['Yellow']
|
||||
|
||||
# Ensure team and org will be created
|
||||
update_user_teams_by_saml_attr(None, None, u1, **kwargs)
|
||||
|
||||
assert Team.objects.filter(name='Yellow', organization__name='Default4').count() == 0
|
||||
assert Team.objects.filter(name='Yellow_Alias', organization__name='Default4_Alias').count() == 1
|
||||
assert Team.objects.get(
|
||||
name='Yellow_Alias', organization__name='Default4_Alias').member_role.members.count() == 1
|
||||
|
||||
@pytest.mark.fixture_args(autocreate=False)
|
||||
def test_autocreate_disabled(self, users, kwargs, mock_settings):
|
||||
kwargs['response']['attributes']['memberOf'] = ['Default1', 'Default2', 'Default3']
|
||||
kwargs['response']['attributes']['groups'] = ['Blue', 'Red', 'Green']
|
||||
with mock.patch('django.conf.settings', mock_settings):
|
||||
for u in users:
|
||||
update_user_orgs_by_saml_attr(None, None, u, **kwargs)
|
||||
update_user_teams_by_saml_attr(None, None, u, **kwargs)
|
||||
assert Organization.objects.count() == 0
|
||||
assert Team.objects.count() == 0
|
||||
|
||||
# precreate everything
|
||||
o1 = Organization.objects.create(name='Default1')
|
||||
o2 = Organization.objects.create(name='Default2')
|
||||
o3 = Organization.objects.create(name='Default3')
|
||||
Team.objects.create(name='Blue', organization_id=o1.id)
|
||||
Team.objects.create(name='Blue', organization_id=o2.id)
|
||||
Team.objects.create(name='Blue', organization_id=o3.id)
|
||||
Team.objects.create(name='Red', organization_id=o1.id)
|
||||
Team.objects.create(name='Green', organization_id=o1.id)
|
||||
Team.objects.create(name='Green', organization_id=o3.id)
|
||||
|
||||
for u in users:
|
||||
update_user_orgs_by_saml_attr(None, None, u, **kwargs)
|
||||
update_user_teams_by_saml_attr(None, None, u, **kwargs)
|
||||
|
||||
assert o1.member_role.members.count() == 3
|
||||
assert o2.member_role.members.count() == 3
|
||||
assert o3.member_role.members.count() == 3
|
||||
|
||||
assert Team.objects.get(name='Blue', organization__name='Default1').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Blue', organization__name='Default2').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Blue', organization__name='Default3').member_role.members.count() == 3
|
||||
|
||||
assert Team.objects.get(name='Red', organization__name='Default1').member_role.members.count() == 3
|
||||
|
||||
assert Team.objects.get(name='Green', organization__name='Default1').member_role.members.count() == 3
|
||||
assert Team.objects.get(name='Green', organization__name='Default3').member_role.members.count() == 3
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
|
||||
# Ensure that our autouse overwrites are working
|
||||
def test_cache(settings):
|
||||
assert settings.CACHES['default']['BACKEND'] == 'django.core.cache.backends.locmem.LocMemCache'
|
||||
assert settings.CACHES['default']['LOCATION'].startswith('unique-')
|
||||
@@ -0,0 +1,142 @@
|
||||
|
||||
import pytest
|
||||
from unittest import mock
|
||||
|
||||
from rest_framework.exceptions import ValidationError
|
||||
|
||||
from awx.sso.fields import (
|
||||
SAMLOrgAttrField,
|
||||
SAMLTeamAttrField,
|
||||
LDAPGroupTypeParamsField,
|
||||
LDAPServerURIField
|
||||
)
|
||||
|
||||
|
||||
class TestSAMLOrgAttrField():
|
||||
|
||||
@pytest.mark.parametrize("data, expected", [
|
||||
({}, {}),
|
||||
({'remove': True, 'saml_attr': 'foobar'}, {'remove': True, 'saml_attr': 'foobar'}),
|
||||
({'remove': True, 'saml_attr': 1234}, {'remove': True, 'saml_attr': '1234'}),
|
||||
({'remove': True, 'saml_attr': 3.14}, {'remove': True, 'saml_attr': '3.14'}),
|
||||
({'saml_attr': 'foobar'}, {'saml_attr': 'foobar'}),
|
||||
({'remove': True}, {'remove': True}),
|
||||
({'remove': True, 'saml_admin_attr': 'foobar'}, {'remove': True, 'saml_admin_attr': 'foobar'}),
|
||||
({'saml_admin_attr': 'foobar'}, {'saml_admin_attr': 'foobar'}),
|
||||
({'remove_admins': True, 'saml_admin_attr': 'foobar'}, {'remove_admins': True, 'saml_admin_attr': 'foobar'}),
|
||||
({'remove': True, 'saml_attr': 'foo', 'remove_admins': True, 'saml_admin_attr': 'bar'},
|
||||
{'remove': True, 'saml_attr': 'foo', 'remove_admins': True, 'saml_admin_attr': 'bar'}),
|
||||
])
|
||||
def test_internal_value_valid(self, data, expected):
|
||||
field = SAMLOrgAttrField()
|
||||
res = field.to_internal_value(data)
|
||||
assert res == expected
|
||||
|
||||
@pytest.mark.parametrize("data, expected", [
|
||||
({'remove': 'blah', 'saml_attr': 'foobar'},
|
||||
{'remove': ['Must be a valid boolean.']}),
|
||||
({'remove': True, 'saml_attr': False},
|
||||
{'saml_attr': ['Not a valid string.']}),
|
||||
({'remove': True, 'saml_attr': False, 'foo': 'bar', 'gig': 'ity'},
|
||||
{'saml_attr': ['Not a valid string.'],
|
||||
'foo': ['Invalid field.'],
|
||||
'gig': ['Invalid field.']}),
|
||||
({'remove_admins': True, 'saml_admin_attr': False},
|
||||
{'saml_admin_attr': ['Not a valid string.']}),
|
||||
({'remove_admins': 'blah', 'saml_admin_attr': 'foobar'},
|
||||
{'remove_admins': ['Must be a valid boolean.']}),
|
||||
])
|
||||
def test_internal_value_invalid(self, data, expected):
|
||||
field = SAMLOrgAttrField()
|
||||
with pytest.raises(ValidationError) as e:
|
||||
field.to_internal_value(data)
|
||||
assert e.value.detail == expected
|
||||
|
||||
|
||||
class TestSAMLTeamAttrField():
|
||||
|
||||
@pytest.mark.parametrize("data", [
|
||||
{},
|
||||
{'remove': True, 'saml_attr': 'foobar', 'team_org_map': []},
|
||||
{'remove': True, 'saml_attr': 'foobar', 'team_org_map': [
|
||||
{'team': 'Engineering', 'organization': 'Ansible'}
|
||||
]},
|
||||
{'remove': True, 'saml_attr': 'foobar', 'team_org_map': [
|
||||
{'team': 'Engineering', 'organization': 'Ansible'},
|
||||
{'team': 'Engineering', 'organization': 'Ansible2'},
|
||||
{'team': 'Engineering2', 'organization': 'Ansible'},
|
||||
]},
|
||||
{'remove': True, 'saml_attr': 'foobar', 'team_org_map': [
|
||||
{'team': 'Engineering', 'organization': 'Ansible'},
|
||||
{'team': 'Engineering', 'organization': 'Ansible2'},
|
||||
{'team': 'Engineering2', 'organization': 'Ansible'},
|
||||
]},
|
||||
{'remove': True, 'saml_attr': 'foobar', 'team_org_map': [
|
||||
{
|
||||
'team': 'Engineering', 'team_alias': 'Engineering Team',
|
||||
'organization': 'Ansible', 'organization_alias': 'Awesome Org'
|
||||
},
|
||||
{'team': 'Engineering', 'organization': 'Ansible2'},
|
||||
{'team': 'Engineering2', 'organization': 'Ansible'},
|
||||
]},
|
||||
])
|
||||
def test_internal_value_valid(self, data):
|
||||
field = SAMLTeamAttrField()
|
||||
res = field.to_internal_value(data)
|
||||
assert res == data
|
||||
|
||||
@pytest.mark.parametrize("data, expected", [
|
||||
({'remove': True, 'saml_attr': 'foobar', 'team_org_map': [
|
||||
{'team': 'foobar', 'not_a_valid_key': 'blah', 'organization': 'Ansible'},
|
||||
]}, {'team_org_map': {0: {'not_a_valid_key': ['Invalid field.']}}}),
|
||||
({'remove': False, 'saml_attr': 'foobar', 'team_org_map': [
|
||||
{'organization': 'Ansible'},
|
||||
]}, {'team_org_map': {0: {'team': ['This field is required.']}}}),
|
||||
({'remove': False, 'saml_attr': 'foobar', 'team_org_map': [
|
||||
{},
|
||||
]}, {'team_org_map': {
|
||||
0: {'organization': ['This field is required.'],
|
||||
'team': ['This field is required.']}}}),
|
||||
])
|
||||
def test_internal_value_invalid(self, data, expected):
|
||||
field = SAMLTeamAttrField()
|
||||
with pytest.raises(ValidationError) as e:
|
||||
field.to_internal_value(data)
|
||||
assert e.value.detail == expected
|
||||
|
||||
|
||||
class TestLDAPGroupTypeParamsField():
|
||||
|
||||
@pytest.mark.parametrize("group_type, data, expected", [
|
||||
('LDAPGroupType', {'name_attr': 'user', 'bob': ['a', 'b'], 'scooter': 'hello'},
|
||||
['Invalid key(s): "bob", "scooter".']),
|
||||
('MemberDNGroupType', {'name_attr': 'user', 'member_attr': 'west', 'bob': ['a', 'b'], 'scooter': 'hello'},
|
||||
['Invalid key(s): "bob", "scooter".']),
|
||||
('PosixUIDGroupType', {'name_attr': 'user', 'member_attr': 'west', 'ldap_group_user_attr': 'legacyThing',
|
||||
'bob': ['a', 'b'], 'scooter': 'hello'},
|
||||
['Invalid key(s): "bob", "member_attr", "scooter".']),
|
||||
])
|
||||
def test_internal_value_invalid(self, group_type, data, expected):
|
||||
field = LDAPGroupTypeParamsField()
|
||||
field.get_depends_on = mock.MagicMock(return_value=group_type)
|
||||
|
||||
with pytest.raises(ValidationError) as e:
|
||||
field.to_internal_value(data)
|
||||
assert e.value.detail == expected
|
||||
|
||||
|
||||
class TestLDAPServerURIField():
|
||||
|
||||
@pytest.mark.parametrize("ldap_uri, exception, expected", [
|
||||
(r'ldap://servername.com:444', None, r'ldap://servername.com:444'),
|
||||
(r'ldap://servername.so3:444', None, r'ldap://servername.so3:444'),
|
||||
(r'ldaps://servername3.s300:344', None, r'ldaps://servername3.s300:344'),
|
||||
(r'ldap://servername.-so3:444', ValidationError, None),
|
||||
])
|
||||
def test_run_validators_valid(self, ldap_uri, exception, expected):
|
||||
field = LDAPServerURIField()
|
||||
if exception is None:
|
||||
assert field.run_validators(ldap_uri) == expected
|
||||
else:
|
||||
with pytest.raises(exception):
|
||||
field.run_validators(ldap_uri)
|
||||
@@ -0,0 +1,25 @@
|
||||
import ldap
|
||||
|
||||
from awx.sso.backends import LDAPSettings
|
||||
from awx.sso.validators import validate_ldap_filter
|
||||
from django.core.cache import cache
|
||||
|
||||
|
||||
def test_ldap_default_settings(mocker):
|
||||
from_db = mocker.Mock(**{'order_by.return_value': []})
|
||||
with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=from_db):
|
||||
settings = LDAPSettings()
|
||||
assert settings.ORGANIZATION_MAP == {}
|
||||
assert settings.TEAM_MAP == {}
|
||||
|
||||
|
||||
def test_ldap_default_network_timeout(mocker):
|
||||
cache.clear() # clearing cache avoids picking up stray default for OPT_REFERRALS
|
||||
from_db = mocker.Mock(**{'order_by.return_value': []})
|
||||
with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=from_db):
|
||||
settings = LDAPSettings()
|
||||
assert settings.CONNECTION_OPTIONS[ldap.OPT_NETWORK_TIMEOUT] == 30
|
||||
|
||||
|
||||
def test_ldap_filter_validator():
|
||||
validate_ldap_filter('(test-uid=%(user)s)', with_user=True)
|
||||
@@ -0,0 +1,2 @@
|
||||
def test_module_loads():
|
||||
from awx.sso import pipeline # noqa
|
||||
@@ -0,0 +1,52 @@
|
||||
from unittest import mock
|
||||
|
||||
|
||||
def test_empty_host_fails_auth(tacacsplus_backend):
|
||||
with mock.patch('awx.sso.backends.django_settings') as settings:
|
||||
settings.TACACSPLUS_HOST = ''
|
||||
ret_user = tacacsplus_backend.authenticate(None, u"user", u"pass")
|
||||
assert ret_user is None
|
||||
|
||||
|
||||
def test_client_raises_exception(tacacsplus_backend):
|
||||
client = mock.MagicMock()
|
||||
client.authenticate.side_effect=Exception("foo")
|
||||
with mock.patch('awx.sso.backends.django_settings') as settings,\
|
||||
mock.patch('awx.sso.backends.logger') as logger,\
|
||||
mock.patch('tacacs_plus.TACACSClient', return_value=client):
|
||||
settings.TACACSPLUS_HOST = 'localhost'
|
||||
settings.TACACSPLUS_AUTH_PROTOCOL = 'ascii'
|
||||
ret_user = tacacsplus_backend.authenticate(None, u"user", u"pass")
|
||||
assert ret_user is None
|
||||
logger.exception.assert_called_once_with(
|
||||
"TACACS+ Authentication Error: foo"
|
||||
)
|
||||
|
||||
|
||||
def test_client_return_invalid_fails_auth(tacacsplus_backend):
|
||||
auth = mock.MagicMock()
|
||||
auth.valid = False
|
||||
client = mock.MagicMock()
|
||||
client.authenticate.return_value = auth
|
||||
with mock.patch('awx.sso.backends.django_settings') as settings,\
|
||||
mock.patch('tacacs_plus.TACACSClient', return_value=client):
|
||||
settings.TACACSPLUS_HOST = 'localhost'
|
||||
settings.TACACSPLUS_AUTH_PROTOCOL = 'ascii'
|
||||
ret_user = tacacsplus_backend.authenticate(None, u"user", u"pass")
|
||||
assert ret_user is None
|
||||
|
||||
|
||||
def test_client_return_valid_passes_auth(tacacsplus_backend):
|
||||
auth = mock.MagicMock()
|
||||
auth.valid = True
|
||||
client = mock.MagicMock()
|
||||
client.authenticate.return_value = auth
|
||||
user = mock.MagicMock()
|
||||
user.has_usable_password = mock.MagicMock(return_value=False)
|
||||
with mock.patch('awx.sso.backends.django_settings') as settings,\
|
||||
mock.patch('tacacs_plus.TACACSClient', return_value=client),\
|
||||
mock.patch('awx.sso.backends._get_or_set_enterprise_user', return_value=user):
|
||||
settings.TACACSPLUS_HOST = 'localhost'
|
||||
settings.TACACSPLUS_AUTH_PROTOCOL = 'ascii'
|
||||
ret_user = tacacsplus_backend.authenticate(None, u"user", u"pass")
|
||||
assert ret_user == user
|
||||
@@ -0,0 +1,19 @@
|
||||
# Copyright (c) 2015 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
|
||||
from django.conf.urls import url
|
||||
from awx.sso.views import (
|
||||
sso_complete,
|
||||
sso_error,
|
||||
sso_inactive,
|
||||
saml_metadata,
|
||||
)
|
||||
|
||||
|
||||
app_name = 'sso'
|
||||
urlpatterns = [
|
||||
url(r'^complete/$', sso_complete, name='sso_complete'),
|
||||
url(r'^error/$', sso_error, name='sso_error'),
|
||||
url(r'^inactive/$', sso_inactive, name='sso_inactive'),
|
||||
url(r'^metadata/saml/$', saml_metadata, name='saml_metadata'),
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
# Python
|
||||
import re
|
||||
|
||||
# Python-LDAP
|
||||
import ldap
|
||||
|
||||
# Django
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
__all__ = ['validate_ldap_dn', 'validate_ldap_dn_with_user',
|
||||
'validate_ldap_bind_dn', 'validate_ldap_filter',
|
||||
'validate_ldap_filter_with_user',
|
||||
'validate_tacacsplus_disallow_nonascii']
|
||||
|
||||
|
||||
def validate_ldap_dn(value, with_user=False):
|
||||
if with_user:
|
||||
if '%(user)s' not in value:
|
||||
raise ValidationError(_('DN must include "%%(user)s" placeholder for username: %s') % value)
|
||||
dn_value = value.replace('%(user)s', 'USER')
|
||||
else:
|
||||
dn_value = value
|
||||
try:
|
||||
ldap.dn.str2dn(dn_value.encode('utf-8'))
|
||||
except ldap.DECODING_ERROR:
|
||||
raise ValidationError(_('Invalid DN: %s') % value)
|
||||
|
||||
|
||||
def validate_ldap_dn_with_user(value):
|
||||
validate_ldap_dn(value, with_user=True)
|
||||
|
||||
|
||||
def validate_ldap_bind_dn(value):
|
||||
if not re.match(r'^[A-Za-z][A-Za-z0-9._-]*?\\[A-Za-z0-9 ._-]+?$', value.strip()) and \
|
||||
not re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', value.strip()):
|
||||
validate_ldap_dn(value)
|
||||
|
||||
|
||||
def validate_ldap_filter(value, with_user=False):
|
||||
value = value.strip()
|
||||
if not value:
|
||||
return
|
||||
if with_user:
|
||||
if '%(user)s' not in value:
|
||||
raise ValidationError(_('DN must include "%%(user)s" placeholder for username: %s') % value)
|
||||
dn_value = value.replace('%(user)s', 'USER')
|
||||
else:
|
||||
dn_value = value
|
||||
if re.match(r'^\([A-Za-z0-9-]+?=[^()]+?\)$', dn_value):
|
||||
return
|
||||
elif re.match(r'^\([&|!]\(.*?\)\)$', dn_value):
|
||||
try:
|
||||
map(validate_ldap_filter, ['(%s)' % x for x in dn_value[3:-2].split(')(')])
|
||||
return
|
||||
except ValidationError:
|
||||
pass
|
||||
raise ValidationError(_('Invalid filter: %s') % value)
|
||||
|
||||
|
||||
def validate_ldap_filter_with_user(value):
|
||||
validate_ldap_filter(value, with_user=True)
|
||||
|
||||
|
||||
def validate_tacacsplus_disallow_nonascii(value):
|
||||
try:
|
||||
value.encode('ascii')
|
||||
except (UnicodeEncodeError, UnicodeDecodeError):
|
||||
raise ValidationError(_('TACACS+ secret does not allow non-ascii characters'))
|
||||
@@ -0,0 +1,77 @@
|
||||
# Copyright (c) 2015 Ansible, Inc.
|
||||
# All Rights Reserved.
|
||||
|
||||
# Python
|
||||
import urllib.parse
|
||||
import logging
|
||||
|
||||
# Django
|
||||
from django.urls import reverse
|
||||
from django.http import HttpResponse
|
||||
from django.views.generic import View
|
||||
from django.views.generic.base import RedirectView
|
||||
from django.utils.encoding import smart_text
|
||||
from awx.api.serializers import UserSerializer
|
||||
from rest_framework.renderers import JSONRenderer
|
||||
from django.conf import settings
|
||||
|
||||
logger = logging.getLogger('awx.sso.views')
|
||||
|
||||
|
||||
class BaseRedirectView(RedirectView):
|
||||
|
||||
permanent = True
|
||||
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
last_path = self.request.COOKIES.get('lastPath', '')
|
||||
last_path = urllib.parse.quote(urllib.parse.unquote(last_path).strip('"'))
|
||||
url = reverse('ui_next:index')
|
||||
if last_path:
|
||||
return '%s#%s' % (url, last_path)
|
||||
else:
|
||||
return url
|
||||
|
||||
|
||||
sso_error = BaseRedirectView.as_view()
|
||||
sso_inactive = BaseRedirectView.as_view()
|
||||
|
||||
|
||||
class CompleteView(BaseRedirectView):
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
response = super(CompleteView, self).dispatch(request, *args, **kwargs)
|
||||
if self.request.user and self.request.user.is_authenticated:
|
||||
logger.info(smart_text(u"User {} logged in".format(self.request.user.username)))
|
||||
response.set_cookie('userLoggedIn', 'true')
|
||||
current_user = UserSerializer(self.request.user)
|
||||
current_user = smart_text(JSONRenderer().render(current_user.data))
|
||||
current_user = urllib.parse.quote('%s' % current_user, '')
|
||||
response.set_cookie('current_user', current_user, secure=settings.SESSION_COOKIE_SECURE or None)
|
||||
return response
|
||||
|
||||
|
||||
sso_complete = CompleteView.as_view()
|
||||
|
||||
|
||||
class MetadataView(View):
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
from social_django.utils import load_backend, load_strategy
|
||||
complete_url = reverse('social:complete', args=('saml', ))
|
||||
try:
|
||||
saml_backend = load_backend(
|
||||
load_strategy(request),
|
||||
'saml',
|
||||
redirect_uri=complete_url,
|
||||
)
|
||||
metadata, errors = saml_backend.generate_metadata_xml()
|
||||
except Exception as e:
|
||||
logger.exception('unable to generate SAML metadata')
|
||||
errors = e
|
||||
if not errors:
|
||||
return HttpResponse(content=metadata, content_type='text/xml')
|
||||
else:
|
||||
return HttpResponse(content=str(errors), content_type='text/plain')
|
||||
|
||||
|
||||
saml_metadata = MetadataView.as_view()
|
||||
Reference in New Issue
Block a user