diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml index cbbd7d0270ac..604485d32851 100644 --- a/.github/workflows/promote.yml +++ b/.github/workflows/promote.yml @@ -29,7 +29,7 @@ jobs: - name: Set GitHub Env vars if release event if: ${{ github.event_name == 'release' }} run: | - echo "TAG_NAME=${{ env.TAG_NAME }}" >> $GITHUB_ENV + echo "TAG_NAME=${{ github.event.release.tag_name }}" >> $GITHUB_ENV - name: Checkout awx uses: actions/checkout@v3 @@ -60,15 +60,18 @@ jobs: COLLECTION_VERSION: ${{ env.TAG_NAME }} COLLECTION_TEMPLATE_VERSION: true run: | + sudo apt-get install jq make build_collection - curl_with_redirects=$(curl --head -sLw '%{http_code}' https://galaxy.ansible.com/download/${{ env.collection_namespace }}-awx-${{ env.TAG_NAME }}.tar.gz | tail -1) - curl_without_redirects=$(curl --head -sw '%{http_code}' https://galaxy.ansible.com/download/${{ env.collection_namespace }}-awx-${{ env.TAG_NAME }}.tar.gz | tail -1) - if [[ "$curl_with_redirects" == "302" ]] || [[ "$curl_without_redirects" == "302" ]]; then + count=$(curl -s https://galaxy.ansible.com/api/v3/plugin/ansible/search/collection-versions/\?namespace\=${COLLECTION_NAMESPACE}\&name\=awx\&version\=${COLLECTION_VERSION} | jq .meta.count) + if [[ "$count" == "1" ]]; then echo "Galaxy release already done"; - else + elif [[ "$count" == "0" ]]; then ansible-galaxy collection publish \ --token=${{ secrets.GALAXY_TOKEN }} \ - awx_collection_build/${{ env.collection_namespace }}-awx-${{ env.TAG_NAME }}.tar.gz; + awx_collection_build/${COLLECTION_NAMESPACE}-awx-${COLLECTION_VERSION}.tar.gz; + else + echo "Unexpected count from galaxy search: $count"; + exit 1; fi - name: Set official pypi info diff --git a/.yamllint b/.yamllint index a937588cdc26..87a0d311a651 100644 --- a/.yamllint +++ b/.yamllint @@ -11,6 +11,8 @@ ignore: | # django template files awx/api/templates/instance_install_bundle/** .readthedocs.yaml + tools/loki + tools/otel extends: default diff --git a/Makefile b/Makefile index 2f5223621f06..1b6ff5156d34 100644 --- a/Makefile +++ b/Makefile @@ -47,8 +47,14 @@ VAULT ?= false VAULT_TLS ?= false # If set to true docker-compose will also start a tacacs+ instance TACACS ?= false +# If set to true docker-compose will also start an OpenTelemetry Collector instance +OTEL ?= false +# If set to true docker-compose will also start a Loki instance +LOKI ?= false # If set to true docker-compose will install editable dependencies EDITABLE_DEPENDENCIES ?= false +# If set to true, use tls for postgres connection +PG_TLS ?= false VENV_BASE ?= /var/lib/awx/venv @@ -65,7 +71,7 @@ RECEPTOR_IMAGE ?= quay.io/ansible/receptor:devel SRC_ONLY_PKGS ?= cffi,pycparser,psycopg,twilio # These should be upgraded in the AWX and Ansible venv before attempting # to install the actual requirements -VENV_BOOTSTRAP ?= pip==21.2.4 setuptools==69.0.2 setuptools_scm[toml]==8.0.4 wheel==0.42.0 +VENV_BOOTSTRAP ?= pip==21.2.4 setuptools==69.0.2 setuptools_scm[toml]==8.0.4 wheel==0.42.0 cython==0.29.37 NAME ?= awx @@ -535,7 +541,10 @@ docker-compose-sources: .git/hooks/pre-commit -e enable_vault=$(VAULT) \ -e vault_tls=$(VAULT_TLS) \ -e enable_tacacs=$(TACACS) \ + -e enable_otel=$(OTEL) \ + -e enable_loki=$(LOKI) \ -e install_editable_dependencies=$(EDITABLE_DEPENDENCIES) \ + -e pg_tls=$(PG_TLS) \ $(EXTRA_SOURCES_ANSIBLE_OPTS) docker-compose: awx/projects docker-compose-sources diff --git a/awx/api/generics.py b/awx/api/generics.py index 5b9ea1e1766e..2597e2452ac2 100644 --- a/awx/api/generics.py +++ b/awx/api/generics.py @@ -33,6 +33,7 @@ # django-ansible-base from ansible_base.rest_filters.rest_framework.field_lookup_backend import FieldLookupBackend from ansible_base.lib.utils.models import get_all_field_names +from ansible_base.lib.utils.requests import get_remote_host from ansible_base.rbac.models import RoleEvaluation, RoleDefinition from ansible_base.rbac.permission_registry import permission_registry @@ -93,8 +94,9 @@ def get(self, request, *args, **kwargs): def post(self, request, *args, **kwargs): ret = super(LoggedLoginView, self).post(request, *args, **kwargs) + ip = get_remote_host(request) # request.META.get('REMOTE_ADDR', None) if request.user.is_authenticated: - logger.info(smart_str(u"User {} logged in from {}".format(self.request.user.username, request.META.get('REMOTE_ADDR', None)))) + logger.info(smart_str(u"User {} logged in from {}".format(self.request.user.username, ip))) ret.set_cookie( 'userLoggedIn', 'true', secure=getattr(settings, 'SESSION_COOKIE_SECURE', False), samesite=getattr(settings, 'USER_COOKIE_SAMESITE', 'Lax') ) @@ -103,7 +105,7 @@ def post(self, request, *args, **kwargs): return ret else: if 'username' in self.request.POST: - logger.warning(smart_str(u"Login failed for user {} from {}".format(self.request.POST.get('username'), request.META.get('REMOTE_ADDR', None)))) + logger.warning(smart_str(u"Login failed for user {} from {}".format(self.request.POST.get('username'), ip))) ret.status_code = 401 return ret @@ -211,11 +213,12 @@ def finalize_response(self, request, response, *args, **kwargs): return response if response.status_code >= 400: + ip = get_remote_host(request) # request.META.get('REMOTE_ADDR', None) msg_data = { 'status_code': response.status_code, 'user_name': request.user, 'url_path': request.path, - 'remote_addr': request.META.get('REMOTE_ADDR', None), + 'remote_addr': ip, } if type(response.data) is dict: diff --git a/awx/api/serializers.py b/awx/api/serializers.py index 75844e9d84a9..b42783eb2a4d 100644 --- a/awx/api/serializers.py +++ b/awx/api/serializers.py @@ -5381,7 +5381,7 @@ class Meta: ) def get_body(self, obj): - if obj.notification_type in ('webhook', 'pagerduty'): + if obj.notification_type in ('webhook', 'pagerduty', 'awssns'): if isinstance(obj.body, dict): if 'body' in obj.body: return obj.body['body'] @@ -5403,9 +5403,9 @@ def get_related(self, obj): def to_representation(self, obj): ret = super(NotificationSerializer, self).to_representation(obj) - if obj.notification_type == 'webhook': + if obj.notification_type in ('webhook', 'awssns'): ret.pop('subject') - if obj.notification_type not in ('email', 'webhook', 'pagerduty'): + if obj.notification_type not in ('email', 'webhook', 'pagerduty', 'awssns'): ret.pop('body') return ret diff --git a/awx/api/views/__init__.py b/awx/api/views/__init__.py index 9bc8bad28621..92db0f87f20f 100644 --- a/awx/api/views/__init__.py +++ b/awx/api/views/__init__.py @@ -62,6 +62,7 @@ # django-ansible-base from ansible_base.rbac.models import RoleEvaluation, ObjectRole +from ansible_base.resource_registry.shared_types import OrganizationType, TeamType, UserType # AWX from awx.main.tasks.system import send_notifications, update_inventory_computed_fields @@ -128,6 +129,7 @@ from awx.api.pagination import UnifiedJobEventPagination from awx.main.utils import set_environ + logger = logging.getLogger('awx.api.views') @@ -710,16 +712,81 @@ def get(self, request): return Response(data) +def immutablesharedfields(cls): + ''' + Class decorator to prevent modifying shared resources when ALLOW_LOCAL_RESOURCE_MANAGEMENT setting is set to False. + + Works by overriding these view methods: + - create + - delete + - perform_update + create and delete are overridden to raise a PermissionDenied exception. + perform_update is overridden to check if any shared fields are being modified, + and raise a PermissionDenied exception if so. + ''' + # create instead of perform_create because some of our views + # override create instead of perform_create + if hasattr(cls, 'create'): + cls.original_create = cls.create + + @functools.wraps(cls.create) + def create_wrapper(*args, **kwargs): + if settings.ALLOW_LOCAL_RESOURCE_MANAGEMENT: + return cls.original_create(*args, **kwargs) + raise PermissionDenied({'detail': _('Creation of this resource is not allowed. Create this resource via the platform ingress.')}) + + cls.create = create_wrapper + + if hasattr(cls, 'delete'): + cls.original_delete = cls.delete + + @functools.wraps(cls.delete) + def delete_wrapper(*args, **kwargs): + if settings.ALLOW_LOCAL_RESOURCE_MANAGEMENT: + return cls.original_delete(*args, **kwargs) + raise PermissionDenied({'detail': _('Deletion of this resource is not allowed. Delete this resource via the platform ingress.')}) + + cls.delete = delete_wrapper + + if hasattr(cls, 'perform_update'): + cls.original_perform_update = cls.perform_update + + @functools.wraps(cls.perform_update) + def update_wrapper(*args, **kwargs): + if not settings.ALLOW_LOCAL_RESOURCE_MANAGEMENT: + view, serializer = args + instance = view.get_object() + if instance: + if isinstance(instance, models.Organization): + shared_fields = OrganizationType._declared_fields.keys() + elif isinstance(instance, models.User): + shared_fields = UserType._declared_fields.keys() + elif isinstance(instance, models.Team): + shared_fields = TeamType._declared_fields.keys() + attrs = serializer.validated_data + for field in shared_fields: + if field in attrs and getattr(instance, field) != attrs[field]: + raise PermissionDenied({field: _(f"Cannot change shared field '{field}'. Alter this field via the platform ingress.")}) + return cls.original_perform_update(*args, **kwargs) + + cls.perform_update = update_wrapper + + return cls + + +@immutablesharedfields class TeamList(ListCreateAPIView): model = models.Team serializer_class = serializers.TeamSerializer +@immutablesharedfields class TeamDetail(RetrieveUpdateDestroyAPIView): model = models.Team serializer_class = serializers.TeamSerializer +@immutablesharedfields class TeamUsersList(BaseUsersList): model = models.User serializer_class = serializers.UserSerializer @@ -1101,6 +1168,7 @@ class ProjectCopy(CopyAPIView): copy_return_serializer_class = serializers.ProjectSerializer +@immutablesharedfields class UserList(ListCreateAPIView): model = models.User serializer_class = serializers.UserSerializer @@ -1271,7 +1339,16 @@ def post(self, request, *args, **kwargs): user = get_object_or_400(models.User, pk=self.kwargs['pk']) role = get_object_or_400(models.Role, pk=sub_id) - credential_content_type = ContentType.objects.get_for_model(models.Credential) + content_types = ContentType.objects.get_for_models(models.Organization, models.Team, models.Credential) # dict of {model: content_type} + # Prevent user to be associated with team/org when ALLOW_LOCAL_RESOURCE_MANAGEMENT is False + if not settings.ALLOW_LOCAL_RESOURCE_MANAGEMENT: + for model in [models.Organization, models.Team]: + ct = content_types[model] + if role.content_type == ct and role.role_field in ['member_role', 'admin_role']: + data = dict(msg=_(f"Cannot directly modify user membership to {ct.model}. Direct shared resource management disabled")) + return Response(data, status=status.HTTP_403_FORBIDDEN) + + credential_content_type = content_types[models.Credential] if role.content_type == credential_content_type: if 'disassociate' not in request.data and role.content_object.organization and user not in role.content_object.organization.member_role: data = dict(msg=_("You cannot grant credential access to a user not in the credentials' organization")) @@ -1343,6 +1420,7 @@ def get_queryset(self): return qs.filter(Q(actor=parent) | Q(user__in=[parent])) +@immutablesharedfields class UserDetail(RetrieveUpdateDestroyAPIView): model = models.User serializer_class = serializers.UserSerializer @@ -4295,7 +4373,15 @@ def post(self, request, *args, **kwargs): user = get_object_or_400(models.User, pk=sub_id) role = self.get_parent_object() - credential_content_type = ContentType.objects.get_for_model(models.Credential) + content_types = ContentType.objects.get_for_models(models.Organization, models.Team, models.Credential) # dict of {model: content_type} + if not settings.ALLOW_LOCAL_RESOURCE_MANAGEMENT: + for model in [models.Organization, models.Team]: + ct = content_types[model] + if role.content_type == ct and role.role_field in ['member_role', 'admin_role']: + data = dict(msg=_(f"Cannot directly modify user membership to {ct.model}. Direct shared resource management disabled")) + return Response(data, status=status.HTTP_403_FORBIDDEN) + + credential_content_type = content_types[models.Credential] if role.content_type == credential_content_type: if 'disassociate' not in request.data and role.content_object.organization and user not in role.content_object.organization.member_role: data = dict(msg=_("You cannot grant credential access to a user not in the credentials' organization")) diff --git a/awx/api/views/organization.py b/awx/api/views/organization.py index b82f4b3a4be0..9b93ac8406a6 100644 --- a/awx/api/views/organization.py +++ b/awx/api/views/organization.py @@ -53,15 +53,18 @@ CredentialSerializer, ) from awx.api.views.mixin import RelatedJobsPreventDeleteMixin, OrganizationCountsMixin +from awx.api.views import immutablesharedfields logger = logging.getLogger('awx.api.views.organization') +@immutablesharedfields class OrganizationList(OrganizationCountsMixin, ListCreateAPIView): model = Organization serializer_class = OrganizationSerializer +@immutablesharedfields class OrganizationDetail(RelatedJobsPreventDeleteMixin, RetrieveUpdateDestroyAPIView): model = Organization serializer_class = OrganizationSerializer @@ -104,6 +107,7 @@ class OrganizationInventoriesList(SubListAPIView): relationship = 'inventories' +@immutablesharedfields class OrganizationUsersList(BaseUsersList): model = User serializer_class = UserSerializer @@ -112,6 +116,7 @@ class OrganizationUsersList(BaseUsersList): ordering = ('username',) +@immutablesharedfields class OrganizationAdminsList(BaseUsersList): model = User serializer_class = UserSerializer @@ -150,6 +155,7 @@ class OrganizationWorkflowJobTemplatesList(SubListCreateAPIView): parent_key = 'organization' +@immutablesharedfields class OrganizationTeamsList(SubListCreateAttachDetachAPIView): model = Team serializer_class = TeamSerializer diff --git a/awx/conf/tests/unit/test_settings.py b/awx/conf/tests/unit/test_settings.py index 1d5d721680e4..1910a136f32f 100644 --- a/awx/conf/tests/unit/test_settings.py +++ b/awx/conf/tests/unit/test_settings.py @@ -130,9 +130,9 @@ def test_default_setting(settings, mocker): settings.registry.register('AWX_SOME_SETTING', field_class=fields.CharField, category=_('System'), category_slug='system', default='DEFAULT') settings_to_cache = mocker.Mock(**{'order_by.return_value': []}) - with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=settings_to_cache): - assert settings.AWX_SOME_SETTING == 'DEFAULT' - assert settings.cache.get('AWX_SOME_SETTING') == 'DEFAULT' + mocker.patch('awx.conf.models.Setting.objects.filter', return_value=settings_to_cache) + assert settings.AWX_SOME_SETTING == 'DEFAULT' + assert settings.cache.get('AWX_SOME_SETTING') == 'DEFAULT' @pytest.mark.defined_in_file(AWX_SOME_SETTING='DEFAULT') @@ -146,9 +146,9 @@ def test_setting_is_not_from_setting_file(settings, mocker): settings.registry.register('AWX_SOME_SETTING', field_class=fields.CharField, category=_('System'), category_slug='system', default='DEFAULT') settings_to_cache = mocker.Mock(**{'order_by.return_value': []}) - with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=settings_to_cache): - assert settings.AWX_SOME_SETTING == 'DEFAULT' - assert settings.registry.get_setting_field('AWX_SOME_SETTING').defined_in_file is False + mocker.patch('awx.conf.models.Setting.objects.filter', return_value=settings_to_cache) + assert settings.AWX_SOME_SETTING == 'DEFAULT' + assert settings.registry.get_setting_field('AWX_SOME_SETTING').defined_in_file is False def test_empty_setting(settings, mocker): @@ -156,10 +156,10 @@ def test_empty_setting(settings, mocker): settings.registry.register('AWX_SOME_SETTING', field_class=fields.CharField, category=_('System'), category_slug='system') mocks = mocker.Mock(**{'order_by.return_value': mocker.Mock(**{'__iter__': lambda self: iter([]), 'first.return_value': None})}) - with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=mocks): - with pytest.raises(AttributeError): - settings.AWX_SOME_SETTING - assert settings.cache.get('AWX_SOME_SETTING') == SETTING_CACHE_NOTSET + mocker.patch('awx.conf.models.Setting.objects.filter', return_value=mocks) + with pytest.raises(AttributeError): + settings.AWX_SOME_SETTING + assert settings.cache.get('AWX_SOME_SETTING') == SETTING_CACHE_NOTSET def test_setting_from_db(settings, mocker): @@ -168,9 +168,9 @@ def test_setting_from_db(settings, mocker): setting_from_db = mocker.Mock(key='AWX_SOME_SETTING', value='FROM_DB') mocks = mocker.Mock(**{'order_by.return_value': mocker.Mock(**{'__iter__': lambda self: iter([setting_from_db]), 'first.return_value': setting_from_db})}) - with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=mocks): - assert settings.AWX_SOME_SETTING == 'FROM_DB' - assert settings.cache.get('AWX_SOME_SETTING') == 'FROM_DB' + mocker.patch('awx.conf.models.Setting.objects.filter', return_value=mocks) + assert settings.AWX_SOME_SETTING == 'FROM_DB' + assert settings.cache.get('AWX_SOME_SETTING') == 'FROM_DB' @pytest.mark.defined_in_file(AWX_SOME_SETTING='DEFAULT') @@ -205,8 +205,8 @@ def test_db_setting_update(settings, mocker): existing_setting = mocker.Mock(key='AWX_SOME_SETTING', value='FROM_DB') setting_list = mocker.Mock(**{'order_by.return_value.first.return_value': existing_setting}) - with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=setting_list): - settings.AWX_SOME_SETTING = 'NEW-VALUE' + mocker.patch('awx.conf.models.Setting.objects.filter', return_value=setting_list) + settings.AWX_SOME_SETTING = 'NEW-VALUE' assert existing_setting.value == 'NEW-VALUE' existing_setting.save.assert_called_with(update_fields=['value']) @@ -217,8 +217,8 @@ def test_db_setting_deletion(settings, mocker): settings.registry.register('AWX_SOME_SETTING', field_class=fields.CharField, category=_('System'), category_slug='system') existing_setting = mocker.Mock(key='AWX_SOME_SETTING', value='FROM_DB') - with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=[existing_setting]): - del settings.AWX_SOME_SETTING + mocker.patch('awx.conf.models.Setting.objects.filter', return_value=[existing_setting]) + del settings.AWX_SOME_SETTING assert existing_setting.delete.call_count == 1 @@ -283,10 +283,10 @@ def rot13(obj, attribute): # use its primary key as part of the encryption key setting_from_db = mocker.Mock(pk=123, key='AWX_ENCRYPTED', value='SECRET!') mocks = mocker.Mock(**{'order_by.return_value': mocker.Mock(**{'__iter__': lambda self: iter([setting_from_db]), 'first.return_value': setting_from_db})}) - with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=mocks): - cache.set('AWX_ENCRYPTED', 'SECRET!') - assert cache.get('AWX_ENCRYPTED') == 'SECRET!' - assert native_cache.get('AWX_ENCRYPTED') == 'FRPERG!' + mocker.patch('awx.conf.models.Setting.objects.filter', return_value=mocks) + cache.set('AWX_ENCRYPTED', 'SECRET!') + assert cache.get('AWX_ENCRYPTED') == 'SECRET!' + assert native_cache.get('AWX_ENCRYPTED') == 'FRPERG!' def test_readonly_sensitive_cache_data_is_encrypted(settings): diff --git a/awx/main/fields.py b/awx/main/fields.py index c6d01f279500..49895d70fc3f 100644 --- a/awx/main/fields.py +++ b/awx/main/fields.py @@ -252,7 +252,7 @@ def __init__(self, parent_role=None, *args, **kwargs): kwargs.setdefault('related_name', '+') kwargs.setdefault('null', 'True') kwargs.setdefault('editable', False) - kwargs.setdefault('on_delete', models.CASCADE) + kwargs.setdefault('on_delete', models.SET_NULL) super(ImplicitRoleField, self).__init__(*args, **kwargs) def deconstruct(self): diff --git a/awx/main/management/commands/check_instance_ready.py b/awx/main/management/commands/check_instance_ready.py new file mode 100644 index 000000000000..833870d8dbc7 --- /dev/null +++ b/awx/main/management/commands/check_instance_ready.py @@ -0,0 +1,12 @@ +from django.core.management.base import BaseCommand, CommandError +from awx.main.models.ha import Instance + + +class Command(BaseCommand): + help = 'Check if the task manager instance is ready throw error if not ready, can be use as readiness probe for k8s.' + + def handle(self, *args, **options): + if Instance.objects.me().node_state != Instance.States.READY: + raise CommandError('Instance is not ready') # so that return code is not 0 + + return diff --git a/awx/main/management/commands/run_wsrelay.py b/awx/main/management/commands/run_wsrelay.py index ee7cbca6825e..a3016ffc9296 100644 --- a/awx/main/management/commands/run_wsrelay.py +++ b/awx/main/management/commands/run_wsrelay.py @@ -101,8 +101,9 @@ def handle(self, *arg, **options): migrating = bool(executor.migration_plan(executor.loader.graph.leaf_nodes())) connection.close() # Because of async nature, main loop will use new connection, so close this except Exception as exc: - logger.warning(f'Error on startup of run_wsrelay (error: {exc}), retry in 10s...') - time.sleep(10) + time.sleep(10) # Prevent supervisor from restarting the service too quickly and the service to enter FATAL state + # sleeping before logging because logging rely on setting which require database connection... + logger.warning(f'Error on startup of run_wsrelay (error: {exc}), slept for 10s...') return # In containerized deployments, migrations happen in the task container, @@ -121,13 +122,14 @@ def handle(self, *arg, **options): return try: - my_hostname = Instance.objects.my_hostname() + my_hostname = Instance.objects.my_hostname() # This relies on settings.CLUSTER_HOST_ID which requires database connection logger.info('Active instance with hostname {} is registered.'.format(my_hostname)) except RuntimeError as e: # the CLUSTER_HOST_ID in the task, and web instance must match and # ensure network connectivity between the task and web instance - logger.info('Unable to return currently active instance: {}, retry in 5s...'.format(e)) - time.sleep(5) + time.sleep(10) # Prevent supervisor from restarting the service too quickly and the service to enter FATAL state + # sleeping before logging because logging rely on setting which require database connection... + logger.warning(f"Unable to return currently active instance: {e}, slept for 10s before return.") return if options.get('status'): @@ -166,12 +168,14 @@ def handle(self, *arg, **options): WebsocketsMetricsServer().start() - while True: - try: - asyncio.run(WebSocketRelayManager().run()) - except KeyboardInterrupt: - logger.info('Shutting down Websocket Relayer') - break - except Exception as e: - logger.exception('Error in Websocket Relayer, exception: {}. Restarting in 10 seconds'.format(e)) - time.sleep(10) + try: + logger.info('Starting Websocket Relayer...') + websocket_relay_manager = WebSocketRelayManager() + asyncio.run(websocket_relay_manager.run()) + except KeyboardInterrupt: + logger.info('Terminating Websocket Relayer') + except BaseException as e: # BaseException is used to catch all exceptions including asyncio.CancelledError + time.sleep(10) # Prevent supervisor from restarting the service too quickly and the service to enter FATAL state + # sleeping before logging because logging rely on setting which require database connection... + logger.warning(f"Encounter error while running Websocket Relayer {e}, slept for 10s...") + return diff --git a/awx/main/middleware.py b/awx/main/middleware.py index d485ce45f7e3..433ade596fe4 100644 --- a/awx/main/middleware.py +++ b/awx/main/middleware.py @@ -6,7 +6,7 @@ import threading import time import urllib.parse -from pathlib import Path +from pathlib import Path, PurePosixPath from django.conf import settings from django.contrib.auth import logout @@ -138,14 +138,36 @@ def _named_url_to_pk(cls, node, resource, named_url): @classmethod def _convert_named_url(cls, url_path): - url_units = url_path.split('/') - # If the identifier is an empty string, it is always invalid. - if len(url_units) < 6 or url_units[1] != 'api' or url_units[2] not in ['v2'] or not url_units[4]: - return url_path - resource = url_units[3] + default_prefix = PurePosixPath('/api/v2/') + optional_prefix = PurePosixPath(f'/api/{settings.OPTIONAL_API_URLPATTERN_PREFIX}/v2/') + + url_path_original = url_path + url_path = PurePosixPath(url_path) + + if set(optional_prefix.parts).issubset(set(url_path.parts)): + url_prefix = optional_prefix + elif set(default_prefix.parts).issubset(set(url_path.parts)): + url_prefix = default_prefix + else: + return url_path_original + + # Remove prefix + url_path = PurePosixPath(*url_path.parts[len(url_prefix.parts) :]) + try: + resource_path = PurePosixPath(url_path.parts[0]) + name = url_path.parts[1] + url_suffix = PurePosixPath(*url_path.parts[2:]) # remove name and resource + except IndexError: + return url_path_original + + resource = resource_path.parts[0] if resource in settings.NAMED_URL_MAPPINGS: - url_units[4] = cls._named_url_to_pk(settings.NAMED_URL_GRAPH[settings.NAMED_URL_MAPPINGS[resource]], resource, url_units[4]) - return '/'.join(url_units) + pk = PurePosixPath(cls._named_url_to_pk(settings.NAMED_URL_GRAPH[settings.NAMED_URL_MAPPINGS[resource]], resource, name)) + else: + return url_path_original + + parts = url_prefix.parts + resource_path.parts + pk.parts + url_suffix.parts + return PurePosixPath(*parts).as_posix() + '/' def process_request(self, request): old_path = request.path_info diff --git a/awx/main/migrations/0021_v330_declare_new_rbac_roles.py b/awx/main/migrations/0021_v330_declare_new_rbac_roles.py index 5f8e7788fea3..d5302fae42dc 100644 --- a/awx/main/migrations/0021_v330_declare_new_rbac_roles.py +++ b/awx/main/migrations/0021_v330_declare_new_rbac_roles.py @@ -17,49 +17,49 @@ class Migration(migrations.Migration): model_name='organization', name='execute_role', field=awx.main.fields.ImplicitRoleField( - null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), ), migrations.AddField( model_name='organization', name='job_template_admin_role', field=awx.main.fields.ImplicitRoleField( - editable=False, null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + editable=False, null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), ), migrations.AddField( model_name='organization', name='credential_admin_role', field=awx.main.fields.ImplicitRoleField( - null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), ), migrations.AddField( model_name='organization', name='inventory_admin_role', field=awx.main.fields.ImplicitRoleField( - null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), ), migrations.AddField( model_name='organization', name='project_admin_role', field=awx.main.fields.ImplicitRoleField( - null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), ), migrations.AddField( model_name='organization', name='workflow_admin_role', field=awx.main.fields.ImplicitRoleField( - null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), ), migrations.AddField( model_name='organization', name='notification_admin_role', field=awx.main.fields.ImplicitRoleField( - null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), ), migrations.AlterField( @@ -67,7 +67,7 @@ class Migration(migrations.Migration): name='admin_role', field=awx.main.fields.ImplicitRoleField( null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['singleton:system_administrator', 'organization.credential_admin_role'], related_name='+', to='main.Role', @@ -77,7 +77,7 @@ class Migration(migrations.Migration): model_name='inventory', name='admin_role', field=awx.main.fields.ImplicitRoleField( - null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='organization.inventory_admin_role', related_name='+', to='main.Role' + null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='organization.inventory_admin_role', related_name='+', to='main.Role' ), ), migrations.AlterField( @@ -85,7 +85,7 @@ class Migration(migrations.Migration): name='admin_role', field=awx.main.fields.ImplicitRoleField( null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['organization.project_admin_role', 'singleton:system_administrator'], related_name='+', to='main.Role', @@ -96,7 +96,7 @@ class Migration(migrations.Migration): name='admin_role', field=awx.main.fields.ImplicitRoleField( null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['singleton:system_administrator', 'organization.workflow_admin_role'], related_name='+', to='main.Role', @@ -107,7 +107,7 @@ class Migration(migrations.Migration): name='execute_role', field=awx.main.fields.ImplicitRoleField( null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['admin_role', 'organization.execute_role'], related_name='+', to='main.Role', @@ -119,7 +119,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['project.organization.job_template_admin_role', 'inventory.organization.job_template_admin_role'], related_name='+', to='main.Role', @@ -130,7 +130,7 @@ class Migration(migrations.Migration): name='execute_role', field=awx.main.fields.ImplicitRoleField( null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['admin_role', 'project.organization.execute_role', 'inventory.organization.execute_role'], related_name='+', to='main.Role', @@ -142,7 +142,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=[ 'admin_role', 'execute_role', diff --git a/awx/main/migrations/0042_v330_org_member_role_deparent.py b/awx/main/migrations/0042_v330_org_member_role_deparent.py index f08bdca5e2f2..ce137cbc5f82 100644 --- a/awx/main/migrations/0042_v330_org_member_role_deparent.py +++ b/awx/main/migrations/0042_v330_org_member_role_deparent.py @@ -18,7 +18,7 @@ class Migration(migrations.Migration): model_name='organization', name='member_role', field=awx.main.fields.ImplicitRoleField( - editable=False, null='True', on_delete=django.db.models.deletion.CASCADE, parent_role=['admin_role'], related_name='+', to='main.Role' + editable=False, null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role=['admin_role'], related_name='+', to='main.Role' ), ), migrations.AlterField( @@ -27,7 +27,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=[ 'member_role', 'auditor_role', diff --git a/awx/main/migrations/0086_v360_workflow_approval.py b/awx/main/migrations/0086_v360_workflow_approval.py index 999cba8ec160..7612b0799427 100644 --- a/awx/main/migrations/0086_v360_workflow_approval.py +++ b/awx/main/migrations/0086_v360_workflow_approval.py @@ -36,7 +36,7 @@ class Migration(migrations.Migration): model_name='organization', name='approval_role', field=awx.main.fields.ImplicitRoleField( - editable=False, null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + editable=False, null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), preserve_default='True', ), @@ -46,7 +46,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['organization.approval_role', 'admin_role'], related_name='+', to='main.Role', @@ -116,7 +116,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=[ 'member_role', 'auditor_role', @@ -139,7 +139,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['singleton:system_auditor', 'organization.auditor_role', 'execute_role', 'admin_role', 'approval_role'], related_name='+', to='main.Role', diff --git a/awx/main/migrations/0109_v370_job_template_organization_field.py b/awx/main/migrations/0109_v370_job_template_organization_field.py index 38c1867480eb..41564ffba2f7 100644 --- a/awx/main/migrations/0109_v370_job_template_organization_field.py +++ b/awx/main/migrations/0109_v370_job_template_organization_field.py @@ -80,7 +80,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['organization.job_template_admin_role'], related_name='+', to='main.Role', @@ -92,7 +92,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['admin_role', 'organization.execute_role'], related_name='+', to='main.Role', @@ -104,7 +104,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['organization.auditor_role', 'inventory.organization.auditor_role', 'execute_role', 'admin_role'], related_name='+', to='main.Role', diff --git a/awx/main/migrations/0125_more_ee_modeling_changes.py b/awx/main/migrations/0125_more_ee_modeling_changes.py index e1e0a86e14f0..a866dd89f64c 100644 --- a/awx/main/migrations/0125_more_ee_modeling_changes.py +++ b/awx/main/migrations/0125_more_ee_modeling_changes.py @@ -26,7 +26,7 @@ class Migration(migrations.Migration): model_name='organization', name='execution_environment_admin_role', field=awx.main.fields.ImplicitRoleField( - editable=False, null='True', on_delete=django.db.models.deletion.CASCADE, parent_role='admin_role', related_name='+', to='main.Role' + editable=False, null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role='admin_role', related_name='+', to='main.Role' ), preserve_default='True', ), diff --git a/awx/main/migrations/0128_organiaztion_read_roles_ee_admin.py b/awx/main/migrations/0128_organiaztion_read_roles_ee_admin.py index 482f4509a5de..262031d94b97 100644 --- a/awx/main/migrations/0128_organiaztion_read_roles_ee_admin.py +++ b/awx/main/migrations/0128_organiaztion_read_roles_ee_admin.py @@ -17,7 +17,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=[ 'member_role', 'auditor_role', diff --git a/awx/main/migrations/0177_instance_group_role_addition.py b/awx/main/migrations/0177_instance_group_role_addition.py index c25a43845b74..27c53e3d93a2 100644 --- a/awx/main/migrations/0177_instance_group_role_addition.py +++ b/awx/main/migrations/0177_instance_group_role_addition.py @@ -17,7 +17,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['singleton:system_administrator'], related_name='+', to='main.role', @@ -30,7 +30,7 @@ class Migration(migrations.Migration): field=awx.main.fields.ImplicitRoleField( editable=False, null='True', - on_delete=django.db.models.deletion.CASCADE, + on_delete=django.db.models.deletion.SET_NULL, parent_role=['singleton:system_auditor', 'use_role', 'admin_role'], related_name='+', to='main.role', @@ -41,7 +41,7 @@ class Migration(migrations.Migration): model_name='instancegroup', name='use_role', field=awx.main.fields.ImplicitRoleField( - editable=False, null='True', on_delete=django.db.models.deletion.CASCADE, parent_role=['admin_role'], related_name='+', to='main.role' + editable=False, null='True', on_delete=django.db.models.deletion.SET_NULL, parent_role=['admin_role'], related_name='+', to='main.role' ), preserve_default='True', ), diff --git a/awx/main/migrations/0193_alter_notification_notification_type_and_more.py b/awx/main/migrations/0193_alter_notification_notification_type_and_more.py new file mode 100644 index 000000000000..59fde544c8e9 --- /dev/null +++ b/awx/main/migrations/0193_alter_notification_notification_type_and_more.py @@ -0,0 +1,51 @@ +# Generated by Django 4.2.6 on 2024-05-08 07:29 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('main', '0192_custom_roles'), + ] + + operations = [ + migrations.AlterField( + model_name='notification', + name='notification_type', + field=models.CharField( + choices=[ + ('awssns', 'AWS SNS'), + ('email', 'Email'), + ('grafana', 'Grafana'), + ('irc', 'IRC'), + ('mattermost', 'Mattermost'), + ('pagerduty', 'Pagerduty'), + ('rocketchat', 'Rocket.Chat'), + ('slack', 'Slack'), + ('twilio', 'Twilio'), + ('webhook', 'Webhook'), + ], + max_length=32, + ), + ), + migrations.AlterField( + model_name='notificationtemplate', + name='notification_type', + field=models.CharField( + choices=[ + ('awssns', 'AWS SNS'), + ('email', 'Email'), + ('grafana', 'Grafana'), + ('irc', 'IRC'), + ('mattermost', 'Mattermost'), + ('pagerduty', 'Pagerduty'), + ('rocketchat', 'Rocket.Chat'), + ('slack', 'Slack'), + ('twilio', 'Twilio'), + ('webhook', 'Webhook'), + ], + max_length=32, + ), + ), + ] diff --git a/awx/main/models/events.py b/awx/main/models/events.py index a794152c0537..fb19de554b6d 100644 --- a/awx/main/models/events.py +++ b/awx/main/models/events.py @@ -4,11 +4,12 @@ from datetime import timezone import logging from collections import defaultdict +import itertools import time from django.conf import settings from django.core.exceptions import ObjectDoesNotExist -from django.db import models, DatabaseError +from django.db import models, DatabaseError, transaction from django.db.models.functions import Cast from django.utils.dateparse import parse_datetime from django.utils.text import Truncator @@ -605,19 +606,23 @@ def _update_host_summary_from_stats(self, hostnames): def _update_host_metrics(updated_hosts_list): from awx.main.models import HostMetric # circular import - # bulk-create current_time = now() - HostMetric.objects.bulk_create( - [HostMetric(hostname=hostname, last_automation=current_time) for hostname in updated_hosts_list], ignore_conflicts=True, batch_size=100 - ) - # bulk-update - batch_start, batch_size = 0, 1000 - while batch_start <= len(updated_hosts_list): - batched_host_list = updated_hosts_list[batch_start : (batch_start + batch_size)] - HostMetric.objects.filter(hostname__in=batched_host_list).update( - last_automation=current_time, automated_counter=models.F('automated_counter') + 1, deleted=False - ) - batch_start += batch_size + + # FUTURE: + # - Hand-rolled implementation of itertools.batched(), introduced in Python 3.12. Replace. + # - Ability to do ORM upserts *may* have been introduced in Django 5.0. + # See the entry about `create_defaults` in https://docs.djangoproject.com/en/5.0/releases/5.0/#models. + # Hopefully this will be fully ready for batch use by 5.2 LTS. + + args = [iter(updated_hosts_list)] * 500 + for hosts in itertools.zip_longest(*args): + with transaction.atomic(): + HostMetric.objects.bulk_create( + [HostMetric(hostname=hostname, last_automation=current_time) for hostname in hosts if hostname is not None], ignore_conflicts=True + ) + HostMetric.objects.filter(hostname__in=hosts).update( + last_automation=current_time, automated_counter=models.F('automated_counter') + 1, deleted=False + ) @property def job_verbosity(self): diff --git a/awx/main/models/notifications.py b/awx/main/models/notifications.py index da03a7dd47f3..38fd2f21b0ca 100644 --- a/awx/main/models/notifications.py +++ b/awx/main/models/notifications.py @@ -31,6 +31,7 @@ from awx.main.notifications.grafana_backend import GrafanaBackend from awx.main.notifications.rocketchat_backend import RocketChatBackend from awx.main.notifications.irc_backend import IrcBackend +from awx.main.notifications.awssns_backend import AWSSNSBackend logger = logging.getLogger('awx.main.models.notifications') @@ -40,6 +41,7 @@ class NotificationTemplate(CommonModelNameNotUnique): NOTIFICATION_TYPES = [ + ('awssns', _('AWS SNS'), AWSSNSBackend), ('email', _('Email'), CustomEmailBackend), ('slack', _('Slack'), SlackBackend), ('twilio', _('Twilio'), TwilioBackend), diff --git a/awx/main/models/unified_jobs.py b/awx/main/models/unified_jobs.py index 4f885585a66f..39bc56f43bfb 100644 --- a/awx/main/models/unified_jobs.py +++ b/awx/main/models/unified_jobs.py @@ -17,7 +17,7 @@ # Django from django.conf import settings -from django.db import models, connection +from django.db import models, connection, transaction from django.core.exceptions import NON_FIELD_ERRORS from django.utils.translation import gettext_lazy as _ from django.utils.timezone import now @@ -273,7 +273,14 @@ def update_computed_fields(self): if new_next_schedule: if new_next_schedule.pk == self.next_schedule_id and new_next_schedule.next_run == self.next_job_run: return # no-op, common for infrequent schedules - self.next_schedule = new_next_schedule + + # If in a transaction, use select_for_update to lock the next schedule row, which + # prevents a race condition if new_next_schedule is deleted elsewhere during this transaction + if transaction.get_autocommit(): + self.next_schedule = related_schedules.first() + else: + self.next_schedule = related_schedules.select_for_update().first() + self.next_job_run = new_next_schedule.next_run self.save(update_fields=['next_schedule', 'next_job_run']) diff --git a/awx/main/notifications/awssns_backend.py b/awx/main/notifications/awssns_backend.py new file mode 100644 index 000000000000..f566e555e909 --- /dev/null +++ b/awx/main/notifications/awssns_backend.py @@ -0,0 +1,70 @@ +# Copyright (c) 2016 Ansible, Inc. +# All Rights Reserved. +import json +import logging + +import boto3 +from botocore.exceptions import ClientError + +from awx.main.notifications.base import AWXBaseEmailBackend +from awx.main.notifications.custom_notification_base import CustomNotificationBase + +logger = logging.getLogger('awx.main.notifications.awssns_backend') +WEBSOCKET_TIMEOUT = 30 + + +class AWSSNSBackend(AWXBaseEmailBackend, CustomNotificationBase): + init_parameters = { + "aws_region": {"label": "AWS Region", "type": "string", "default": ""}, + "aws_access_key_id": {"label": "Access Key ID", "type": "string", "default": ""}, + "aws_secret_access_key": {"label": "Secret Access Key", "type": "password", "default": ""}, + "aws_session_token": {"label": "Session Token", "type": "password", "default": ""}, + "sns_topic_arn": {"label": "SNS Topic ARN", "type": "string", "default": ""}, + } + recipient_parameter = "sns_topic_arn" + sender_parameter = None + + DEFAULT_BODY = "{{ job_metadata }}" + default_messages = CustomNotificationBase.job_metadata_messages + + def __init__(self, aws_region, aws_access_key_id, aws_secret_access_key, aws_session_token, fail_silently=False, **kwargs): + session = boto3.session.Session() + client_config = {"service_name": 'sns'} + if aws_region: + client_config["region_name"] = aws_region + if aws_secret_access_key: + client_config["aws_secret_access_key"] = aws_secret_access_key + if aws_access_key_id: + client_config["aws_access_key_id"] = aws_access_key_id + if aws_session_token: + client_config["aws_session_token"] = aws_session_token + self.client = session.client(**client_config) + super(AWSSNSBackend, self).__init__(fail_silently=fail_silently) + + def _sns_publish(self, topic_arn, message): + self.client.publish(TopicArn=topic_arn, Message=message, MessageAttributes={}) + + def format_body(self, body): + if isinstance(body, str): + try: + body = json.loads(body) + except json.JSONDecodeError: + pass + + if isinstance(body, dict): + body = json.dumps(body) + # convert dict body to json string + return body + + def send_messages(self, messages): + sent_messages = 0 + for message in messages: + sns_topic_arn = str(message.recipients()[0]) + try: + self._sns_publish(topic_arn=sns_topic_arn, message=message.body) + sent_messages += 1 + except ClientError as error: + if not self.fail_silently: + raise error + + return sent_messages diff --git a/awx/main/notifications/custom_notification_base.py b/awx/main/notifications/custom_notification_base.py index 22d04f651156..034ff3ddbf97 100644 --- a/awx/main/notifications/custom_notification_base.py +++ b/awx/main/notifications/custom_notification_base.py @@ -32,3 +32,15 @@ class CustomNotificationBase(object): "denied": {"message": DEFAULT_APPROVAL_DENIED_MSG, "body": None}, }, } + + job_metadata_messages = { + "started": {"body": "{{ job_metadata }}"}, + "success": {"body": "{{ job_metadata }}"}, + "error": {"body": "{{ job_metadata }}"}, + "workflow_approval": { + "running": {"body": '{"body": "The approval node \\"{{ approval_node_name }}\\" needs review. This node can be viewed at: {{ workflow_url }}"}'}, + "approved": {"body": '{"body": "The approval node \\"{{ approval_node_name }}\\" was approved. {{ workflow_url }}"}'}, + "timed_out": {"body": '{"body": "The approval node \\"{{ approval_node_name }}\\" has timed out. {{ workflow_url }}"}'}, + "denied": {"body": '{"body": "The approval node \\"{{ approval_node_name }}\\" was denied. {{ workflow_url }}"}'}, + }, + } diff --git a/awx/main/notifications/webhook_backend.py b/awx/main/notifications/webhook_backend.py index 6cb4c21b8337..615c549fba6a 100644 --- a/awx/main/notifications/webhook_backend.py +++ b/awx/main/notifications/webhook_backend.py @@ -27,17 +27,7 @@ class WebhookBackend(AWXBaseEmailBackend, CustomNotificationBase): sender_parameter = None DEFAULT_BODY = "{{ job_metadata }}" - default_messages = { - "started": {"body": DEFAULT_BODY}, - "success": {"body": DEFAULT_BODY}, - "error": {"body": DEFAULT_BODY}, - "workflow_approval": { - "running": {"body": '{"body": "The approval node \\"{{ approval_node_name }}\\" needs review. This node can be viewed at: {{ workflow_url }}"}'}, - "approved": {"body": '{"body": "The approval node \\"{{ approval_node_name }}\\" was approved. {{ workflow_url }}"}'}, - "timed_out": {"body": '{"body": "The approval node \\"{{ approval_node_name }}\\" has timed out. {{ workflow_url }}"}'}, - "denied": {"body": '{"body": "The approval node \\"{{ approval_node_name }}\\" was denied. {{ workflow_url }}"}'}, - }, - } + default_messages = CustomNotificationBase.job_metadata_messages def __init__(self, http_method, headers, disable_ssl_verification=False, fail_silently=False, username=None, password=None, **kwargs): self.http_method = http_method diff --git a/awx/main/tasks/system.py b/awx/main/tasks/system.py index bca9d16c055f..aa65e706c1a7 100644 --- a/awx/main/tasks/system.py +++ b/awx/main/tasks/system.py @@ -36,6 +36,9 @@ # dateutil from dateutil.parser import parse as parse_date +# django-ansible-base +from ansible_base.resource_registry.tasks.sync import SyncExecutor + # AWX from awx import __version__ as awx_application_version from awx.main.access import access_registry @@ -964,3 +967,17 @@ def deep_copy_model_obj(model_module, model_name, obj_pk, new_obj_pk, user_pk, p permission_check_func(creater, copy_mapping.values()) if isinstance(new_obj, Inventory): update_inventory_computed_fields.delay(new_obj.id) + + +@task(queue=get_task_queuename) +def periodic_resource_sync(): + if not getattr(settings, 'RESOURCE_SERVER', None): + logger.debug("Skipping periodic resource_sync, RESOURCE_SERVER not configured") + return + + with advisory_lock('periodic_resource_sync', wait=False) as acquired: + if acquired is False: + logger.debug("Not running periodic_resource_sync, another task holds lock") + return + + SyncExecutor().run() diff --git a/awx/main/tests/functional/api/test_create_attach_views.py b/awx/main/tests/functional/api/test_create_attach_views.py index b22ec089122f..7b92f82f5076 100644 --- a/awx/main/tests/functional/api/test_create_attach_views.py +++ b/awx/main/tests/functional/api/test_create_attach_views.py @@ -9,8 +9,8 @@ def test_user_role_view_access(rando, inventory, mocker, post): role_pk = inventory.admin_role.pk data = {"id": role_pk} mock_access = mocker.MagicMock(can_attach=mocker.MagicMock(return_value=False)) - with mocker.patch('awx.main.access.RoleAccess', return_value=mock_access): - post(url=reverse('api:user_roles_list', kwargs={'pk': rando.pk}), data=data, user=rando, expect=403) + mocker.patch('awx.main.access.RoleAccess', return_value=mock_access) + post(url=reverse('api:user_roles_list', kwargs={'pk': rando.pk}), data=data, user=rando, expect=403) mock_access.can_attach.assert_called_once_with(inventory.admin_role, rando, 'members', data, skip_sub_obj_read_check=False) @@ -21,8 +21,8 @@ def test_team_role_view_access(rando, team, inventory, mocker, post): role_pk = inventory.admin_role.pk data = {"id": role_pk} mock_access = mocker.MagicMock(can_attach=mocker.MagicMock(return_value=False)) - with mocker.patch('awx.main.access.RoleAccess', return_value=mock_access): - post(url=reverse('api:team_roles_list', kwargs={'pk': team.pk}), data=data, user=rando, expect=403) + mocker.patch('awx.main.access.RoleAccess', return_value=mock_access) + post(url=reverse('api:team_roles_list', kwargs={'pk': team.pk}), data=data, user=rando, expect=403) mock_access.can_attach.assert_called_once_with(inventory.admin_role, team, 'member_role.parents', data, skip_sub_obj_read_check=False) @@ -33,8 +33,8 @@ def test_role_team_view_access(rando, team, inventory, mocker, post): role_pk = inventory.admin_role.pk data = {"id": team.pk} mock_access = mocker.MagicMock(return_value=False, __name__='mocked') - with mocker.patch('awx.main.access.RoleAccess.can_attach', mock_access): - post(url=reverse('api:role_teams_list', kwargs={'pk': role_pk}), data=data, user=rando, expect=403) + mocker.patch('awx.main.access.RoleAccess.can_attach', mock_access) + post(url=reverse('api:role_teams_list', kwargs={'pk': role_pk}), data=data, user=rando, expect=403) mock_access.assert_called_once_with(inventory.admin_role, team, 'member_role.parents', data, skip_sub_obj_read_check=False) diff --git a/awx/main/tests/functional/api/test_immutablesharedfields.py b/awx/main/tests/functional/api/test_immutablesharedfields.py new file mode 100644 index 000000000000..b5ae68f2e59c --- /dev/null +++ b/awx/main/tests/functional/api/test_immutablesharedfields.py @@ -0,0 +1,66 @@ +import pytest + +from awx.api.versioning import reverse +from awx.main.models import Organization + + +@pytest.mark.django_db +class TestImmutableSharedFields: + @pytest.fixture(autouse=True) + def configure_settings(self, settings): + settings.ALLOW_LOCAL_RESOURCE_MANAGEMENT = False + + def test_create_raises_permission_denied(self, admin_user, post): + orgA = Organization.objects.create(name='orgA') + resp = post( + url=reverse('api:team_list'), + data={'name': 'teamA', 'organization': orgA.id}, + user=admin_user, + expect=403, + ) + assert "Creation of this resource is not allowed" in resp.data['detail'] + + def test_perform_delete_raises_permission_denied(self, admin_user, delete): + orgA = Organization.objects.create(name='orgA') + team = orgA.teams.create(name='teamA') + resp = delete( + url=reverse('api:team_detail', kwargs={'pk': team.id}), + user=admin_user, + expect=403, + ) + assert "Deletion of this resource is not allowed" in resp.data['detail'] + + def test_perform_update(self, admin_user, patch): + orgA = Organization.objects.create(name='orgA') + team = orgA.teams.create(name='teamA') + # allow patching non-shared fields + patch( + url=reverse('api:team_detail', kwargs={'pk': team.id}), + data={"description": "can change this field"}, + user=admin_user, + expect=200, + ) + orgB = Organization.objects.create(name='orgB') + # prevent patching shared fields + resp = patch(url=reverse('api:team_detail', kwargs={'pk': team.id}), data={"organization": orgB.id}, user=admin_user, expect=403) + assert "Cannot change shared field" in resp.data['organization'] + + @pytest.mark.parametrize( + 'role', + ['admin_role', 'member_role'], + ) + @pytest.mark.parametrize('resource', ['organization', 'team']) + def test_prevent_assigning_member_to_organization_or_team(self, admin_user, post, resource, role): + orgA = Organization.objects.create(name='orgA') + if resource == 'organization': + role = getattr(orgA, role) + elif resource == 'team': + teamA = orgA.teams.create(name='teamA') + role = getattr(teamA, role) + resp = post( + url=reverse('api:user_roles_list', kwargs={'pk': admin_user.id}), + data={'id': role.id}, + user=admin_user, + expect=403, + ) + assert f"Cannot directly modify user membership to {resource}." in resp.data['msg'] diff --git a/awx/main/tests/functional/api/test_job_runtime_params.py b/awx/main/tests/functional/api/test_job_runtime_params.py index f477a66ed945..f893b53c66f0 100644 --- a/awx/main/tests/functional/api/test_job_runtime_params.py +++ b/awx/main/tests/functional/api/test_job_runtime_params.py @@ -131,11 +131,11 @@ def test_job_ignore_unprompted_vars(runtime_data, job_template_prompts, post, ad mock_job = mocker.MagicMock(spec=Job, id=968, **runtime_data) - with mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): - response = post(reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), runtime_data, admin_user, expect=201) - assert JobTemplate.create_unified_job.called - assert JobTemplate.create_unified_job.call_args == () + mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job) + mocker.patch('awx.api.serializers.JobSerializer.to_representation') + response = post(reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), runtime_data, admin_user, expect=201) + assert JobTemplate.create_unified_job.called + assert JobTemplate.create_unified_job.call_args == () # Check that job is serialized correctly job_id = response.data['job'] @@ -167,12 +167,12 @@ def test_job_accept_prompted_vars(runtime_data, job_template_prompts, post, admi mock_job = mocker.MagicMock(spec=Job, id=968, **runtime_data) - with mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): - response = post(reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), runtime_data, admin_user, expect=201) - assert JobTemplate.create_unified_job.called - called_with = data_to_internal(runtime_data) - JobTemplate.create_unified_job.assert_called_with(**called_with) + mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job) + mocker.patch('awx.api.serializers.JobSerializer.to_representation') + response = post(reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), runtime_data, admin_user, expect=201) + assert JobTemplate.create_unified_job.called + called_with = data_to_internal(runtime_data) + JobTemplate.create_unified_job.assert_called_with(**called_with) job_id = response.data['job'] assert job_id == 968 @@ -187,11 +187,11 @@ def test_job_accept_empty_tags(job_template_prompts, post, admin_user, mocker): mock_job = mocker.MagicMock(spec=Job, id=968) - with mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): - post(reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), {'job_tags': '', 'skip_tags': ''}, admin_user, expect=201) - assert JobTemplate.create_unified_job.called - assert JobTemplate.create_unified_job.call_args == ({'job_tags': '', 'skip_tags': ''},) + mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job) + mocker.patch('awx.api.serializers.JobSerializer.to_representation') + post(reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), {'job_tags': '', 'skip_tags': ''}, admin_user, expect=201) + assert JobTemplate.create_unified_job.called + assert JobTemplate.create_unified_job.call_args == ({'job_tags': '', 'skip_tags': ''},) mock_job.signal_start.assert_called_once() @@ -203,14 +203,14 @@ def test_slice_timeout_forks_need_int(job_template_prompts, post, admin_user, mo mock_job = mocker.MagicMock(spec=Job, id=968) - with mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): - response = post( - reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), {'timeout': '', 'job_slice_count': '', 'forks': ''}, admin_user, expect=400 - ) - assert 'forks' in response.data and response.data['forks'][0] == 'A valid integer is required.' - assert 'job_slice_count' in response.data and response.data['job_slice_count'][0] == 'A valid integer is required.' - assert 'timeout' in response.data and response.data['timeout'][0] == 'A valid integer is required.' + mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job) + mocker.patch('awx.api.serializers.JobSerializer.to_representation') + response = post( + reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), {'timeout': '', 'job_slice_count': '', 'forks': ''}, admin_user, expect=400 + ) + assert 'forks' in response.data and response.data['forks'][0] == 'A valid integer is required.' + assert 'job_slice_count' in response.data and response.data['job_slice_count'][0] == 'A valid integer is required.' + assert 'timeout' in response.data and response.data['timeout'][0] == 'A valid integer is required.' @pytest.mark.django_db @@ -244,12 +244,12 @@ def test_job_accept_prompted_vars_null(runtime_data, job_template_prompts_null, mock_job = mocker.MagicMock(spec=Job, id=968, **runtime_data) - with mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation'): - response = post(reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), runtime_data, rando, expect=201) - assert JobTemplate.create_unified_job.called - expected_call = data_to_internal(runtime_data) - assert JobTemplate.create_unified_job.call_args == (expected_call,) + mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job) + mocker.patch('awx.api.serializers.JobSerializer.to_representation') + response = post(reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), runtime_data, rando, expect=201) + assert JobTemplate.create_unified_job.called + expected_call = data_to_internal(runtime_data) + assert JobTemplate.create_unified_job.call_args == (expected_call,) job_id = response.data['job'] assert job_id == 968 @@ -641,18 +641,18 @@ def test_job_launch_unprompted_vars_with_survey(mocker, survey_spec_factory, job job_template.survey_spec = survey_spec_factory('survey_var') job_template.save() - with mocker.patch('awx.main.access.BaseAccess.check_license'): - mock_job = mocker.MagicMock(spec=Job, id=968, extra_vars={"job_launch_var": 3, "survey_var": 4}) - with mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation', return_value={}): - response = post( - reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), - dict(extra_vars={"job_launch_var": 3, "survey_var": 4}), - admin_user, - expect=201, - ) - assert JobTemplate.create_unified_job.called - assert JobTemplate.create_unified_job.call_args == ({'extra_vars': {'survey_var': 4}},) + mocker.patch('awx.main.access.BaseAccess.check_license') + mock_job = mocker.MagicMock(spec=Job, id=968, extra_vars={"job_launch_var": 3, "survey_var": 4}) + mocker.patch.object(JobTemplate, 'create_unified_job', return_value=mock_job) + mocker.patch('awx.api.serializers.JobSerializer.to_representation', return_value={}) + response = post( + reverse('api:job_template_launch', kwargs={'pk': job_template.pk}), + dict(extra_vars={"job_launch_var": 3, "survey_var": 4}), + admin_user, + expect=201, + ) + assert JobTemplate.create_unified_job.called + assert JobTemplate.create_unified_job.call_args == ({'extra_vars': {'survey_var': 4}},) job_id = response.data['job'] assert job_id == 968 @@ -670,22 +670,22 @@ def test_callback_accept_prompted_extra_var(mocker, survey_spec_factory, job_tem job_template.survey_spec = survey_spec_factory('survey_var') job_template.save() - with mocker.patch('awx.main.access.BaseAccess.check_license'): - mock_job = mocker.MagicMock(spec=Job, id=968, extra_vars={"job_launch_var": 3, "survey_var": 4}) - with mocker.patch.object(UnifiedJobTemplate, 'create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation', return_value={}): - with mocker.patch('awx.api.views.JobTemplateCallback.find_matching_hosts', return_value=[host]): - post( - reverse('api:job_template_callback', kwargs={'pk': job_template.pk}), - dict(extra_vars={"job_launch_var": 3, "survey_var": 4}, host_config_key="foo"), - admin_user, - expect=201, - format='json', - ) - assert UnifiedJobTemplate.create_unified_job.called - call_args = UnifiedJobTemplate.create_unified_job.call_args[1] - call_args.pop('_eager_fields', None) # internal purposes - assert call_args == {'extra_vars': {'survey_var': 4, 'job_launch_var': 3}, 'limit': 'single-host'} + mocker.patch('awx.main.access.BaseAccess.check_license') + mock_job = mocker.MagicMock(spec=Job, id=968, extra_vars={"job_launch_var": 3, "survey_var": 4}) + mocker.patch.object(UnifiedJobTemplate, 'create_unified_job', return_value=mock_job) + mocker.patch('awx.api.serializers.JobSerializer.to_representation', return_value={}) + mocker.patch('awx.api.views.JobTemplateCallback.find_matching_hosts', return_value=[host]) + post( + reverse('api:job_template_callback', kwargs={'pk': job_template.pk}), + dict(extra_vars={"job_launch_var": 3, "survey_var": 4}, host_config_key="foo"), + admin_user, + expect=201, + format='json', + ) + assert UnifiedJobTemplate.create_unified_job.called + call_args = UnifiedJobTemplate.create_unified_job.call_args[1] + call_args.pop('_eager_fields', None) # internal purposes + assert call_args == {'extra_vars': {'survey_var': 4, 'job_launch_var': 3}, 'limit': 'single-host'} mock_job.signal_start.assert_called_once() @@ -697,22 +697,22 @@ def test_callback_ignore_unprompted_extra_var(mocker, survey_spec_factory, job_t job_template.host_config_key = "foo" job_template.save() - with mocker.patch('awx.main.access.BaseAccess.check_license'): - mock_job = mocker.MagicMock(spec=Job, id=968, extra_vars={"job_launch_var": 3, "survey_var": 4}) - with mocker.patch.object(UnifiedJobTemplate, 'create_unified_job', return_value=mock_job): - with mocker.patch('awx.api.serializers.JobSerializer.to_representation', return_value={}): - with mocker.patch('awx.api.views.JobTemplateCallback.find_matching_hosts', return_value=[host]): - post( - reverse('api:job_template_callback', kwargs={'pk': job_template.pk}), - dict(extra_vars={"job_launch_var": 3, "survey_var": 4}, host_config_key="foo"), - admin_user, - expect=201, - format='json', - ) - assert UnifiedJobTemplate.create_unified_job.called - call_args = UnifiedJobTemplate.create_unified_job.call_args[1] - call_args.pop('_eager_fields', None) # internal purposes - assert call_args == {'limit': 'single-host'} + mocker.patch('awx.main.access.BaseAccess.check_license') + mock_job = mocker.MagicMock(spec=Job, id=968, extra_vars={"job_launch_var": 3, "survey_var": 4}) + mocker.patch.object(UnifiedJobTemplate, 'create_unified_job', return_value=mock_job) + mocker.patch('awx.api.serializers.JobSerializer.to_representation', return_value={}) + mocker.patch('awx.api.views.JobTemplateCallback.find_matching_hosts', return_value=[host]) + post( + reverse('api:job_template_callback', kwargs={'pk': job_template.pk}), + dict(extra_vars={"job_launch_var": 3, "survey_var": 4}, host_config_key="foo"), + admin_user, + expect=201, + format='json', + ) + assert UnifiedJobTemplate.create_unified_job.called + call_args = UnifiedJobTemplate.create_unified_job.call_args[1] + call_args.pop('_eager_fields', None) # internal purposes + assert call_args == {'limit': 'single-host'} mock_job.signal_start.assert_called_once() @@ -725,9 +725,9 @@ def test_callback_find_matching_hosts(mocker, get, job_template_prompts, admin_u job_template.save() host_with_alias = Host(name='localhost', inventory=job_template.inventory) host_with_alias.save() - with mocker.patch('awx.main.access.BaseAccess.check_license'): - r = get(reverse('api:job_template_callback', kwargs={'pk': job_template.pk}), user=admin_user, expect=200) - assert tuple(r.data['matching_hosts']) == ('localhost',) + mocker.patch('awx.main.access.BaseAccess.check_license') + r = get(reverse('api:job_template_callback', kwargs={'pk': job_template.pk}), user=admin_user, expect=200) + assert tuple(r.data['matching_hosts']) == ('localhost',) @pytest.mark.django_db @@ -738,6 +738,6 @@ def test_callback_extra_var_takes_priority_over_host_name(mocker, get, job_templ job_template.save() host_with_alias = Host(name='localhost', variables={'ansible_host': 'foobar'}, inventory=job_template.inventory) host_with_alias.save() - with mocker.patch('awx.main.access.BaseAccess.check_license'): - r = get(reverse('api:job_template_callback', kwargs={'pk': job_template.pk}), user=admin_user, expect=200) - assert not r.data['matching_hosts'] + mocker.patch('awx.main.access.BaseAccess.check_license') + r = get(reverse('api:job_template_callback', kwargs={'pk': job_template.pk}), user=admin_user, expect=200) + assert not r.data['matching_hosts'] diff --git a/awx/main/tests/functional/api/test_rbac_displays.py b/awx/main/tests/functional/api/test_rbac_displays.py index 8178da672c05..22d9ec9990a9 100644 --- a/awx/main/tests/functional/api/test_rbac_displays.py +++ b/awx/main/tests/functional/api/test_rbac_displays.py @@ -165,8 +165,8 @@ def _assert_one_in_list(self, data, sublist='direct_access'): def test_access_list_direct_access_capability(self, inventory, rando, get, mocker, mock_access_method): inventory.admin_role.members.add(rando) - with mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method): - response = get(reverse('api:inventory_access_list', kwargs={'pk': inventory.id}), rando) + mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method) + response = get(reverse('api:inventory_access_list', kwargs={'pk': inventory.id}), rando) mock_access_method.assert_called_once_with(inventory.admin_role, rando, 'members', **self.extra_kwargs) self._assert_one_in_list(response.data) @@ -174,8 +174,8 @@ def test_access_list_direct_access_capability(self, inventory, rando, get, mocke assert direct_access_list[0]['role']['user_capabilities']['unattach'] == 'foobar' def test_access_list_indirect_access_capability(self, inventory, organization, org_admin, get, mocker, mock_access_method): - with mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method): - response = get(reverse('api:inventory_access_list', kwargs={'pk': inventory.id}), org_admin) + mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method) + response = get(reverse('api:inventory_access_list', kwargs={'pk': inventory.id}), org_admin) mock_access_method.assert_called_once_with(organization.admin_role, org_admin, 'members', **self.extra_kwargs) self._assert_one_in_list(response.data, sublist='indirect_access') @@ -185,8 +185,8 @@ def test_access_list_indirect_access_capability(self, inventory, organization, o def test_access_list_team_direct_access_capability(self, inventory, team, team_member, get, mocker, mock_access_method): team.member_role.children.add(inventory.admin_role) - with mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method): - response = get(reverse('api:inventory_access_list', kwargs={'pk': inventory.id}), team_member) + mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method) + response = get(reverse('api:inventory_access_list', kwargs={'pk': inventory.id}), team_member) mock_access_method.assert_called_once_with(inventory.admin_role, team.member_role, 'parents', **self.extra_kwargs) self._assert_one_in_list(response.data) @@ -198,8 +198,8 @@ def test_access_list_team_direct_access_capability(self, inventory, team, team_m def test_team_roles_unattach(mocker, team, team_member, inventory, mock_access_method, get): team.member_role.children.add(inventory.admin_role) - with mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method): - response = get(reverse('api:team_roles_list', kwargs={'pk': team.id}), team_member) + mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method) + response = get(reverse('api:team_roles_list', kwargs={'pk': team.id}), team_member) # Did we assess whether team_member can remove team's permission to the inventory? mock_access_method.assert_called_once_with(inventory.admin_role, team.member_role, 'parents', skip_sub_obj_read_check=True, data={}) @@ -212,8 +212,8 @@ def test_user_roles_unattach(mocker, organization, alice, bob, mock_access_metho organization.member_role.members.add(alice) organization.member_role.members.add(bob) - with mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method): - response = get(reverse('api:user_roles_list', kwargs={'pk': alice.id}), bob) + mocker.patch.object(access_registry[Role], 'can_unattach', mock_access_method) + response = get(reverse('api:user_roles_list', kwargs={'pk': alice.id}), bob) # Did we assess whether bob can remove alice's permission to the inventory? mock_access_method.assert_called_once_with(organization.member_role, alice, 'members', skip_sub_obj_read_check=True, data={}) diff --git a/awx/main/tests/functional/commands/test_commands.py b/awx/main/tests/functional/commands/test_commands.py index 69f584c2871b..f62dac02064d 100644 --- a/awx/main/tests/functional/commands/test_commands.py +++ b/awx/main/tests/functional/commands/test_commands.py @@ -43,9 +43,9 @@ def run_command(name, *args, **options): ], ) def test_update_password_command(mocker, username, password, expected, changed): - with mocker.patch.object(UpdatePassword, 'update_password', return_value=changed): - result, stdout, stderr = run_command('update_password', username=username, password=password) - if result is None: - assert stdout == expected - else: - assert str(result) == expected + mocker.patch.object(UpdatePassword, 'update_password', return_value=changed) + result, stdout, stderr = run_command('update_password', username=username, password=password) + if result is None: + assert stdout == expected + else: + assert str(result) == expected diff --git a/awx/main/tests/functional/models/test_context_managers.py b/awx/main/tests/functional/models/test_context_managers.py index 271f88b21f57..7dfc0da11729 100644 --- a/awx/main/tests/functional/models/test_context_managers.py +++ b/awx/main/tests/functional/models/test_context_managers.py @@ -21,13 +21,13 @@ class TestComputedFields: def test_computed_fields_normal_use(self, mocker, inventory): job = Job.objects.create(name='fake-job', inventory=inventory) with immediate_on_commit(): - with mocker.patch.object(update_inventory_computed_fields, 'delay'): - job.delete() - update_inventory_computed_fields.delay.assert_called_once_with(inventory.id) + mocker.patch.object(update_inventory_computed_fields, 'delay') + job.delete() + update_inventory_computed_fields.delay.assert_called_once_with(inventory.id) def test_disable_computed_fields(self, mocker, inventory): job = Job.objects.create(name='fake-job', inventory=inventory) with disable_computed_fields(): - with mocker.patch.object(update_inventory_computed_fields, 'delay'): - job.delete() - update_inventory_computed_fields.delay.assert_not_called() + mocker.patch.object(update_inventory_computed_fields, 'delay') + job.delete() + update_inventory_computed_fields.delay.assert_not_called() diff --git a/awx/main/tests/functional/task_management/test_rampart_groups.py b/awx/main/tests/functional/task_management/test_rampart_groups.py index 48ea9edb0805..f4bb81f405a6 100644 --- a/awx/main/tests/functional/task_management/test_rampart_groups.py +++ b/awx/main/tests/functional/task_management/test_rampart_groups.py @@ -21,13 +21,13 @@ def test_multi_group_basic_job_launch(instance_factory, controlplane_instance_gr j2 = create_job(objects2.job_template) with mock.patch('awx.main.models.Job.task_impact', new_callable=mock.PropertyMock) as mock_task_impact: mock_task_impact.return_value = 500 - with mocker.patch("awx.main.scheduler.TaskManager.start_task"): - TaskManager().schedule() - TaskManager.start_task.assert_has_calls([mock.call(j1, ig1, i1), mock.call(j2, ig2, i2)]) + mocker.patch("awx.main.scheduler.TaskManager.start_task") + TaskManager().schedule() + TaskManager.start_task.assert_has_calls([mock.call(j1, ig1, i1), mock.call(j2, ig2, i2)]) @pytest.mark.django_db -def test_multi_group_with_shared_dependency(instance_factory, controlplane_instance_group, mocker, instance_group_factory, job_template_factory): +def test_multi_group_with_shared_dependency(instance_factory, controlplane_instance_group, instance_group_factory, job_template_factory): i1 = instance_factory("i1") i2 = instance_factory("i2") ig1 = instance_group_factory("ig1", instances=[i1]) @@ -50,7 +50,7 @@ def test_multi_group_with_shared_dependency(instance_factory, controlplane_insta objects2 = job_template_factory('jt2', organization=objects1.organization, project=p, inventory='inv2', credential='cred2') objects2.job_template.instance_groups.add(ig2) j2 = create_job(objects2.job_template, dependencies_processed=False) - with mocker.patch("awx.main.scheduler.TaskManager.start_task"): + with mock.patch("awx.main.scheduler.TaskManager.start_task"): DependencyManager().schedule() TaskManager().schedule() pu = p.project_updates.first() @@ -73,10 +73,10 @@ def test_workflow_job_no_instancegroup(workflow_job_template_factory, controlpla wfj = wfjt.create_unified_job() wfj.status = "pending" wfj.save() - with mocker.patch("awx.main.scheduler.TaskManager.start_task"): - TaskManager().schedule() - TaskManager.start_task.assert_called_once_with(wfj, None, None) - assert wfj.instance_group is None + mocker.patch("awx.main.scheduler.TaskManager.start_task") + TaskManager().schedule() + TaskManager.start_task.assert_called_once_with(wfj, None, None) + assert wfj.instance_group is None @pytest.mark.django_db diff --git a/awx/main/tests/functional/task_management/test_scheduler.py b/awx/main/tests/functional/task_management/test_scheduler.py index 743609c760b4..32651311d83f 100644 --- a/awx/main/tests/functional/task_management/test_scheduler.py +++ b/awx/main/tests/functional/task_management/test_scheduler.py @@ -16,9 +16,9 @@ def test_single_job_scheduler_launch(hybrid_instance, controlplane_instance_grou instance = controlplane_instance_group.instances.all()[0] objects = job_template_factory('jt', organization='org1', project='proj', inventory='inv', credential='cred') j = create_job(objects.job_template) - with mocker.patch("awx.main.scheduler.TaskManager.start_task"): - TaskManager().schedule() - TaskManager.start_task.assert_called_once_with(j, controlplane_instance_group, instance) + mocker.patch("awx.main.scheduler.TaskManager.start_task") + TaskManager().schedule() + TaskManager.start_task.assert_called_once_with(j, controlplane_instance_group, instance) @pytest.mark.django_db diff --git a/awx/main/tests/functional/test_named_url.py b/awx/main/tests/functional/test_named_url.py index 54e3b96eddb9..557fdb8e9276 100644 --- a/awx/main/tests/functional/test_named_url.py +++ b/awx/main/tests/functional/test_named_url.py @@ -1,8 +1,6 @@ # -*- coding: utf-8 -*- import pytest -from django.conf import settings - from awx.api.versioning import reverse from awx.main.middleware import URLModificationMiddleware from awx.main.models import ( # noqa @@ -121,7 +119,7 @@ def test_notification_template(get, admin_user): @pytest.mark.django_db -def test_instance(get, admin_user): +def test_instance(get, admin_user, settings): test_instance = Instance.objects.create(uuid=settings.SYSTEM_UUID, hostname="localhost", capacity=100) url = reverse('api:instance_detail', kwargs={'pk': test_instance.pk}) response = get(url, user=admin_user, expect=200) @@ -205,3 +203,65 @@ def test_403_vs_404(get): get(f'/api/v2/users/{cindy.pk}/', expect=401) get('/api/v2/users/cindy/', expect=404) + + +@pytest.mark.django_db +class TestConvertNamedUrl: + @pytest.mark.parametrize( + "url", + ( + "/api/", + "/api/v2/", + "/api/v2/hosts/", + "/api/v2/hosts/1/", + "/api/v2/organizations/1/inventories/", + "/api/foo/", + "/api/foo/v2/", + "/api/foo/v2/organizations/", + "/api/foo/v2/organizations/1/", + "/api/foo/v2/organizations/1/inventories/", + "/api/foobar/", + "/api/foobar/v2/", + "/api/foobar/v2/organizations/", + "/api/foobar/v2/organizations/1/", + "/api/foobar/v2/organizations/1/inventories/", + "/api/foobar/v2/organizations/1/inventories/", + ), + ) + def test_noop(self, url, settings): + settings.OPTIONAL_API_URLPATTERN_PREFIX = '' + assert URLModificationMiddleware._convert_named_url(url) == url + + settings.OPTIONAL_API_URLPATTERN_PREFIX = 'foo' + assert URLModificationMiddleware._convert_named_url(url) == url + + def test_named_org(self): + test_org = Organization.objects.create(name='test_org') + + assert URLModificationMiddleware._convert_named_url('/api/v2/organizations/test_org/') == f'/api/v2/organizations/{test_org.pk}/' + + def test_named_org_optional_api_urlpattern_prefix_interaction(self, settings): + settings.OPTIONAL_API_URLPATTERN_PREFIX = 'bar' + test_org = Organization.objects.create(name='test_org') + + assert URLModificationMiddleware._convert_named_url('/api/bar/v2/organizations/test_org/') == f'/api/bar/v2/organizations/{test_org.pk}/' + + @pytest.mark.parametrize("prefix", ['', 'bar']) + def test_named_org_not_found(self, prefix, settings): + settings.OPTIONAL_API_URLPATTERN_PREFIX = prefix + if prefix: + prefix += '/' + + assert URLModificationMiddleware._convert_named_url(f'/api/{prefix}v2/organizations/does-not-exist/') == f'/api/{prefix}v2/organizations/0/' + + @pytest.mark.parametrize("prefix", ['', 'bar']) + def test_named_sub_resource(self, prefix, settings): + settings.OPTIONAL_API_URLPATTERN_PREFIX = prefix + test_org = Organization.objects.create(name='test_org') + if prefix: + prefix += '/' + + assert ( + URLModificationMiddleware._convert_named_url(f'/api/{prefix}v2/organizations/test_org/inventories/') + == f'/api/{prefix}v2/organizations/{test_org.pk}/inventories/' + ) diff --git a/awx/main/tests/functional/test_rbac_api.py b/awx/main/tests/functional/test_rbac_api.py index e1e76e981e01..8eb26177a42f 100644 --- a/awx/main/tests/functional/test_rbac_api.py +++ b/awx/main/tests/functional/test_rbac_api.py @@ -187,7 +187,7 @@ def test_remove_role_from_user(role, post, admin): @pytest.mark.django_db -@override_settings(ANSIBLE_BASE_ALLOW_TEAM_ORG_ADMIN=True) +@override_settings(ANSIBLE_BASE_ALLOW_TEAM_ORG_ADMIN=True, ANSIBLE_BASE_ALLOW_TEAM_ORG_MEMBER=True) def test_get_teams_roles_list(get, team, organization, admin): team.member_role.children.add(organization.admin_role) url = reverse('api:team_roles_list', kwargs={'pk': team.id}) diff --git a/awx/main/tests/unit/api/serializers/test_job_template_serializers.py b/awx/main/tests/unit/api/serializers/test_job_template_serializers.py index 51e64fd753a1..0a9e31b91cbd 100644 --- a/awx/main/tests/unit/api/serializers/test_job_template_serializers.py +++ b/awx/main/tests/unit/api/serializers/test_job_template_serializers.py @@ -76,15 +76,15 @@ def test_callback_absent(self, get_related_mock_and_run, job_template): class TestJobTemplateSerializerGetSummaryFields: def test_survey_spec_exists(self, test_get_summary_fields, mocker, job_template): job_template.survey_spec = {'name': 'blah', 'description': 'blah blah'} - with mocker.patch.object(JobTemplateSerializer, '_recent_jobs') as mock_rj: - mock_rj.return_value = [] - test_get_summary_fields(JobTemplateSerializer, job_template, 'survey') + mock_rj = mocker.patch.object(JobTemplateSerializer, '_recent_jobs') + mock_rj.return_value = [] + test_get_summary_fields(JobTemplateSerializer, job_template, 'survey') def test_survey_spec_absent(self, get_summary_fields_mock_and_run, mocker, job_template): job_template.survey_spec = None - with mocker.patch.object(JobTemplateSerializer, '_recent_jobs') as mock_rj: - mock_rj.return_value = [] - summary = get_summary_fields_mock_and_run(JobTemplateSerializer, job_template) + mock_rj = mocker.patch.object(JobTemplateSerializer, '_recent_jobs') + mock_rj.return_value = [] + summary = get_summary_fields_mock_and_run(JobTemplateSerializer, job_template) assert 'survey' not in summary def test_copy_edit_standard(self, mocker, job_template_factory): @@ -107,10 +107,10 @@ def test_copy_edit_standard(self, mocker, job_template_factory): view.kwargs = {} serializer.context['view'] = view - with mocker.patch("awx.api.serializers.role_summary_fields_generator", return_value='Can eat pie'): - with mocker.patch("awx.main.access.JobTemplateAccess.can_change", return_value='foobar'): - with mocker.patch("awx.main.access.JobTemplateAccess.can_copy", return_value='foo'): - response = serializer.get_summary_fields(jt_obj) + mocker.patch("awx.api.serializers.role_summary_fields_generator", return_value='Can eat pie') + mocker.patch("awx.main.access.JobTemplateAccess.can_change", return_value='foobar') + mocker.patch("awx.main.access.JobTemplateAccess.can_copy", return_value='foo') + response = serializer.get_summary_fields(jt_obj) assert response['user_capabilities']['copy'] == 'foo' assert response['user_capabilities']['edit'] == 'foobar' diff --git a/awx/main/tests/unit/api/serializers/test_workflow_serializers.py b/awx/main/tests/unit/api/serializers/test_workflow_serializers.py index 9e7fe51344e0..218395dc6c62 100644 --- a/awx/main/tests/unit/api/serializers/test_workflow_serializers.py +++ b/awx/main/tests/unit/api/serializers/test_workflow_serializers.py @@ -189,8 +189,8 @@ def test_use_db_answer(self, jt, mocker): serializer = WorkflowJobTemplateNodeSerializer() wfjt = WorkflowJobTemplate.objects.create(name='fake-wfjt') serializer.instance = WorkflowJobTemplateNode(workflow_job_template=wfjt, unified_job_template=jt, extra_data={'var1': '$encrypted$foooooo'}) - with mocker.patch('awx.main.models.mixins.decrypt_value', return_value='foo'): - attrs = serializer.validate({'unified_job_template': jt, 'workflow_job_template': wfjt, 'extra_data': {'var1': '$encrypted$'}}) + mocker.patch('awx.main.models.mixins.decrypt_value', return_value='foo') + attrs = serializer.validate({'unified_job_template': jt, 'workflow_job_template': wfjt, 'extra_data': {'var1': '$encrypted$'}}) assert 'survey_passwords' in attrs assert 'var1' in attrs['survey_passwords'] assert attrs['extra_data']['var1'] == '$encrypted$foooooo' diff --git a/awx/main/tests/unit/api/test_generics.py b/awx/main/tests/unit/api/test_generics.py index 6f0982bfd847..ea8cb388786c 100644 --- a/awx/main/tests/unit/api/test_generics.py +++ b/awx/main/tests/unit/api/test_generics.py @@ -191,16 +191,16 @@ def mock_view(self, parent=None): def test_parent_access_check_failed(self, mocker, mock_organization): mock_access = mocker.MagicMock(__name__='for logger', return_value=False) - with mocker.patch('awx.main.access.BaseAccess.can_read', mock_access): - with pytest.raises(PermissionDenied): - self.mock_view(parent=mock_organization).check_permissions(self.mock_request()) - mock_access.assert_called_once_with(mock_organization) + mocker.patch('awx.main.access.BaseAccess.can_read', mock_access) + with pytest.raises(PermissionDenied): + self.mock_view(parent=mock_organization).check_permissions(self.mock_request()) + mock_access.assert_called_once_with(mock_organization) def test_parent_access_check_worked(self, mocker, mock_organization): mock_access = mocker.MagicMock(__name__='for logger', return_value=True) - with mocker.patch('awx.main.access.BaseAccess.can_read', mock_access): - self.mock_view(parent=mock_organization).check_permissions(self.mock_request()) - mock_access.assert_called_once_with(mock_organization) + mocker.patch('awx.main.access.BaseAccess.can_read', mock_access) + self.mock_view(parent=mock_organization).check_permissions(self.mock_request()) + mock_access.assert_called_once_with(mock_organization) def test_related_search_reverse_FK_field(): diff --git a/awx/main/tests/unit/api/test_views.py b/awx/main/tests/unit/api/test_views.py index edb60351d0f8..503ad6e854dd 100644 --- a/awx/main/tests/unit/api/test_views.py +++ b/awx/main/tests/unit/api/test_views.py @@ -66,7 +66,7 @@ def test_inherited_mixin_unattach(self): mock_request = mock.MagicMock() super(JobTemplateLabelList, view).unattach(mock_request, None, None) - assert mixin_unattach.called_with(mock_request, None, None) + mixin_unattach.assert_called_with(mock_request, None, None) class TestInventoryInventorySourcesUpdate: @@ -108,15 +108,16 @@ def exclude(self, **kwargs): mock_request = mocker.MagicMock() mock_request.user.can_access.return_value = can_access - with mocker.patch.object(InventoryInventorySourcesUpdate, 'get_object', return_value=obj): - with mocker.patch.object(InventoryInventorySourcesUpdate, 'get_serializer_context', return_value=None): - with mocker.patch('awx.api.serializers.InventoryUpdateDetailSerializer') as serializer_class: - serializer = serializer_class.return_value - serializer.to_representation.return_value = {} + mocker.patch.object(InventoryInventorySourcesUpdate, 'get_object', return_value=obj) + mocker.patch.object(InventoryInventorySourcesUpdate, 'get_serializer_context', return_value=None) + serializer_class = mocker.patch('awx.api.serializers.InventoryUpdateDetailSerializer') - view = InventoryInventorySourcesUpdate() - response = view.post(mock_request) - assert response.data == expected + serializer = serializer_class.return_value + serializer.to_representation.return_value = {} + + view = InventoryInventorySourcesUpdate() + response = view.post(mock_request) + assert response.data == expected class TestSurveySpecValidation: diff --git a/awx/main/tests/unit/models/test_workflow_unit.py b/awx/main/tests/unit/models/test_workflow_unit.py index dc01c3301f6d..7ac2009403de 100644 --- a/awx/main/tests/unit/models/test_workflow_unit.py +++ b/awx/main/tests/unit/models/test_workflow_unit.py @@ -155,35 +155,35 @@ def test_node_getter_and_setters(): class TestWorkflowJobCreate: def test_create_no_prompts(self, wfjt_node_no_prompts, workflow_job_unit, mocker): mock_create = mocker.MagicMock() - with mocker.patch('awx.main.models.WorkflowJobNode.objects.create', mock_create): - wfjt_node_no_prompts.create_workflow_job_node(workflow_job=workflow_job_unit) - mock_create.assert_called_once_with( - all_parents_must_converge=False, - extra_data={}, - survey_passwords={}, - char_prompts=wfjt_node_no_prompts.char_prompts, - inventory=None, - unified_job_template=wfjt_node_no_prompts.unified_job_template, - workflow_job=workflow_job_unit, - identifier=mocker.ANY, - execution_environment=None, - ) + mocker.patch('awx.main.models.WorkflowJobNode.objects.create', mock_create) + wfjt_node_no_prompts.create_workflow_job_node(workflow_job=workflow_job_unit) + mock_create.assert_called_once_with( + all_parents_must_converge=False, + extra_data={}, + survey_passwords={}, + char_prompts=wfjt_node_no_prompts.char_prompts, + inventory=None, + unified_job_template=wfjt_node_no_prompts.unified_job_template, + workflow_job=workflow_job_unit, + identifier=mocker.ANY, + execution_environment=None, + ) def test_create_with_prompts(self, wfjt_node_with_prompts, workflow_job_unit, credential, mocker): mock_create = mocker.MagicMock() - with mocker.patch('awx.main.models.WorkflowJobNode.objects.create', mock_create): - wfjt_node_with_prompts.create_workflow_job_node(workflow_job=workflow_job_unit) - mock_create.assert_called_once_with( - all_parents_must_converge=False, - extra_data={}, - survey_passwords={}, - char_prompts=wfjt_node_with_prompts.char_prompts, - inventory=wfjt_node_with_prompts.inventory, - unified_job_template=wfjt_node_with_prompts.unified_job_template, - workflow_job=workflow_job_unit, - identifier=mocker.ANY, - execution_environment=None, - ) + mocker.patch('awx.main.models.WorkflowJobNode.objects.create', mock_create) + wfjt_node_with_prompts.create_workflow_job_node(workflow_job=workflow_job_unit) + mock_create.assert_called_once_with( + all_parents_must_converge=False, + extra_data={}, + survey_passwords={}, + char_prompts=wfjt_node_with_prompts.char_prompts, + inventory=wfjt_node_with_prompts.inventory, + unified_job_template=wfjt_node_with_prompts.unified_job_template, + workflow_job=workflow_job_unit, + identifier=mocker.ANY, + execution_environment=None, + ) @pytest.mark.django_db diff --git a/awx/main/tests/unit/notifications/test_awssns.py b/awx/main/tests/unit/notifications/test_awssns.py new file mode 100644 index 000000000000..0d18821fe3e3 --- /dev/null +++ b/awx/main/tests/unit/notifications/test_awssns.py @@ -0,0 +1,26 @@ +from unittest import mock +from django.core.mail.message import EmailMessage + +import awx.main.notifications.awssns_backend as awssns_backend + + +def test_send_messages(): + with mock.patch('awx.main.notifications.awssns_backend.AWSSNSBackend._sns_publish') as sns_publish_mock: + aws_region = 'us-east-1' + sns_topic = f"arn:aws:sns:{aws_region}:111111111111:topic-mock" + backend = awssns_backend.AWSSNSBackend(aws_region=aws_region, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None) + message = EmailMessage( + 'test subject', + {'body': 'test body'}, + [], + [ + sns_topic, + ], + ) + sent_messages = backend.send_messages( + [ + message, + ] + ) + sns_publish_mock.assert_called_once_with(topic_arn=sns_topic, message=message.body) + assert sent_messages == 1 diff --git a/awx/main/tests/unit/test_tasks.py b/awx/main/tests/unit/test_tasks.py index e5b8fbf79e6c..10ed00b186a9 100644 --- a/awx/main/tests/unit/test_tasks.py +++ b/awx/main/tests/unit/test_tasks.py @@ -137,10 +137,10 @@ def test_send_notifications_not_list(): def test_send_notifications_job_id(mocker): - with mocker.patch('awx.main.models.UnifiedJob.objects.get'): - system.send_notifications([], job_id=1) - assert UnifiedJob.objects.get.called - assert UnifiedJob.objects.get.called_with(id=1) + mocker.patch('awx.main.models.UnifiedJob.objects.get') + system.send_notifications([], job_id=1) + assert UnifiedJob.objects.get.called + assert UnifiedJob.objects.get.called_with(id=1) @mock.patch('awx.main.models.UnifiedJob.objects.get') diff --git a/awx/main/tests/unit/utils/test_reload.py b/awx/main/tests/unit/utils/test_reload.py index 5f8c7b95e35b..2b41a5fef0c1 100644 --- a/awx/main/tests/unit/utils/test_reload.py +++ b/awx/main/tests/unit/utils/test_reload.py @@ -7,15 +7,15 @@ def test_produce_supervisor_command(mocker): mock_process = mocker.MagicMock() mock_process.communicate = communicate_mock Popen_mock = mocker.MagicMock(return_value=mock_process) - with mocker.patch.object(reload.subprocess, 'Popen', Popen_mock): - reload.supervisor_service_command("restart") - reload.subprocess.Popen.assert_called_once_with( - [ - 'supervisorctl', - 'restart', - 'tower-processes:*', - ], - stderr=-1, - stdin=-1, - stdout=-1, - ) + mocker.patch.object(reload.subprocess, 'Popen', Popen_mock) + reload.supervisor_service_command("restart") + reload.subprocess.Popen.assert_called_once_with( + [ + 'supervisorctl', + 'restart', + 'tower-processes:*', + ], + stderr=-1, + stdin=-1, + stdout=-1, + ) diff --git a/awx/main/utils/handlers.py b/awx/main/utils/handlers.py index 15343463e8d3..4def0b6ba094 100644 --- a/awx/main/utils/handlers.py +++ b/awx/main/utils/handlers.py @@ -2,9 +2,11 @@ # All Rights Reserved. # Python +import base64 import logging import sys import traceback +import os from datetime import datetime # Django @@ -15,6 +17,15 @@ # AWX from awx.main.exceptions import PostRunError +# OTEL +from opentelemetry._logs import set_logger_provider +from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter as OTLPGrpcLogExporter +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter as OTLPHttpLogExporter + +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.sdk.resources import Resource + class RSysLogHandler(logging.handlers.SysLogHandler): append_nul = False @@ -133,3 +144,39 @@ def format(self, record): pass else: ColorHandler = logging.StreamHandler + + +class OTLPHandler(LoggingHandler): + def __init__(self, endpoint=None, protocol='grpc', service_name=None, instance_id=None, auth=None, username=None, password=None): + if not endpoint: + raise ValueError("endpoint required") + + if auth == 'basic' and (username is None or password is None): + raise ValueError("auth type basic requires username and passsword parameters") + + self.endpoint = endpoint + self.service_name = service_name or (sys.argv[1] if len(sys.argv) > 1 else (sys.argv[0] or 'unknown_service')) + self.instance_id = instance_id or os.uname().nodename + + logger_provider = LoggerProvider( + resource=Resource.create( + { + "service.name": self.service_name, + "service.instance.id": self.instance_id, + } + ), + ) + set_logger_provider(logger_provider) + + headers = {} + if auth == 'basic': + secret = f'{username}:{password}' + headers['Authorization'] = "Basic " + base64.b64encode(secret.encode()).decode() + + if protocol == 'grpc': + otlp_exporter = OTLPGrpcLogExporter(endpoint=self.endpoint, insecure=True, headers=headers) + elif protocol == 'http': + otlp_exporter = OTLPHttpLogExporter(endpoint=self.endpoint, headers=headers) + logger_provider.add_log_record_processor(BatchLogRecordProcessor(otlp_exporter)) + + super().__init__(level=logging.NOTSET, logger_provider=logger_provider) diff --git a/awx/main/wsrelay.py b/awx/main/wsrelay.py index a4c94bd7e60b..bedf68efb030 100644 --- a/awx/main/wsrelay.py +++ b/awx/main/wsrelay.py @@ -285,8 +285,6 @@ async def cleanup_offline_host(self, hostname): except asyncio.CancelledError: # Handle the case where the task was already cancelled by the time we got here. pass - except Exception as e: - logger.warning(f"Failed to cancel relay connection for {hostname}: {e}") del self.relay_connections[hostname] @@ -297,8 +295,6 @@ async def cleanup_offline_host(self, hostname): self.stats_mgr.delete_remote_host_stats(hostname) except KeyError: pass - except Exception as e: - logger.warning(f"Failed to delete stats for {hostname}: {e}") async def run(self): event_loop = asyncio.get_running_loop() @@ -306,7 +302,6 @@ async def run(self): self.stats_mgr = RelayWebsocketStatsManager(event_loop, self.local_hostname) self.stats_mgr.start() - # Set up a pg_notify consumer for allowing web nodes to "provision" and "deprovision" themselves gracefully. database_conf = deepcopy(settings.DATABASES['default']) database_conf['OPTIONS'] = deepcopy(database_conf.get('OPTIONS', {})) @@ -318,79 +313,54 @@ async def run(self): if 'PASSWORD' in database_conf: database_conf['OPTIONS']['password'] = database_conf.pop('PASSWORD') - task = None + async_conn = await psycopg.AsyncConnection.connect( + dbname=database_conf['NAME'], + host=database_conf['HOST'], + user=database_conf['USER'], + port=database_conf['PORT'], + **database_conf.get("OPTIONS", {}), + ) - # Managing the async_conn here so that we can close it if we need to restart the connection - async_conn = None + await async_conn.set_autocommit(True) + on_ws_heartbeat_task = event_loop.create_task(self.on_ws_heartbeat(async_conn)) # Establishes a websocket connection to /websocket/relay on all API servers - try: - while True: - if not task or task.done(): - try: - # Try to close the connection if it's open - if async_conn: - try: - await async_conn.close() - except Exception as e: - logger.warning(f"Failed to close connection to database for pg_notify: {e}") - - # and re-establish the connection - async_conn = await psycopg.AsyncConnection.connect( - dbname=database_conf['NAME'], - host=database_conf['HOST'], - user=database_conf['USER'], - port=database_conf['PORT'], - **database_conf.get("OPTIONS", {}), - ) - await async_conn.set_autocommit(True) - - # before creating the task that uses the connection - task = event_loop.create_task(self.on_ws_heartbeat(async_conn), name="on_ws_heartbeat") - logger.info("Creating `on_ws_heartbeat` task in event loop.") - - except Exception as e: - logger.warning(f"Failed to connect to database for pg_notify: {e}") - - future_remote_hosts = self.known_hosts.keys() - current_remote_hosts = self.relay_connections.keys() - deleted_remote_hosts = set(current_remote_hosts) - set(future_remote_hosts) - new_remote_hosts = set(future_remote_hosts) - set(current_remote_hosts) - - # This loop handles if we get an advertisement from a host we already know about but - # the advertisement has a different IP than we are currently connected to. - for hostname, address in self.known_hosts.items(): - if hostname not in self.relay_connections: - # We've picked up a new hostname that we don't know about yet. - continue + while True: + if on_ws_heartbeat_task.done(): + raise Exception("on_ws_heartbeat_task has exited") + + future_remote_hosts = self.known_hosts.keys() + current_remote_hosts = self.relay_connections.keys() + deleted_remote_hosts = set(current_remote_hosts) - set(future_remote_hosts) + new_remote_hosts = set(future_remote_hosts) - set(current_remote_hosts) + + # This loop handles if we get an advertisement from a host we already know about but + # the advertisement has a different IP than we are currently connected to. + for hostname, address in self.known_hosts.items(): + if hostname not in self.relay_connections: + # We've picked up a new hostname that we don't know about yet. + continue - if address != self.relay_connections[hostname].remote_host: - deleted_remote_hosts.add(hostname) - new_remote_hosts.add(hostname) + if address != self.relay_connections[hostname].remote_host: + deleted_remote_hosts.add(hostname) + new_remote_hosts.add(hostname) - # Delete any hosts with closed connections - for hostname, relay_conn in self.relay_connections.items(): - if not relay_conn.connected: - deleted_remote_hosts.add(hostname) + # Delete any hosts with closed connections + for hostname, relay_conn in self.relay_connections.items(): + if not relay_conn.connected: + deleted_remote_hosts.add(hostname) - if deleted_remote_hosts: - logger.info(f"Removing {deleted_remote_hosts} from websocket broadcast list") - await asyncio.gather(*[self.cleanup_offline_host(h) for h in deleted_remote_hosts]) + if deleted_remote_hosts: + logger.info(f"Removing {deleted_remote_hosts} from websocket broadcast list") + await asyncio.gather(*[self.cleanup_offline_host(h) for h in deleted_remote_hosts]) - if new_remote_hosts: - logger.info(f"Adding {new_remote_hosts} to websocket broadcast list") + if new_remote_hosts: + logger.info(f"Adding {new_remote_hosts} to websocket broadcast list") - for h in new_remote_hosts: - stats = self.stats_mgr.new_remote_host_stats(h) - relay_connection = WebsocketRelayConnection(name=self.local_hostname, stats=stats, remote_host=self.known_hosts[h]) - relay_connection.start() - self.relay_connections[h] = relay_connection + for h in new_remote_hosts: + stats = self.stats_mgr.new_remote_host_stats(h) + relay_connection = WebsocketRelayConnection(name=self.local_hostname, stats=stats, remote_host=self.known_hosts[h]) + relay_connection.start() + self.relay_connections[h] = relay_connection - await asyncio.sleep(settings.BROADCAST_WEBSOCKET_NEW_INSTANCE_POLL_RATE_SECONDS) - finally: - if async_conn: - logger.info("Shutting down db connection for wsrelay.") - try: - await async_conn.close() - except Exception as e: - logger.info(f"Failed to close connection to database for pg_notify: {e}") + await asyncio.sleep(settings.BROADCAST_WEBSOCKET_NEW_INSTANCE_POLL_RATE_SECONDS) diff --git a/awx/settings/defaults.py b/awx/settings/defaults.py index 9a144777bb10..d0fd7b115cad 100644 --- a/awx/settings/defaults.py +++ b/awx/settings/defaults.py @@ -492,6 +492,7 @@ 'cleanup_images': {'task': 'awx.main.tasks.system.cleanup_images_and_files', 'schedule': timedelta(hours=3)}, 'cleanup_host_metrics': {'task': 'awx.main.tasks.host_metrics.cleanup_host_metrics', 'schedule': timedelta(hours=3, minutes=30)}, 'host_metric_summary_monthly': {'task': 'awx.main.tasks.host_metrics.host_metric_summary_monthly', 'schedule': timedelta(hours=4)}, + 'periodic_resource_sync': {'task': 'awx.main.tasks.system.periodic_resource_sync', 'schedule': timedelta(minutes=15)}, } # Django Caching Configuration @@ -656,6 +657,10 @@ # Automatically remove nodes that have missed their heartbeats after some time AWX_AUTO_DEPROVISION_INSTANCES = False +# If False, do not allow creation of resources that are shared with the platform ingress +# e.g. organizations, teams, and users +ALLOW_LOCAL_RESOURCE_MANAGEMENT = True + # Enable Pendo on the UI, possible values are 'off', 'anonymous', and 'detailed' # Note: This setting may be overridden by database settings. PENDO_TRACKING_STATE = "off" @@ -880,6 +885,7 @@ 'address': '/var/run/awx-rsyslog/rsyslog.sock', 'filters': ['external_log_enabled', 'dynamic_level_filter', 'guid'], }, + 'otel': {'class': 'logging.NullHandler'}, }, 'loggers': { 'django': {'handlers': ['console']}, diff --git a/awx/sso/conf.py b/awx/sso/conf.py index 655640d9d765..03640fccd8ae 100644 --- a/awx/sso/conf.py +++ b/awx/sso/conf.py @@ -92,1568 +92,1576 @@ def __call__(self): ] ) -############################################################################### -# AUTHENTICATION BACKENDS DYNAMIC SETTING -############################################################################### - -register( - 'AUTHENTICATION_BACKENDS', - field_class=AuthenticationBackendsField, - label=_('Authentication Backends'), - help_text=_('List of authentication backends that are enabled based on license features and other authentication settings.'), - read_only=True, - depends_on=AuthenticationBackendsField.get_all_required_settings(), - category=_('Authentication'), - category_slug='authentication', -) +if settings.ALLOW_LOCAL_RESOURCE_MANAGEMENT: + ############################################################################### + # AUTHENTICATION BACKENDS DYNAMIC SETTING + ############################################################################### -register( - 'SOCIAL_AUTH_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('Social Auth Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('Authentication'), - category_slug='authentication', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) + register( + 'AUTHENTICATION_BACKENDS', + field_class=AuthenticationBackendsField, + label=_('Authentication Backends'), + help_text=_('List of authentication backends that are enabled based on license features and other authentication settings.'), + read_only=True, + depends_on=AuthenticationBackendsField.get_all_required_settings(), + category=_('Authentication'), + category_slug='authentication', + ) -register( - 'SOCIAL_AUTH_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('Social Auth Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('Authentication'), - category_slug='authentication', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('Social Auth Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('Authentication'), + category_slug='authentication', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_USER_FIELDS', - field_class=fields.StringListField, - allow_null=True, - default=None, - label=_('Social Auth User Fields'), - help_text=_( - 'When set to an empty list `[]`, this setting prevents new user ' - 'accounts from being created. Only users who have previously ' - 'logged in using social auth or have a user account with a ' - 'matching email address will be able to login.' - ), - category=_('Authentication'), - category_slug='authentication', - placeholder=['username', 'email'], -) + register( + 'SOCIAL_AUTH_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('Social Auth Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('Authentication'), + category_slug='authentication', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL', - field_class=fields.BooleanField, - default=False, - label=_('Use Email address for usernames'), - help_text=_('Enabling this setting will tell social auth to use the full Email as username instead of the full name'), - category=_('Authentication'), - category_slug='authentication', -) + register( + 'SOCIAL_AUTH_USER_FIELDS', + field_class=fields.StringListField, + allow_null=True, + default=None, + label=_('Social Auth User Fields'), + help_text=_( + 'When set to an empty list `[]`, this setting prevents new user ' + 'accounts from being created. Only users who have previously ' + 'logged in using social auth or have a user account with a ' + 'matching email address will be able to login.' + ), + category=_('Authentication'), + category_slug='authentication', + placeholder=['username', 'email'], + ) + + register( + 'SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL', + field_class=fields.BooleanField, + default=False, + label=_('Use Email address for usernames'), + help_text=_('Enabling this setting will tell social auth to use the full Email as username instead of the full name'), + category=_('Authentication'), + category_slug='authentication', + ) -############################################################################### -# LDAP AUTHENTICATION SETTINGS -############################################################################### + ############################################################################### + # LDAP AUTHENTICATION SETTINGS + ############################################################################### + + def _register_ldap(append=None): + append_str = '_{}'.format(append) if append else '' + + register( + 'AUTH_LDAP{}_SERVER_URI'.format(append_str), + field_class=LDAPServerURIField, + allow_blank=True, + default='', + label=_('LDAP Server URI'), + help_text=_( + 'URI to connect to LDAP server, such as "ldap://ldap.example.com:389" ' + '(non-SSL) or "ldaps://ldap.example.com:636" (SSL). Multiple LDAP ' + 'servers may be specified by separating with spaces or commas. LDAP ' + 'authentication is disabled if this parameter is empty.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder='ldaps://ldap.example.com:636', + ) + + register( + 'AUTH_LDAP{}_BIND_DN'.format(append_str), + field_class=fields.CharField, + allow_blank=True, + default='', + validators=[validate_ldap_bind_dn], + label=_('LDAP Bind DN'), + help_text=_( + 'DN (Distinguished Name) of user to bind for all search queries. This' + ' is the system user account we will use to login to query LDAP for other' + ' user information. Refer to the documentation for example syntax.' + ), + category=_('LDAP'), + category_slug='ldap', + ) + + register( + 'AUTH_LDAP{}_BIND_PASSWORD'.format(append_str), + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('LDAP Bind Password'), + help_text=_('Password used to bind LDAP user account.'), + category=_('LDAP'), + category_slug='ldap', + encrypted=True, + ) + + register( + 'AUTH_LDAP{}_START_TLS'.format(append_str), + field_class=fields.BooleanField, + default=False, + label=_('LDAP Start TLS'), + help_text=_('Whether to enable TLS when the LDAP connection is not using SSL.'), + category=_('LDAP'), + category_slug='ldap', + ) + + register( + 'AUTH_LDAP{}_CONNECTION_OPTIONS'.format(append_str), + field_class=LDAPConnectionOptionsField, + default={'OPT_REFERRALS': 0, 'OPT_NETWORK_TIMEOUT': 30}, + label=_('LDAP Connection Options'), + help_text=_( + 'Additional options to set for the LDAP connection. LDAP ' + 'referrals are disabled by default (to prevent certain LDAP ' + 'queries from hanging with AD). Option names should be strings ' + '(e.g. "OPT_REFERRALS"). Refer to ' + 'https://www.python-ldap.org/doc/html/ldap.html#options for ' + 'possible options and values that can be set.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder=collections.OrderedDict([('OPT_REFERRALS', 0), ('OPT_NETWORK_TIMEOUT', 30)]), + ) + + register( + 'AUTH_LDAP{}_USER_SEARCH'.format(append_str), + field_class=LDAPSearchUnionField, + default=[], + label=_('LDAP User Search'), + help_text=_( + 'LDAP search query to find users. Any user that matches the given ' + 'pattern will be able to login to the service. The user should also be ' + 'mapped into an organization (as defined in the ' + 'AUTH_LDAP_ORGANIZATION_MAP setting). If multiple search queries ' + 'need to be supported use of "LDAPUnion" is possible. See ' + 'the documentation for details.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder=('OU=Users,DC=example,DC=com', 'SCOPE_SUBTREE', '(sAMAccountName=%(user)s)'), + ) + + register( + 'AUTH_LDAP{}_USER_DN_TEMPLATE'.format(append_str), + field_class=LDAPDNWithUserField, + allow_blank=True, + allow_null=True, + default=None, + label=_('LDAP User DN Template'), + help_text=_( + 'Alternative to user search, if user DNs are all of the same ' + 'format. This approach is more efficient for user lookups than ' + 'searching if it is usable in your organizational environment. If ' + 'this setting has a value it will be used instead of ' + 'AUTH_LDAP_USER_SEARCH.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder='uid=%(user)s,OU=Users,DC=example,DC=com', + ) + + register( + 'AUTH_LDAP{}_USER_ATTR_MAP'.format(append_str), + field_class=LDAPUserAttrMapField, + default={}, + label=_('LDAP User Attribute Map'), + help_text=_( + 'Mapping of LDAP user schema to API user attributes. The default' + ' setting is valid for ActiveDirectory but users with other LDAP' + ' configurations may need to change the values. Refer to the' + ' documentation for additional details.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder=collections.OrderedDict([('first_name', 'givenName'), ('last_name', 'sn'), ('email', 'mail')]), + ) + + register( + 'AUTH_LDAP{}_GROUP_SEARCH'.format(append_str), + field_class=LDAPSearchField, + default=[], + label=_('LDAP Group Search'), + help_text=_( + 'Users are mapped to organizations based on their membership in LDAP' + ' groups. This setting defines the LDAP search query to find groups. ' + 'Unlike the user search, group search does not support LDAPSearchUnion.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder=('DC=example,DC=com', 'SCOPE_SUBTREE', '(objectClass=group)'), + ) + + register( + 'AUTH_LDAP{}_GROUP_TYPE'.format(append_str), + field_class=LDAPGroupTypeField, + label=_('LDAP Group Type'), + help_text=_( + 'The group type may need to be changed based on the type of the ' + 'LDAP server. Values are listed at: ' + 'https://django-auth-ldap.readthedocs.io/en/stable/groups.html#types-of-groups' + ), + category=_('LDAP'), + category_slug='ldap', + default='MemberDNGroupType', + depends_on=['AUTH_LDAP{}_GROUP_TYPE_PARAMS'.format(append_str)], + ) + + register( + 'AUTH_LDAP{}_GROUP_TYPE_PARAMS'.format(append_str), + field_class=LDAPGroupTypeParamsField, + label=_('LDAP Group Type Parameters'), + help_text=_('Key value parameters to send the chosen group type init method.'), + category=_('LDAP'), + category_slug='ldap', + default=collections.OrderedDict([('member_attr', 'member'), ('name_attr', 'cn')]), + placeholder=collections.OrderedDict([('ldap_group_user_attr', 'legacyuid'), ('member_attr', 'member'), ('name_attr', 'cn')]), + depends_on=['AUTH_LDAP{}_GROUP_TYPE'.format(append_str)], + ) + + register( + 'AUTH_LDAP{}_REQUIRE_GROUP'.format(append_str), + field_class=LDAPDNField, + allow_blank=True, + allow_null=True, + default=None, + label=_('LDAP Require Group'), + help_text=_( + 'Group DN required to login. If specified, user must be a member ' + 'of this group to login via LDAP. If not set, everyone in LDAP ' + 'that matches the user search will be able to login to the service. ' + 'Only one require group is supported.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder='CN=Service Users,OU=Users,DC=example,DC=com', + ) + + register( + 'AUTH_LDAP{}_DENY_GROUP'.format(append_str), + field_class=LDAPDNField, + allow_blank=True, + allow_null=True, + default=None, + label=_('LDAP Deny Group'), + help_text=_( + 'Group DN denied from login. If specified, user will not be allowed to login if a member of this group. Only one deny group is supported.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder='CN=Disabled Users,OU=Users,DC=example,DC=com', + ) + + register( + 'AUTH_LDAP{}_USER_FLAGS_BY_GROUP'.format(append_str), + field_class=LDAPUserFlagsField, + default={}, + label=_('LDAP User Flags By Group'), + help_text=_( + 'Retrieve users from a given group. At this time, superuser and system' + ' auditors are the only groups supported. Refer to the' + ' documentation for more detail.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder=collections.OrderedDict( + [('is_superuser', 'CN=Domain Admins,CN=Users,DC=example,DC=com'), ('is_system_auditor', 'CN=Domain Auditors,CN=Users,DC=example,DC=com')] + ), + ) + + register( + 'AUTH_LDAP{}_ORGANIZATION_MAP'.format(append_str), + field_class=LDAPOrganizationMapField, + default={}, + label=_('LDAP Organization Map'), + help_text=_( + 'Mapping between organization admins/users and LDAP groups. This ' + 'controls which users are placed into which organizations ' + 'relative to their LDAP group memberships. Configuration details ' + 'are available in the documentation.' + ), + category=_('LDAP'), + category_slug='ldap', + placeholder=collections.OrderedDict( + [ + ( + 'Test Org', + collections.OrderedDict( + [ + ('admins', 'CN=Domain Admins,CN=Users,DC=example,DC=com'), + ('auditors', 'CN=Domain Auditors,CN=Users,DC=example,DC=com'), + ('users', ['CN=Domain Users,CN=Users,DC=example,DC=com']), + ('remove_users', True), + ('remove_admins', True), + ] + ), + ), + ( + 'Test Org 2', + collections.OrderedDict( + [('admins', 'CN=Administrators,CN=Builtin,DC=example,DC=com'), ('users', True), ('remove_users', True), ('remove_admins', True)] + ), + ), + ] + ), + ) + + register( + 'AUTH_LDAP{}_TEAM_MAP'.format(append_str), + field_class=LDAPTeamMapField, + default={}, + label=_('LDAP Team Map'), + help_text=_('Mapping between team members (users) and LDAP groups. Configuration details are available in the documentation.'), + category=_('LDAP'), + category_slug='ldap', + placeholder=collections.OrderedDict( + [ + ( + 'My Team', + collections.OrderedDict([('organization', 'Test Org'), ('users', ['CN=Domain Users,CN=Users,DC=example,DC=com']), ('remove', True)]), + ), + ( + 'Other Team', + collections.OrderedDict([('organization', 'Test Org 2'), ('users', 'CN=Other Users,CN=Users,DC=example,DC=com'), ('remove', False)]), + ), + ] + ), + ) + _register_ldap() + _register_ldap('1') + _register_ldap('2') + _register_ldap('3') + _register_ldap('4') + _register_ldap('5') -def _register_ldap(append=None): - append_str = '_{}'.format(append) if append else '' + ############################################################################### + # RADIUS AUTHENTICATION SETTINGS + ############################################################################### register( - 'AUTH_LDAP{}_SERVER_URI'.format(append_str), - field_class=LDAPServerURIField, + 'RADIUS_SERVER', + field_class=fields.CharField, allow_blank=True, default='', - label=_('LDAP Server URI'), - help_text=_( - 'URI to connect to LDAP server, such as "ldap://ldap.example.com:389" ' - '(non-SSL) or "ldaps://ldap.example.com:636" (SSL). Multiple LDAP ' - 'servers may be specified by separating with spaces or commas. LDAP ' - 'authentication is disabled if this parameter is empty.' - ), - category=_('LDAP'), - category_slug='ldap', - placeholder='ldaps://ldap.example.com:636', + label=_('RADIUS Server'), + help_text=_('Hostname/IP of RADIUS server. RADIUS authentication is disabled if this setting is empty.'), + category=_('RADIUS'), + category_slug='radius', + placeholder='radius.example.com', ) register( - 'AUTH_LDAP{}_BIND_DN'.format(append_str), + 'RADIUS_PORT', + field_class=fields.IntegerField, + min_value=1, + max_value=65535, + default=1812, + label=_('RADIUS Port'), + help_text=_('Port of RADIUS server.'), + category=_('RADIUS'), + category_slug='radius', + ) + + register( + 'RADIUS_SECRET', field_class=fields.CharField, allow_blank=True, default='', - validators=[validate_ldap_bind_dn], - label=_('LDAP Bind DN'), - help_text=_( - 'DN (Distinguished Name) of user to bind for all search queries. This' - ' is the system user account we will use to login to query LDAP for other' - ' user information. Refer to the documentation for example syntax.' - ), - category=_('LDAP'), - category_slug='ldap', + label=_('RADIUS Secret'), + help_text=_('Shared secret for authenticating to RADIUS server.'), + category=_('RADIUS'), + category_slug='radius', + encrypted=True, + ) + + ############################################################################### + # TACACSPLUS AUTHENTICATION SETTINGS + ############################################################################### + + register( + 'TACACSPLUS_HOST', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('TACACS+ Server'), + help_text=_('Hostname of TACACS+ server.'), + category=_('TACACS+'), + category_slug='tacacsplus', + ) + + register( + 'TACACSPLUS_PORT', + field_class=fields.IntegerField, + min_value=1, + max_value=65535, + default=49, + label=_('TACACS+ Port'), + help_text=_('Port number of TACACS+ server.'), + category=_('TACACS+'), + category_slug='tacacsplus', ) register( - 'AUTH_LDAP{}_BIND_PASSWORD'.format(append_str), + 'TACACSPLUS_SECRET', field_class=fields.CharField, allow_blank=True, default='', - label=_('LDAP Bind Password'), - help_text=_('Password used to bind LDAP user account.'), - category=_('LDAP'), - category_slug='ldap', + validators=[validate_tacacsplus_disallow_nonascii], + label=_('TACACS+ Secret'), + help_text=_('Shared secret for authenticating to TACACS+ server.'), + category=_('TACACS+'), + category_slug='tacacsplus', encrypted=True, ) register( - 'AUTH_LDAP{}_START_TLS'.format(append_str), + 'TACACSPLUS_SESSION_TIMEOUT', + field_class=fields.IntegerField, + min_value=0, + default=5, + label=_('TACACS+ Auth Session Timeout'), + help_text=_('TACACS+ session timeout value in seconds, 0 disables timeout.'), + category=_('TACACS+'), + category_slug='tacacsplus', + unit=_('seconds'), + ) + + register( + 'TACACSPLUS_AUTH_PROTOCOL', + field_class=fields.ChoiceField, + choices=['ascii', 'pap'], + default='ascii', + label=_('TACACS+ Authentication Protocol'), + help_text=_('Choose the authentication protocol used by TACACS+ client.'), + category=_('TACACS+'), + category_slug='tacacsplus', + ) + + register( + 'TACACSPLUS_REM_ADDR', field_class=fields.BooleanField, - default=False, - label=_('LDAP Start TLS'), - help_text=_('Whether to enable TLS when the LDAP connection is not using SSL.'), - category=_('LDAP'), - category_slug='ldap', + default=True, + label=_('TACACS+ client address sending enabled'), + help_text=_('Enable the client address sending by TACACS+ client.'), + category=_('TACACS+'), + category_slug='tacacsplus', ) + ############################################################################### + # GOOGLE OAUTH2 AUTHENTICATION SETTINGS + ############################################################################### + register( - 'AUTH_LDAP{}_CONNECTION_OPTIONS'.format(append_str), - field_class=LDAPConnectionOptionsField, - default={'OPT_REFERRALS': 0, 'OPT_NETWORK_TIMEOUT': 30}, - label=_('LDAP Connection Options'), + 'SOCIAL_AUTH_GOOGLE_OAUTH2_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('google-oauth2'), + label=_('Google OAuth2 Callback URL'), help_text=_( - 'Additional options to set for the LDAP connection. LDAP ' - 'referrals are disabled by default (to prevent certain LDAP ' - 'queries from hanging with AD). Option names should be strings ' - '(e.g. "OPT_REFERRALS"). Refer to ' - 'https://www.python-ldap.org/doc/html/ldap.html#options for ' - 'possible options and values that can be set.' + 'Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.' ), - category=_('LDAP'), - category_slug='ldap', - placeholder=collections.OrderedDict([('OPT_REFERRALS', 0), ('OPT_NETWORK_TIMEOUT', 30)]), + category=_('Google OAuth2'), + category_slug='google-oauth2', + depends_on=['TOWER_URL_BASE'], ) register( - 'AUTH_LDAP{}_USER_SEARCH'.format(append_str), - field_class=LDAPSearchUnionField, - default=[], - label=_('LDAP User Search'), - help_text=_( - 'LDAP search query to find users. Any user that matches the given ' - 'pattern will be able to login to the service. The user should also be ' - 'mapped into an organization (as defined in the ' - 'AUTH_LDAP_ORGANIZATION_MAP setting). If multiple search queries ' - 'need to be supported use of "LDAPUnion" is possible. See ' - 'the documentation for details.' - ), - category=_('LDAP'), - category_slug='ldap', - placeholder=('OU=Users,DC=example,DC=com', 'SCOPE_SUBTREE', '(sAMAccountName=%(user)s)'), + 'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('Google OAuth2 Key'), + help_text=_('The OAuth2 key from your web application.'), + category=_('Google OAuth2'), + category_slug='google-oauth2', + placeholder='528620852399-gm2dt4hrl2tsj67fqamk09k1e0ad6gd8.apps.googleusercontent.com', ) register( - 'AUTH_LDAP{}_USER_DN_TEMPLATE'.format(append_str), - field_class=LDAPDNWithUserField, + 'SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET', + field_class=fields.CharField, allow_blank=True, - allow_null=True, - default=None, - label=_('LDAP User DN Template'), - help_text=_( - 'Alternative to user search, if user DNs are all of the same ' - 'format. This approach is more efficient for user lookups than ' - 'searching if it is usable in your organizational environment. If ' - 'this setting has a value it will be used instead of ' - 'AUTH_LDAP_USER_SEARCH.' - ), - category=_('LDAP'), - category_slug='ldap', - placeholder='uid=%(user)s,OU=Users,DC=example,DC=com', + default='', + label=_('Google OAuth2 Secret'), + help_text=_('The OAuth2 secret from your web application.'), + category=_('Google OAuth2'), + category_slug='google-oauth2', + placeholder='q2fMVCmEregbg-drvebPp8OW', + encrypted=True, + ) + + register( + 'SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS', + field_class=fields.StringListField, + default=[], + label=_('Google OAuth2 Allowed Domains'), + help_text=_('Update this setting to restrict the domains who are allowed to login using Google OAuth2.'), + category=_('Google OAuth2'), + category_slug='google-oauth2', + placeholder=['example.com'], ) register( - 'AUTH_LDAP{}_USER_ATTR_MAP'.format(append_str), - field_class=LDAPUserAttrMapField, + 'SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS', + field_class=fields.DictField, default={}, - label=_('LDAP User Attribute Map'), + label=_('Google OAuth2 Extra Arguments'), help_text=_( - 'Mapping of LDAP user schema to API user attributes. The default' - ' setting is valid for ActiveDirectory but users with other LDAP' - ' configurations may need to change the values. Refer to the' - ' documentation for additional details.' + 'Extra arguments for Google OAuth2 login. You can restrict it to' + ' only allow a single domain to authenticate, even if the user is' + ' logged in with multple Google accounts. Refer to the' + ' documentation for more detail.' ), - category=_('LDAP'), - category_slug='ldap', - placeholder=collections.OrderedDict([('first_name', 'givenName'), ('last_name', 'sn'), ('email', 'mail')]), + category=_('Google OAuth2'), + category_slug='google-oauth2', + placeholder={'hd': 'example.com'}, ) register( - 'AUTH_LDAP{}_GROUP_SEARCH'.format(append_str), - field_class=LDAPSearchField, - default=[], - label=_('LDAP Group Search'), - help_text=_( - 'Users are mapped to organizations based on their membership in LDAP' - ' groups. This setting defines the LDAP search query to find groups. ' - 'Unlike the user search, group search does not support LDAPSearchUnion.' - ), - category=_('LDAP'), - category_slug='ldap', - placeholder=('DC=example,DC=com', 'SCOPE_SUBTREE', '(objectClass=group)'), + 'SOCIAL_AUTH_GOOGLE_OAUTH2_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('Google OAuth2 Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('Google OAuth2'), + category_slug='google-oauth2', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) + + register( + 'SOCIAL_AUTH_GOOGLE_OAUTH2_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('Google OAuth2 Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('Google OAuth2'), + category_slug='google-oauth2', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, ) + ############################################################################### + # GITHUB OAUTH2 AUTHENTICATION SETTINGS + ############################################################################### + register( - 'AUTH_LDAP{}_GROUP_TYPE'.format(append_str), - field_class=LDAPGroupTypeField, - label=_('LDAP Group Type'), + 'SOCIAL_AUTH_GITHUB_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('github'), + label=_('GitHub OAuth2 Callback URL'), help_text=_( - 'The group type may need to be changed based on the type of the ' - 'LDAP server. Values are listed at: ' - 'https://django-auth-ldap.readthedocs.io/en/stable/groups.html#types-of-groups' + 'Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.' ), - category=_('LDAP'), - category_slug='ldap', - default='MemberDNGroupType', - depends_on=['AUTH_LDAP{}_GROUP_TYPE_PARAMS'.format(append_str)], + category=_('GitHub OAuth2'), + category_slug='github', + depends_on=['TOWER_URL_BASE'], ) register( - 'AUTH_LDAP{}_GROUP_TYPE_PARAMS'.format(append_str), - field_class=LDAPGroupTypeParamsField, - label=_('LDAP Group Type Parameters'), - help_text=_('Key value parameters to send the chosen group type init method.'), - category=_('LDAP'), - category_slug='ldap', - default=collections.OrderedDict([('member_attr', 'member'), ('name_attr', 'cn')]), - placeholder=collections.OrderedDict([('ldap_group_user_attr', 'legacyuid'), ('member_attr', 'member'), ('name_attr', 'cn')]), - depends_on=['AUTH_LDAP{}_GROUP_TYPE'.format(append_str)], + 'SOCIAL_AUTH_GITHUB_KEY', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub OAuth2 Key'), + help_text=_('The OAuth2 key (Client ID) from your GitHub developer application.'), + category=_('GitHub OAuth2'), + category_slug='github', ) register( - 'AUTH_LDAP{}_REQUIRE_GROUP'.format(append_str), - field_class=LDAPDNField, + 'SOCIAL_AUTH_GITHUB_SECRET', + field_class=fields.CharField, allow_blank=True, + default='', + label=_('GitHub OAuth2 Secret'), + help_text=_('The OAuth2 secret (Client Secret) from your GitHub developer application.'), + category=_('GitHub OAuth2'), + category_slug='github', + encrypted=True, + ) + + register( + 'SOCIAL_AUTH_GITHUB_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, allow_null=True, default=None, - label=_('LDAP Require Group'), - help_text=_( - 'Group DN required to login. If specified, user must be a member ' - 'of this group to login via LDAP. If not set, everyone in LDAP ' - 'that matches the user search will be able to login to the service. ' - 'Only one require group is supported.' - ), - category=_('LDAP'), - category_slug='ldap', - placeholder='CN=Service Users,OU=Users,DC=example,DC=com', + label=_('GitHub OAuth2 Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('GitHub OAuth2'), + category_slug='github', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, ) register( - 'AUTH_LDAP{}_DENY_GROUP'.format(append_str), - field_class=LDAPDNField, - allow_blank=True, + 'SOCIAL_AUTH_GITHUB_TEAM_MAP', + field_class=SocialTeamMapField, allow_null=True, default=None, - label=_('LDAP Deny Group'), - help_text=_( - 'Group DN denied from login. If specified, user will not be allowed to login if a member of this group. Only one deny group is supported.' - ), - category=_('LDAP'), - category_slug='ldap', - placeholder='CN=Disabled Users,OU=Users,DC=example,DC=com', + label=_('GitHub OAuth2 Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('GitHub OAuth2'), + category_slug='github', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, ) + ############################################################################### + # GITHUB ORG OAUTH2 AUTHENTICATION SETTINGS + ############################################################################### + register( - 'AUTH_LDAP{}_USER_FLAGS_BY_GROUP'.format(append_str), - field_class=LDAPUserFlagsField, - default={}, - label=_('LDAP User Flags By Group'), + 'SOCIAL_AUTH_GITHUB_ORG_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('github-org'), + label=_('GitHub Organization OAuth2 Callback URL'), help_text=_( - 'Retrieve users from a given group. At this time, superuser and system' - ' auditors are the only groups supported. Refer to the' - ' documentation for more detail.' - ), - category=_('LDAP'), - category_slug='ldap', - placeholder=collections.OrderedDict( - [('is_superuser', 'CN=Domain Admins,CN=Users,DC=example,DC=com'), ('is_system_auditor', 'CN=Domain Auditors,CN=Users,DC=example,DC=com')] + 'Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.' ), + category=_('GitHub Organization OAuth2'), + category_slug='github-org', + depends_on=['TOWER_URL_BASE'], ) register( - 'AUTH_LDAP{}_ORGANIZATION_MAP'.format(append_str), - field_class=LDAPOrganizationMapField, - default={}, - label=_('LDAP Organization Map'), - help_text=_( - 'Mapping between organization admins/users and LDAP groups. This ' - 'controls which users are placed into which organizations ' - 'relative to their LDAP group memberships. Configuration details ' - 'are available in the documentation.' - ), - category=_('LDAP'), - category_slug='ldap', - placeholder=collections.OrderedDict( - [ - ( - 'Test Org', - collections.OrderedDict( - [ - ('admins', 'CN=Domain Admins,CN=Users,DC=example,DC=com'), - ('auditors', 'CN=Domain Auditors,CN=Users,DC=example,DC=com'), - ('users', ['CN=Domain Users,CN=Users,DC=example,DC=com']), - ('remove_users', True), - ('remove_admins', True), - ] - ), - ), - ( - 'Test Org 2', - collections.OrderedDict( - [('admins', 'CN=Administrators,CN=Builtin,DC=example,DC=com'), ('users', True), ('remove_users', True), ('remove_admins', True)] - ), - ), - ] - ), + 'SOCIAL_AUTH_GITHUB_ORG_KEY', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Organization OAuth2 Key'), + help_text=_('The OAuth2 key (Client ID) from your GitHub organization application.'), + category=_('GitHub Organization OAuth2'), + category_slug='github-org', ) register( - 'AUTH_LDAP{}_TEAM_MAP'.format(append_str), - field_class=LDAPTeamMapField, - default={}, - label=_('LDAP Team Map'), - help_text=_('Mapping between team members (users) and LDAP groups. Configuration details are available in the documentation.'), - category=_('LDAP'), - category_slug='ldap', - placeholder=collections.OrderedDict( - [ - ( - 'My Team', - collections.OrderedDict([('organization', 'Test Org'), ('users', ['CN=Domain Users,CN=Users,DC=example,DC=com']), ('remove', True)]), - ), - ( - 'Other Team', - collections.OrderedDict([('organization', 'Test Org 2'), ('users', 'CN=Other Users,CN=Users,DC=example,DC=com'), ('remove', False)]), - ), - ] - ), + 'SOCIAL_AUTH_GITHUB_ORG_SECRET', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Organization OAuth2 Secret'), + help_text=_('The OAuth2 secret (Client Secret) from your GitHub organization application.'), + category=_('GitHub Organization OAuth2'), + category_slug='github-org', + encrypted=True, ) + register( + 'SOCIAL_AUTH_GITHUB_ORG_NAME', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Organization Name'), + help_text=_('The name of your GitHub organization, as used in your organization\'s URL: https://github.com//.'), + category=_('GitHub Organization OAuth2'), + category_slug='github-org', + ) -_register_ldap() -_register_ldap('1') -_register_ldap('2') -_register_ldap('3') -_register_ldap('4') -_register_ldap('5') - -############################################################################### -# RADIUS AUTHENTICATION SETTINGS -############################################################################### - -register( - 'RADIUS_SERVER', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('RADIUS Server'), - help_text=_('Hostname/IP of RADIUS server. RADIUS authentication is disabled if this setting is empty.'), - category=_('RADIUS'), - category_slug='radius', - placeholder='radius.example.com', -) + register( + 'SOCIAL_AUTH_GITHUB_ORG_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('GitHub Organization OAuth2 Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('GitHub Organization OAuth2'), + category_slug='github-org', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) -register( - 'RADIUS_PORT', - field_class=fields.IntegerField, - min_value=1, - max_value=65535, - default=1812, - label=_('RADIUS Port'), - help_text=_('Port of RADIUS server.'), - category=_('RADIUS'), - category_slug='radius', -) + register( + 'SOCIAL_AUTH_GITHUB_ORG_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('GitHub Organization OAuth2 Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('GitHub Organization OAuth2'), + category_slug='github-org', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, + ) -register( - 'RADIUS_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('RADIUS Secret'), - help_text=_('Shared secret for authenticating to RADIUS server.'), - category=_('RADIUS'), - category_slug='radius', - encrypted=True, -) + ############################################################################### + # GITHUB TEAM OAUTH2 AUTHENTICATION SETTINGS + ############################################################################### -############################################################################### -# TACACSPLUS AUTHENTICATION SETTINGS -############################################################################### - -register( - 'TACACSPLUS_HOST', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('TACACS+ Server'), - help_text=_('Hostname of TACACS+ server.'), - category=_('TACACS+'), - category_slug='tacacsplus', -) + register( + 'SOCIAL_AUTH_GITHUB_TEAM_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('github-team'), + label=_('GitHub Team OAuth2 Callback URL'), + help_text=_( + 'Create an organization-owned application at ' + 'https://github.com/organizations//settings/applications ' + 'and obtain an OAuth2 key (Client ID) and secret (Client Secret). ' + 'Provide this URL as the callback URL for your application.' + ), + category=_('GitHub Team OAuth2'), + category_slug='github-team', + depends_on=['TOWER_URL_BASE'], + ) -register( - 'TACACSPLUS_PORT', - field_class=fields.IntegerField, - min_value=1, - max_value=65535, - default=49, - label=_('TACACS+ Port'), - help_text=_('Port number of TACACS+ server.'), - category=_('TACACS+'), - category_slug='tacacsplus', -) + register( + 'SOCIAL_AUTH_GITHUB_TEAM_KEY', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Team OAuth2 Key'), + help_text=_('The OAuth2 key (Client ID) from your GitHub organization application.'), + category=_('GitHub Team OAuth2'), + category_slug='github-team', + ) -register( - 'TACACSPLUS_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - validators=[validate_tacacsplus_disallow_nonascii], - label=_('TACACS+ Secret'), - help_text=_('Shared secret for authenticating to TACACS+ server.'), - category=_('TACACS+'), - category_slug='tacacsplus', - encrypted=True, -) + register( + 'SOCIAL_AUTH_GITHUB_TEAM_SECRET', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Team OAuth2 Secret'), + help_text=_('The OAuth2 secret (Client Secret) from your GitHub organization application.'), + category=_('GitHub Team OAuth2'), + category_slug='github-team', + encrypted=True, + ) -register( - 'TACACSPLUS_SESSION_TIMEOUT', - field_class=fields.IntegerField, - min_value=0, - default=5, - label=_('TACACS+ Auth Session Timeout'), - help_text=_('TACACS+ session timeout value in seconds, 0 disables timeout.'), - category=_('TACACS+'), - category_slug='tacacsplus', - unit=_('seconds'), -) + register( + 'SOCIAL_AUTH_GITHUB_TEAM_ID', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Team ID'), + help_text=_('Find the numeric team ID using the Github API: http://fabian-kostadinov.github.io/2015/01/16/how-to-find-a-github-team-id/.'), + category=_('GitHub Team OAuth2'), + category_slug='github-team', + ) -register( - 'TACACSPLUS_AUTH_PROTOCOL', - field_class=fields.ChoiceField, - choices=['ascii', 'pap'], - default='ascii', - label=_('TACACS+ Authentication Protocol'), - help_text=_('Choose the authentication protocol used by TACACS+ client.'), - category=_('TACACS+'), - category_slug='tacacsplus', -) + register( + 'SOCIAL_AUTH_GITHUB_TEAM_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('GitHub Team OAuth2 Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('GitHub Team OAuth2'), + category_slug='github-team', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) -register( - 'TACACSPLUS_REM_ADDR', - field_class=fields.BooleanField, - default=True, - label=_('TACACS+ client address sending enabled'), - help_text=_('Enable the client address sending by TACACS+ client.'), - category=_('TACACS+'), - category_slug='tacacsplus', -) + register( + 'SOCIAL_AUTH_GITHUB_TEAM_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('GitHub Team OAuth2 Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('GitHub Team OAuth2'), + category_slug='github-team', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, + ) -############################################################################### -# GOOGLE OAUTH2 AUTHENTICATION SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_GOOGLE_OAUTH2_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('google-oauth2'), - label=_('Google OAuth2 Callback URL'), - help_text=_('Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.'), - category=_('Google OAuth2'), - category_slug='google-oauth2', - depends_on=['TOWER_URL_BASE'], -) + ############################################################################### + # GITHUB ENTERPRISE OAUTH2 AUTHENTICATION SETTINGS + ############################################################################### -register( - 'SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('Google OAuth2 Key'), - help_text=_('The OAuth2 key from your web application.'), - category=_('Google OAuth2'), - category_slug='google-oauth2', - placeholder='528620852399-gm2dt4hrl2tsj67fqamk09k1e0ad6gd8.apps.googleusercontent.com', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('github-enterprise'), + label=_('GitHub Enterprise OAuth2 Callback URL'), + help_text=_( + 'Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.' + ), + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise', + depends_on=['TOWER_URL_BASE'], + ) -register( - 'SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('Google OAuth2 Secret'), - help_text=_('The OAuth2 secret from your web application.'), - category=_('Google OAuth2'), - category_slug='google-oauth2', - placeholder='q2fMVCmEregbg-drvebPp8OW', - encrypted=True, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_URL', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise URL'), + help_text=_('The URL for your Github Enterprise instance, e.g.: http(s)://hostname/. Refer to Github Enterprise documentation for more details.'), + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise', + ) -register( - 'SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS', - field_class=fields.StringListField, - default=[], - label=_('Google OAuth2 Allowed Domains'), - help_text=_('Update this setting to restrict the domains who are allowed to login using Google OAuth2.'), - category=_('Google OAuth2'), - category_slug='google-oauth2', - placeholder=['example.com'], -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_API_URL', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise API URL'), + help_text=_( + 'The API URL for your GitHub Enterprise instance, e.g.: http(s)://hostname/api/v3/. Refer to Github Enterprise documentation for more details.' + ), + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise', + ) -register( - 'SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS', - field_class=fields.DictField, - default={}, - label=_('Google OAuth2 Extra Arguments'), - help_text=_( - 'Extra arguments for Google OAuth2 login. You can restrict it to' - ' only allow a single domain to authenticate, even if the user is' - ' logged in with multple Google accounts. Refer to the' - ' documentation for more detail.' - ), - category=_('Google OAuth2'), - category_slug='google-oauth2', - placeholder={'hd': 'example.com'}, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_KEY', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise OAuth2 Key'), + help_text=_('The OAuth2 key (Client ID) from your GitHub Enterprise developer application.'), + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise', + ) -register( - 'SOCIAL_AUTH_GOOGLE_OAUTH2_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('Google OAuth2 Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('Google OAuth2'), - category_slug='google-oauth2', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_SECRET', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise OAuth2 Secret'), + help_text=_('The OAuth2 secret (Client Secret) from your GitHub Enterprise developer application.'), + category=_('GitHub OAuth2'), + category_slug='github-enterprise', + encrypted=True, + ) -register( - 'SOCIAL_AUTH_GOOGLE_OAUTH2_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('Google OAuth2 Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('Google OAuth2'), - category_slug='google-oauth2', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('GitHub Enterprise OAuth2 Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) -############################################################################### -# GITHUB OAUTH2 AUTHENTICATION SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_GITHUB_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('github'), - label=_('GitHub OAuth2 Callback URL'), - help_text=_('Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.'), - category=_('GitHub OAuth2'), - category_slug='github', - depends_on=['TOWER_URL_BASE'], -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('GitHub Enterprise OAuth2 Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_GITHUB_KEY', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub OAuth2 Key'), - help_text=_('The OAuth2 key (Client ID) from your GitHub developer application.'), - category=_('GitHub OAuth2'), - category_slug='github', -) + ############################################################################### + # GITHUB ENTERPRISE ORG OAUTH2 AUTHENTICATION SETTINGS + ############################################################################### -register( - 'SOCIAL_AUTH_GITHUB_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub OAuth2 Secret'), - help_text=_('The OAuth2 secret (Client Secret) from your GitHub developer application.'), - category=_('GitHub OAuth2'), - category_slug='github', - encrypted=True, -) - -register( - 'SOCIAL_AUTH_GITHUB_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('GitHub OAuth2 Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('GitHub OAuth2'), - category_slug='github', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) - -register( - 'SOCIAL_AUTH_GITHUB_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('GitHub OAuth2 Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('GitHub OAuth2'), - category_slug='github', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) - -############################################################################### -# GITHUB ORG OAUTH2 AUTHENTICATION SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_GITHUB_ORG_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('github-org'), - label=_('GitHub Organization OAuth2 Callback URL'), - help_text=_('Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.'), - category=_('GitHub Organization OAuth2'), - category_slug='github-org', - depends_on=['TOWER_URL_BASE'], -) - -register( - 'SOCIAL_AUTH_GITHUB_ORG_KEY', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Organization OAuth2 Key'), - help_text=_('The OAuth2 key (Client ID) from your GitHub organization application.'), - category=_('GitHub Organization OAuth2'), - category_slug='github-org', -) - -register( - 'SOCIAL_AUTH_GITHUB_ORG_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Organization OAuth2 Secret'), - help_text=_('The OAuth2 secret (Client Secret) from your GitHub organization application.'), - category=_('GitHub Organization OAuth2'), - category_slug='github-org', - encrypted=True, -) - -register( - 'SOCIAL_AUTH_GITHUB_ORG_NAME', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Organization Name'), - help_text=_('The name of your GitHub organization, as used in your organization\'s URL: https://github.com//.'), - category=_('GitHub Organization OAuth2'), - category_slug='github-org', -) - -register( - 'SOCIAL_AUTH_GITHUB_ORG_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('GitHub Organization OAuth2 Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('GitHub Organization OAuth2'), - category_slug='github-org', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) - -register( - 'SOCIAL_AUTH_GITHUB_ORG_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('GitHub Organization OAuth2 Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('GitHub Organization OAuth2'), - category_slug='github-org', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) - -############################################################################### -# GITHUB TEAM OAUTH2 AUTHENTICATION SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_GITHUB_TEAM_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('github-team'), - label=_('GitHub Team OAuth2 Callback URL'), - help_text=_( - 'Create an organization-owned application at ' - 'https://github.com/organizations//settings/applications ' - 'and obtain an OAuth2 key (Client ID) and secret (Client Secret). ' - 'Provide this URL as the callback URL for your application.' - ), - category=_('GitHub Team OAuth2'), - category_slug='github-team', - depends_on=['TOWER_URL_BASE'], -) - -register( - 'SOCIAL_AUTH_GITHUB_TEAM_KEY', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Team OAuth2 Key'), - help_text=_('The OAuth2 key (Client ID) from your GitHub organization application.'), - category=_('GitHub Team OAuth2'), - category_slug='github-team', -) - -register( - 'SOCIAL_AUTH_GITHUB_TEAM_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Team OAuth2 Secret'), - help_text=_('The OAuth2 secret (Client Secret) from your GitHub organization application.'), - category=_('GitHub Team OAuth2'), - category_slug='github-team', - encrypted=True, -) - -register( - 'SOCIAL_AUTH_GITHUB_TEAM_ID', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Team ID'), - help_text=_('Find the numeric team ID using the Github API: http://fabian-kostadinov.github.io/2015/01/16/how-to-find-a-github-team-id/.'), - category=_('GitHub Team OAuth2'), - category_slug='github-team', -) - -register( - 'SOCIAL_AUTH_GITHUB_TEAM_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('GitHub Team OAuth2 Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('GitHub Team OAuth2'), - category_slug='github-team', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) - -register( - 'SOCIAL_AUTH_GITHUB_TEAM_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('GitHub Team OAuth2 Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('GitHub Team OAuth2'), - category_slug='github-team', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) - -############################################################################### -# GITHUB ENTERPRISE OAUTH2 AUTHENTICATION SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('github-enterprise'), - label=_('GitHub Enterprise OAuth2 Callback URL'), - help_text=_('Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.'), - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise', - depends_on=['TOWER_URL_BASE'], -) - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_URL', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise URL'), - help_text=_('The URL for your Github Enterprise instance, e.g.: http(s)://hostname/. Refer to Github Enterprise documentation for more details.'), - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise', -) - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_API_URL', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise API URL'), - help_text=_( - 'The API URL for your GitHub Enterprise instance, e.g.: http(s)://hostname/api/v3/. Refer to Github Enterprise documentation for more details.' - ), - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise', -) - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_KEY', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise OAuth2 Key'), - help_text=_('The OAuth2 key (Client ID) from your GitHub Enterprise developer application.'), - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise', -) - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise OAuth2 Secret'), - help_text=_('The OAuth2 secret (Client Secret) from your GitHub Enterprise developer application.'), - category=_('GitHub OAuth2'), - category_slug='github-enterprise', - encrypted=True, -) - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('GitHub Enterprise OAuth2 Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('GitHub Enterprise OAuth2 Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) - -############################################################################### -# GITHUB ENTERPRISE ORG OAUTH2 AUTHENTICATION SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('github-enterprise-org'), - label=_('GitHub Enterprise Organization OAuth2 Callback URL'), - help_text=_('Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.'), - category=_('GitHub Enterprise Organization OAuth2'), - category_slug='github-enterprise-org', - depends_on=['TOWER_URL_BASE'], -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('github-enterprise-org'), + label=_('GitHub Enterprise Organization OAuth2 Callback URL'), + help_text=_( + 'Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail.' + ), + category=_('GitHub Enterprise Organization OAuth2'), + category_slug='github-enterprise-org', + depends_on=['TOWER_URL_BASE'], + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_URL', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Organization URL'), - help_text=_('The URL for your Github Enterprise instance, e.g.: http(s)://hostname/. Refer to Github Enterprise documentation for more details.'), - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise-org', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_URL', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Organization URL'), + help_text=_('The URL for your Github Enterprise instance, e.g.: http(s)://hostname/. Refer to Github Enterprise documentation for more details.'), + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise-org', + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_API_URL', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Organization API URL'), - help_text=_( - 'The API URL for your GitHub Enterprise instance, e.g.: http(s)://hostname/api/v3/. Refer to Github Enterprise documentation for more details.' - ), - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise-org', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_API_URL', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Organization API URL'), + help_text=_( + 'The API URL for your GitHub Enterprise instance, e.g.: http(s)://hostname/api/v3/. Refer to Github Enterprise documentation for more details.' + ), + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise-org', + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_KEY', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Organization OAuth2 Key'), - help_text=_('The OAuth2 key (Client ID) from your GitHub Enterprise organization application.'), - category=_('GitHub Enterprise Organization OAuth2'), - category_slug='github-enterprise-org', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_KEY', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Organization OAuth2 Key'), + help_text=_('The OAuth2 key (Client ID) from your GitHub Enterprise organization application.'), + category=_('GitHub Enterprise Organization OAuth2'), + category_slug='github-enterprise-org', + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Organization OAuth2 Secret'), - help_text=_('The OAuth2 secret (Client Secret) from your GitHub Enterprise organization application.'), - category=_('GitHub Enterprise Organization OAuth2'), - category_slug='github-enterprise-org', - encrypted=True, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_SECRET', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Organization OAuth2 Secret'), + help_text=_('The OAuth2 secret (Client Secret) from your GitHub Enterprise organization application.'), + category=_('GitHub Enterprise Organization OAuth2'), + category_slug='github-enterprise-org', + encrypted=True, + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_NAME', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Organization Name'), - help_text=_('The name of your GitHub Enterprise organization, as used in your organization\'s URL: https://github.com//.'), - category=_('GitHub Enterprise Organization OAuth2'), - category_slug='github-enterprise-org', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_NAME', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Organization Name'), + help_text=_('The name of your GitHub Enterprise organization, as used in your organization\'s URL: https://github.com//.'), + category=_('GitHub Enterprise Organization OAuth2'), + category_slug='github-enterprise-org', + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('GitHub Enterprise Organization OAuth2 Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('GitHub Enterprise Organization OAuth2'), - category_slug='github-enterprise-org', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('GitHub Enterprise Organization OAuth2 Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('GitHub Enterprise Organization OAuth2'), + category_slug='github-enterprise-org', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('GitHub Enterprise Organization OAuth2 Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('GitHub Enterprise Organization OAuth2'), - category_slug='github-enterprise-org', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_ORG_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('GitHub Enterprise Organization OAuth2 Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('GitHub Enterprise Organization OAuth2'), + category_slug='github-enterprise-org', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, + ) -############################################################################### -# GITHUB ENTERPRISE TEAM OAUTH2 AUTHENTICATION SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('github-enterprise-team'), - label=_('GitHub Enterprise Team OAuth2 Callback URL'), - help_text=_( - 'Create an organization-owned application at ' - 'https://github.com/organizations//settings/applications ' - 'and obtain an OAuth2 key (Client ID) and secret (Client Secret). ' - 'Provide this URL as the callback URL for your application.' - ), - category=_('GitHub Enterprise Team OAuth2'), - category_slug='github-enterprise-team', - depends_on=['TOWER_URL_BASE'], -) + ############################################################################### + # GITHUB ENTERPRISE TEAM OAUTH2 AUTHENTICATION SETTINGS + ############################################################################### -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_URL', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Team URL'), - help_text=_('The URL for your Github Enterprise instance, e.g.: http(s)://hostname/. Refer to Github Enterprise documentation for more details.'), - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise-team', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('github-enterprise-team'), + label=_('GitHub Enterprise Team OAuth2 Callback URL'), + help_text=_( + 'Create an organization-owned application at ' + 'https://github.com/organizations//settings/applications ' + 'and obtain an OAuth2 key (Client ID) and secret (Client Secret). ' + 'Provide this URL as the callback URL for your application.' + ), + category=_('GitHub Enterprise Team OAuth2'), + category_slug='github-enterprise-team', + depends_on=['TOWER_URL_BASE'], + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_API_URL', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Team API URL'), - help_text=_( - 'The API URL for your GitHub Enterprise instance, e.g.: http(s)://hostname/api/v3/. Refer to Github Enterprise documentation for more details.' - ), - category=_('GitHub Enterprise OAuth2'), - category_slug='github-enterprise-team', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_URL', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Team URL'), + help_text=_('The URL for your Github Enterprise instance, e.g.: http(s)://hostname/. Refer to Github Enterprise documentation for more details.'), + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise-team', + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_KEY', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Team OAuth2 Key'), - help_text=_('The OAuth2 key (Client ID) from your GitHub Enterprise organization application.'), - category=_('GitHub Enterprise Team OAuth2'), - category_slug='github-enterprise-team', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_API_URL', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Team API URL'), + help_text=_( + 'The API URL for your GitHub Enterprise instance, e.g.: http(s)://hostname/api/v3/. Refer to Github Enterprise documentation for more details.' + ), + category=_('GitHub Enterprise OAuth2'), + category_slug='github-enterprise-team', + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Team OAuth2 Secret'), - help_text=_('The OAuth2 secret (Client Secret) from your GitHub Enterprise organization application.'), - category=_('GitHub Enterprise Team OAuth2'), - category_slug='github-enterprise-team', - encrypted=True, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_KEY', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Team OAuth2 Key'), + help_text=_('The OAuth2 key (Client ID) from your GitHub Enterprise organization application.'), + category=_('GitHub Enterprise Team OAuth2'), + category_slug='github-enterprise-team', + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_ID', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('GitHub Enterprise Team ID'), - help_text=_('Find the numeric team ID using the Github Enterprise API: http://fabian-kostadinov.github.io/2015/01/16/how-to-find-a-github-team-id/.'), - category=_('GitHub Enterprise Team OAuth2'), - category_slug='github-enterprise-team', -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_SECRET', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Team OAuth2 Secret'), + help_text=_('The OAuth2 secret (Client Secret) from your GitHub Enterprise organization application.'), + category=_('GitHub Enterprise Team OAuth2'), + category_slug='github-enterprise-team', + encrypted=True, + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('GitHub Enterprise Team OAuth2 Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('GitHub Enterprise Team OAuth2'), - category_slug='github-enterprise-team', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_ID', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('GitHub Enterprise Team ID'), + help_text=_('Find the numeric team ID using the Github Enterprise API: http://fabian-kostadinov.github.io/2015/01/16/how-to-find-a-github-team-id/.'), + category=_('GitHub Enterprise Team OAuth2'), + category_slug='github-enterprise-team', + ) -register( - 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('GitHub Enterprise Team OAuth2 Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('GitHub Enterprise Team OAuth2'), - category_slug='github-enterprise-team', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('GitHub Enterprise Team OAuth2 Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('GitHub Enterprise Team OAuth2'), + category_slug='github-enterprise-team', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) -############################################################################### -# MICROSOFT AZURE ACTIVE DIRECTORY SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_AZUREAD_OAUTH2_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('azuread-oauth2'), - label=_('Azure AD OAuth2 Callback URL'), - help_text=_('Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail. '), - category=_('Azure AD OAuth2'), - category_slug='azuread-oauth2', - depends_on=['TOWER_URL_BASE'], -) + register( + 'SOCIAL_AUTH_GITHUB_ENTERPRISE_TEAM_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('GitHub Enterprise Team OAuth2 Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('GitHub Enterprise Team OAuth2'), + category_slug='github-enterprise-team', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_AZUREAD_OAUTH2_KEY', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('Azure AD OAuth2 Key'), - help_text=_('The OAuth2 key (Client ID) from your Azure AD application.'), - category=_('Azure AD OAuth2'), - category_slug='azuread-oauth2', -) + ############################################################################### + # MICROSOFT AZURE ACTIVE DIRECTORY SETTINGS + ############################################################################### -register( - 'SOCIAL_AUTH_AZUREAD_OAUTH2_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('Azure AD OAuth2 Secret'), - help_text=_('The OAuth2 secret (Client Secret) from your Azure AD application.'), - category=_('Azure AD OAuth2'), - category_slug='azuread-oauth2', - encrypted=True, -) + register( + 'SOCIAL_AUTH_AZUREAD_OAUTH2_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('azuread-oauth2'), + label=_('Azure AD OAuth2 Callback URL'), + help_text=_( + 'Provide this URL as the callback URL for your application as part of your registration process. Refer to the documentation for more detail. ' + ), + category=_('Azure AD OAuth2'), + category_slug='azuread-oauth2', + depends_on=['TOWER_URL_BASE'], + ) -register( - 'SOCIAL_AUTH_AZUREAD_OAUTH2_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('Azure AD OAuth2 Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('Azure AD OAuth2'), - category_slug='azuread-oauth2', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_AZUREAD_OAUTH2_KEY', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('Azure AD OAuth2 Key'), + help_text=_('The OAuth2 key (Client ID) from your Azure AD application.'), + category=_('Azure AD OAuth2'), + category_slug='azuread-oauth2', + ) -register( - 'SOCIAL_AUTH_AZUREAD_OAUTH2_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('Azure AD OAuth2 Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('Azure AD OAuth2'), - category_slug='azuread-oauth2', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_AZUREAD_OAUTH2_SECRET', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('Azure AD OAuth2 Secret'), + help_text=_('The OAuth2 secret (Client Secret) from your Azure AD application.'), + category=_('Azure AD OAuth2'), + category_slug='azuread-oauth2', + encrypted=True, + ) -############################################################################### -# Generic OIDC AUTHENTICATION SETTINGS -############################################################################### - -register( - 'SOCIAL_AUTH_OIDC_KEY', - field_class=fields.CharField, - allow_null=False, - default=None, - label=_('OIDC Key'), - help_text='The OIDC key (Client ID) from your IDP.', - category=_('Generic OIDC'), - category_slug='oidc', -) + register( + 'SOCIAL_AUTH_AZUREAD_OAUTH2_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('Azure AD OAuth2 Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('Azure AD OAuth2'), + category_slug='azuread-oauth2', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_OIDC_SECRET', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('OIDC Secret'), - help_text=_('The OIDC secret (Client Secret) from your IDP.'), - category=_('Generic OIDC'), - category_slug='oidc', - encrypted=True, -) + register( + 'SOCIAL_AUTH_AZUREAD_OAUTH2_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('Azure AD OAuth2 Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('Azure AD OAuth2'), + category_slug='azuread-oauth2', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_OIDC_OIDC_ENDPOINT', - field_class=fields.CharField, - allow_blank=True, - default='', - label=_('OIDC Provider URL'), - help_text=_('The URL for your OIDC provider including the path up to /.well-known/openid-configuration'), - category=_('Generic OIDC'), - category_slug='oidc', -) + ############################################################################### + # Generic OIDC AUTHENTICATION SETTINGS + ############################################################################### -register( - 'SOCIAL_AUTH_OIDC_VERIFY_SSL', - field_class=fields.BooleanField, - default=True, - label=_('Verify OIDC Provider Certificate'), - help_text=_('Verify the OIDC provider ssl certificate.'), - category=_('Generic OIDC'), - category_slug='oidc', -) + register( + 'SOCIAL_AUTH_OIDC_KEY', + field_class=fields.CharField, + allow_null=False, + default=None, + label=_('OIDC Key'), + help_text='The OIDC key (Client ID) from your IDP.', + category=_('Generic OIDC'), + category_slug='oidc', + ) -############################################################################### -# SAML AUTHENTICATION SETTINGS -############################################################################### + register( + 'SOCIAL_AUTH_OIDC_SECRET', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('OIDC Secret'), + help_text=_('The OIDC secret (Client Secret) from your IDP.'), + category=_('Generic OIDC'), + category_slug='oidc', + encrypted=True, + ) + register( + 'SOCIAL_AUTH_OIDC_OIDC_ENDPOINT', + field_class=fields.CharField, + allow_blank=True, + default='', + label=_('OIDC Provider URL'), + help_text=_('The URL for your OIDC provider including the path up to /.well-known/openid-configuration'), + category=_('Generic OIDC'), + category_slug='oidc', + ) -def get_saml_metadata_url(): - return urlparse.urljoin(settings.TOWER_URL_BASE, reverse('sso:saml_metadata')) + register( + 'SOCIAL_AUTH_OIDC_VERIFY_SSL', + field_class=fields.BooleanField, + default=True, + label=_('Verify OIDC Provider Certificate'), + help_text=_('Verify the OIDC provider ssl certificate.'), + category=_('Generic OIDC'), + category_slug='oidc', + ) + ############################################################################### + # SAML AUTHENTICATION SETTINGS + ############################################################################### -def get_saml_entity_id(): - return settings.TOWER_URL_BASE + def get_saml_metadata_url(): + return urlparse.urljoin(settings.TOWER_URL_BASE, reverse('sso:saml_metadata')) + def get_saml_entity_id(): + return settings.TOWER_URL_BASE -register( - 'SAML_AUTO_CREATE_OBJECTS', - field_class=fields.BooleanField, - default=True, - label=_('Automatically Create Organizations and Teams on SAML Login'), - help_text=_('When enabled (the default), mapped Organizations and Teams will be created automatically on successful SAML login.'), - category=_('SAML'), - category_slug='saml', -) + register( + 'SAML_AUTO_CREATE_OBJECTS', + field_class=fields.BooleanField, + default=True, + label=_('Automatically Create Organizations and Teams on SAML Login'), + help_text=_('When enabled (the default), mapped Organizations and Teams will be created automatically on successful SAML login.'), + category=_('SAML'), + category_slug='saml', + ) -register( - 'SOCIAL_AUTH_SAML_CALLBACK_URL', - field_class=fields.CharField, - read_only=True, - default=SocialAuthCallbackURL('saml'), - label=_('SAML Assertion Consumer Service (ACS) URL'), - help_text=_( - 'Register the service as a service provider (SP) with each identity ' - 'provider (IdP) you have configured. Provide your SP Entity ID ' - 'and this ACS URL for your application.' - ), - category=_('SAML'), - category_slug='saml', - depends_on=['TOWER_URL_BASE'], -) + register( + 'SOCIAL_AUTH_SAML_CALLBACK_URL', + field_class=fields.CharField, + read_only=True, + default=SocialAuthCallbackURL('saml'), + label=_('SAML Assertion Consumer Service (ACS) URL'), + help_text=_( + 'Register the service as a service provider (SP) with each identity ' + 'provider (IdP) you have configured. Provide your SP Entity ID ' + 'and this ACS URL for your application.' + ), + category=_('SAML'), + category_slug='saml', + depends_on=['TOWER_URL_BASE'], + ) -register( - 'SOCIAL_AUTH_SAML_METADATA_URL', - field_class=fields.CharField, - read_only=True, - default=get_saml_metadata_url, - label=_('SAML Service Provider Metadata URL'), - help_text=_('If your identity provider (IdP) allows uploading an XML metadata file, you can download one from this URL.'), - category=_('SAML'), - category_slug='saml', -) + register( + 'SOCIAL_AUTH_SAML_METADATA_URL', + field_class=fields.CharField, + read_only=True, + default=get_saml_metadata_url, + label=_('SAML Service Provider Metadata URL'), + help_text=_('If your identity provider (IdP) allows uploading an XML metadata file, you can download one from this URL.'), + category=_('SAML'), + category_slug='saml', + ) -register( - 'SOCIAL_AUTH_SAML_SP_ENTITY_ID', - field_class=fields.CharField, - allow_blank=True, - default=get_saml_entity_id, - label=_('SAML Service Provider Entity ID'), - help_text=_( - 'The application-defined unique identifier used as the ' - 'audience of the SAML service provider (SP) configuration. ' - 'This is usually the URL for the service.' - ), - category=_('SAML'), - category_slug='saml', - depends_on=['TOWER_URL_BASE'], -) + register( + 'SOCIAL_AUTH_SAML_SP_ENTITY_ID', + field_class=fields.CharField, + allow_blank=True, + default=get_saml_entity_id, + label=_('SAML Service Provider Entity ID'), + help_text=_( + 'The application-defined unique identifier used as the ' + 'audience of the SAML service provider (SP) configuration. ' + 'This is usually the URL for the service.' + ), + category=_('SAML'), + category_slug='saml', + depends_on=['TOWER_URL_BASE'], + ) -register( - 'SOCIAL_AUTH_SAML_SP_PUBLIC_CERT', - field_class=fields.CharField, - allow_blank=True, - validators=[validate_certificate], - label=_('SAML Service Provider Public Certificate'), - help_text=_('Create a keypair to use as a service provider (SP) and include the certificate content here.'), - category=_('SAML'), - category_slug='saml', -) + register( + 'SOCIAL_AUTH_SAML_SP_PUBLIC_CERT', + field_class=fields.CharField, + allow_blank=True, + validators=[validate_certificate], + label=_('SAML Service Provider Public Certificate'), + help_text=_('Create a keypair to use as a service provider (SP) and include the certificate content here.'), + category=_('SAML'), + category_slug='saml', + ) -register( - 'SOCIAL_AUTH_SAML_SP_PRIVATE_KEY', - field_class=fields.CharField, - allow_blank=True, - validators=[validate_private_key], - label=_('SAML Service Provider Private Key'), - help_text=_('Create a keypair to use as a service provider (SP) and include the private key content here.'), - category=_('SAML'), - category_slug='saml', - encrypted=True, -) + register( + 'SOCIAL_AUTH_SAML_SP_PRIVATE_KEY', + field_class=fields.CharField, + allow_blank=True, + validators=[validate_private_key], + label=_('SAML Service Provider Private Key'), + help_text=_('Create a keypair to use as a service provider (SP) and include the private key content here.'), + category=_('SAML'), + category_slug='saml', + encrypted=True, + ) -register( - 'SOCIAL_AUTH_SAML_ORG_INFO', - field_class=SAMLOrgInfoField, - label=_('SAML Service Provider Organization Info'), - help_text=_('Provide the URL, display name, and the name of your app. Refer to the documentation for example syntax.'), - category=_('SAML'), - category_slug='saml', - placeholder=collections.OrderedDict( - [('en-US', collections.OrderedDict([('name', 'example'), ('displayname', 'Example'), ('url', 'http://www.example.com')]))] - ), -) + register( + 'SOCIAL_AUTH_SAML_ORG_INFO', + field_class=SAMLOrgInfoField, + label=_('SAML Service Provider Organization Info'), + help_text=_('Provide the URL, display name, and the name of your app. Refer to the documentation for example syntax.'), + category=_('SAML'), + category_slug='saml', + placeholder=collections.OrderedDict( + [('en-US', collections.OrderedDict([('name', 'example'), ('displayname', 'Example'), ('url', 'http://www.example.com')]))] + ), + ) -register( - 'SOCIAL_AUTH_SAML_TECHNICAL_CONTACT', - field_class=SAMLContactField, - allow_blank=True, - label=_('SAML Service Provider Technical Contact'), - help_text=_('Provide the name and email address of the technical contact for your service provider. Refer to the documentation for example syntax.'), - category=_('SAML'), - category_slug='saml', - placeholder=collections.OrderedDict([('givenName', 'Technical Contact'), ('emailAddress', 'techsup@example.com')]), -) + register( + 'SOCIAL_AUTH_SAML_TECHNICAL_CONTACT', + field_class=SAMLContactField, + allow_blank=True, + label=_('SAML Service Provider Technical Contact'), + help_text=_('Provide the name and email address of the technical contact for your service provider. Refer to the documentation for example syntax.'), + category=_('SAML'), + category_slug='saml', + placeholder=collections.OrderedDict([('givenName', 'Technical Contact'), ('emailAddress', 'techsup@example.com')]), + ) -register( - 'SOCIAL_AUTH_SAML_SUPPORT_CONTACT', - field_class=SAMLContactField, - allow_blank=True, - label=_('SAML Service Provider Support Contact'), - help_text=_('Provide the name and email address of the support contact for your service provider. Refer to the documentation for example syntax.'), - category=_('SAML'), - category_slug='saml', - placeholder=collections.OrderedDict([('givenName', 'Support Contact'), ('emailAddress', 'support@example.com')]), -) + register( + 'SOCIAL_AUTH_SAML_SUPPORT_CONTACT', + field_class=SAMLContactField, + allow_blank=True, + label=_('SAML Service Provider Support Contact'), + help_text=_('Provide the name and email address of the support contact for your service provider. Refer to the documentation for example syntax.'), + category=_('SAML'), + category_slug='saml', + placeholder=collections.OrderedDict([('givenName', 'Support Contact'), ('emailAddress', 'support@example.com')]), + ) -register( - 'SOCIAL_AUTH_SAML_ENABLED_IDPS', - field_class=SAMLEnabledIdPsField, - default={}, - label=_('SAML Enabled Identity Providers'), - help_text=_( - 'Configure the Entity ID, SSO URL and certificate for each identity' - ' provider (IdP) in use. Multiple SAML IdPs are supported. Some IdPs' - ' may provide user data using attribute names that differ from the' - ' default OIDs. Attribute names may be overridden for each IdP. Refer' - ' to the Ansible documentation for additional details and syntax.' - ), - category=_('SAML'), - category_slug='saml', - placeholder=collections.OrderedDict( - [ - ( - 'Okta', - collections.OrderedDict( - [ - ('entity_id', 'http://www.okta.com/HHniyLkaxk9e76wD0Thh'), - ('url', 'https://dev-123456.oktapreview.com/app/ansibletower/HHniyLkaxk9e76wD0Thh/sso/saml'), - ('x509cert', 'MIIDpDCCAoygAwIBAgIGAVVZ4rPzMA0GCSqGSIb3...'), - ('attr_user_permanent_id', 'username'), - ('attr_first_name', 'first_name'), - ('attr_last_name', 'last_name'), - ('attr_username', 'username'), - ('attr_email', 'email'), - ] + register( + 'SOCIAL_AUTH_SAML_ENABLED_IDPS', + field_class=SAMLEnabledIdPsField, + default={}, + label=_('SAML Enabled Identity Providers'), + help_text=_( + 'Configure the Entity ID, SSO URL and certificate for each identity' + ' provider (IdP) in use. Multiple SAML IdPs are supported. Some IdPs' + ' may provide user data using attribute names that differ from the' + ' default OIDs. Attribute names may be overridden for each IdP. Refer' + ' to the Ansible documentation for additional details and syntax.' + ), + category=_('SAML'), + category_slug='saml', + placeholder=collections.OrderedDict( + [ + ( + 'Okta', + collections.OrderedDict( + [ + ('entity_id', 'http://www.okta.com/HHniyLkaxk9e76wD0Thh'), + ('url', 'https://dev-123456.oktapreview.com/app/ansibletower/HHniyLkaxk9e76wD0Thh/sso/saml'), + ('x509cert', 'MIIDpDCCAoygAwIBAgIGAVVZ4rPzMA0GCSqGSIb3...'), + ('attr_user_permanent_id', 'username'), + ('attr_first_name', 'first_name'), + ('attr_last_name', 'last_name'), + ('attr_username', 'username'), + ('attr_email', 'email'), + ] + ), ), - ), - ( - 'OneLogin', - collections.OrderedDict( - [ - ('entity_id', 'https://app.onelogin.com/saml/metadata/123456'), - ('url', 'https://example.onelogin.com/trust/saml2/http-post/sso/123456'), - ('x509cert', 'MIIEJjCCAw6gAwIBAgIUfuSD54OPSBhndDHh3gZo...'), - ('attr_user_permanent_id', 'name_id'), - ('attr_first_name', 'User.FirstName'), - ('attr_last_name', 'User.LastName'), - ('attr_username', 'User.email'), - ('attr_email', 'User.email'), - ] + ( + 'OneLogin', + collections.OrderedDict( + [ + ('entity_id', 'https://app.onelogin.com/saml/metadata/123456'), + ('url', 'https://example.onelogin.com/trust/saml2/http-post/sso/123456'), + ('x509cert', 'MIIEJjCCAw6gAwIBAgIUfuSD54OPSBhndDHh3gZo...'), + ('attr_user_permanent_id', 'name_id'), + ('attr_first_name', 'User.FirstName'), + ('attr_last_name', 'User.LastName'), + ('attr_username', 'User.email'), + ('attr_email', 'User.email'), + ] + ), ), - ), - ] - ), -) - -register( - 'SOCIAL_AUTH_SAML_SECURITY_CONFIG', - field_class=SAMLSecurityField, - allow_null=True, - default={'requestedAuthnContext': False}, - label=_('SAML Security Config'), - help_text=_('A dict of key value pairs that are passed to the underlying python-saml security setting https://github.com/onelogin/python-saml#settings'), - category=_('SAML'), - category_slug='saml', - placeholder=collections.OrderedDict( - [ - ("nameIdEncrypted", False), - ("authnRequestsSigned", False), - ("logoutRequestSigned", False), - ("logoutResponseSigned", False), - ("signMetadata", False), - ("wantMessagesSigned", False), - ("wantAssertionsSigned", False), - ("wantAssertionsEncrypted", False), - ("wantNameId", True), - ("wantNameIdEncrypted", False), - ("wantAttributeStatement", True), - ("requestedAuthnContext", True), - ("requestedAuthnContextComparison", "exact"), - ("metadataValidUntil", "2015-06-26T20:00:00Z"), - ("metadataCacheDuration", "PT518400S"), - ("signatureAlgorithm", "http://www.w3.org/2000/09/xmldsig#rsa-sha1"), - ("digestAlgorithm", "http://www.w3.org/2000/09/xmldsig#sha1"), - ] - ), -) + ] + ), + ) -register( - 'SOCIAL_AUTH_SAML_SP_EXTRA', - field_class=fields.DictField, - allow_null=True, - default=None, - label=_('SAML Service Provider extra configuration data'), - help_text=_('A dict of key value pairs to be passed to the underlying python-saml Service Provider configuration setting.'), - category=_('SAML'), - category_slug='saml', - placeholder=collections.OrderedDict(), -) + register( + 'SOCIAL_AUTH_SAML_SECURITY_CONFIG', + field_class=SAMLSecurityField, + allow_null=True, + default={'requestedAuthnContext': False}, + label=_('SAML Security Config'), + help_text=_( + 'A dict of key value pairs that are passed to the underlying python-saml security setting https://github.com/onelogin/python-saml#settings' + ), + category=_('SAML'), + category_slug='saml', + placeholder=collections.OrderedDict( + [ + ("nameIdEncrypted", False), + ("authnRequestsSigned", False), + ("logoutRequestSigned", False), + ("logoutResponseSigned", False), + ("signMetadata", False), + ("wantMessagesSigned", False), + ("wantAssertionsSigned", False), + ("wantAssertionsEncrypted", False), + ("wantNameId", True), + ("wantNameIdEncrypted", False), + ("wantAttributeStatement", True), + ("requestedAuthnContext", True), + ("requestedAuthnContextComparison", "exact"), + ("metadataValidUntil", "2015-06-26T20:00:00Z"), + ("metadataCacheDuration", "PT518400S"), + ("signatureAlgorithm", "http://www.w3.org/2000/09/xmldsig#rsa-sha1"), + ("digestAlgorithm", "http://www.w3.org/2000/09/xmldsig#sha1"), + ] + ), + ) -register( - 'SOCIAL_AUTH_SAML_EXTRA_DATA', - field_class=fields.ListTuplesField, - allow_null=True, - default=None, - label=_('SAML IDP to extra_data attribute mapping'), - help_text=_('A list of tuples that maps IDP attributes to extra_attributes.' ' Each attribute will be a list of values, even if only 1 value.'), - category=_('SAML'), - category_slug='saml', - placeholder=[('attribute_name', 'extra_data_name_for_attribute'), ('department', 'department'), ('manager_full_name', 'manager_full_name')], -) + register( + 'SOCIAL_AUTH_SAML_SP_EXTRA', + field_class=fields.DictField, + allow_null=True, + default=None, + label=_('SAML Service Provider extra configuration data'), + help_text=_('A dict of key value pairs to be passed to the underlying python-saml Service Provider configuration setting.'), + category=_('SAML'), + category_slug='saml', + placeholder=collections.OrderedDict(), + ) -register( - 'SOCIAL_AUTH_SAML_ORGANIZATION_MAP', - field_class=SocialOrganizationMapField, - allow_null=True, - default=None, - label=_('SAML Organization Map'), - help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, - category=_('SAML'), - category_slug='saml', - placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_SAML_EXTRA_DATA', + field_class=fields.ListTuplesField, + allow_null=True, + default=None, + label=_('SAML IDP to extra_data attribute mapping'), + help_text=_('A list of tuples that maps IDP attributes to extra_attributes.' ' Each attribute will be a list of values, even if only 1 value.'), + category=_('SAML'), + category_slug='saml', + placeholder=[('attribute_name', 'extra_data_name_for_attribute'), ('department', 'department'), ('manager_full_name', 'manager_full_name')], + ) -register( - 'SOCIAL_AUTH_SAML_TEAM_MAP', - field_class=SocialTeamMapField, - allow_null=True, - default=None, - label=_('SAML Team Map'), - help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, - category=_('SAML'), - category_slug='saml', - placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, -) + register( + 'SOCIAL_AUTH_SAML_ORGANIZATION_MAP', + field_class=SocialOrganizationMapField, + allow_null=True, + default=None, + label=_('SAML Organization Map'), + help_text=SOCIAL_AUTH_ORGANIZATION_MAP_HELP_TEXT, + category=_('SAML'), + category_slug='saml', + placeholder=SOCIAL_AUTH_ORGANIZATION_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_SAML_ORGANIZATION_ATTR', - field_class=SAMLOrgAttrField, - allow_null=True, - default=None, - label=_('SAML Organization Attribute Mapping'), - help_text=_('Used to translate user organization membership.'), - category=_('SAML'), - category_slug='saml', - placeholder=collections.OrderedDict( - [ - ('saml_attr', 'organization'), - ('saml_admin_attr', 'organization_admin'), - ('saml_auditor_attr', 'organization_auditor'), - ('remove', True), - ('remove_admins', True), - ('remove_auditors', True), - ] - ), -) + register( + 'SOCIAL_AUTH_SAML_TEAM_MAP', + field_class=SocialTeamMapField, + allow_null=True, + default=None, + label=_('SAML Team Map'), + help_text=SOCIAL_AUTH_TEAM_MAP_HELP_TEXT, + category=_('SAML'), + category_slug='saml', + placeholder=SOCIAL_AUTH_TEAM_MAP_PLACEHOLDER, + ) -register( - 'SOCIAL_AUTH_SAML_TEAM_ATTR', - field_class=SAMLTeamAttrField, - allow_null=True, - default=None, - label=_('SAML Team Attribute Mapping'), - help_text=_('Used to translate user team membership.'), - category=_('SAML'), - category_slug='saml', - placeholder=collections.OrderedDict( - [ - ('saml_attr', 'team'), - ('remove', True), - ( - 'team_org_map', - [ - collections.OrderedDict([('team', 'Marketing'), ('organization', 'Red Hat')]), - collections.OrderedDict([('team', 'Human Resources'), ('organization', 'Red Hat')]), - collections.OrderedDict([('team', 'Engineering'), ('organization', 'Red Hat')]), - collections.OrderedDict([('team', 'Engineering'), ('organization', 'Ansible')]), - collections.OrderedDict([('team', 'Quality Engineering'), ('organization', 'Ansible')]), - collections.OrderedDict([('team', 'Sales'), ('organization', 'Ansible')]), - ], - ), - ] - ), -) + register( + 'SOCIAL_AUTH_SAML_ORGANIZATION_ATTR', + field_class=SAMLOrgAttrField, + allow_null=True, + default=None, + label=_('SAML Organization Attribute Mapping'), + help_text=_('Used to translate user organization membership.'), + category=_('SAML'), + category_slug='saml', + placeholder=collections.OrderedDict( + [ + ('saml_attr', 'organization'), + ('saml_admin_attr', 'organization_admin'), + ('saml_auditor_attr', 'organization_auditor'), + ('remove', True), + ('remove_admins', True), + ('remove_auditors', True), + ] + ), + ) -register( - 'SOCIAL_AUTH_SAML_USER_FLAGS_BY_ATTR', - field_class=SAMLUserFlagsAttrField, - allow_null=True, - default=None, - label=_('SAML User Flags Attribute Mapping'), - help_text=_('Used to map super users and system auditors from SAML.'), - category=_('SAML'), - category_slug='saml', - placeholder=[ - ('is_superuser_attr', 'saml_attr'), - ('is_superuser_value', ['value']), - ('is_superuser_role', ['saml_role']), - ('remove_superusers', True), - ('is_system_auditor_attr', 'saml_attr'), - ('is_system_auditor_value', ['value']), - ('is_system_auditor_role', ['saml_role']), - ('remove_system_auditors', True), - ], -) + register( + 'SOCIAL_AUTH_SAML_TEAM_ATTR', + field_class=SAMLTeamAttrField, + allow_null=True, + default=None, + label=_('SAML Team Attribute Mapping'), + help_text=_('Used to translate user team membership.'), + category=_('SAML'), + category_slug='saml', + placeholder=collections.OrderedDict( + [ + ('saml_attr', 'team'), + ('remove', True), + ( + 'team_org_map', + [ + collections.OrderedDict([('team', 'Marketing'), ('organization', 'Red Hat')]), + collections.OrderedDict([('team', 'Human Resources'), ('organization', 'Red Hat')]), + collections.OrderedDict([('team', 'Engineering'), ('organization', 'Red Hat')]), + collections.OrderedDict([('team', 'Engineering'), ('organization', 'Ansible')]), + collections.OrderedDict([('team', 'Quality Engineering'), ('organization', 'Ansible')]), + collections.OrderedDict([('team', 'Sales'), ('organization', 'Ansible')]), + ], + ), + ] + ), + ) -register( - 'LOCAL_PASSWORD_MIN_LENGTH', - field_class=fields.IntegerField, - min_value=0, - default=0, - label=_('Minimum number of characters in local password'), - help_text=_('Minimum number of characters required in a local password. 0 means no minimum'), - category=_('Authentication'), - category_slug='authentication', -) + register( + 'SOCIAL_AUTH_SAML_USER_FLAGS_BY_ATTR', + field_class=SAMLUserFlagsAttrField, + allow_null=True, + default=None, + label=_('SAML User Flags Attribute Mapping'), + help_text=_('Used to map super users and system auditors from SAML.'), + category=_('SAML'), + category_slug='saml', + placeholder=[ + ('is_superuser_attr', 'saml_attr'), + ('is_superuser_value', ['value']), + ('is_superuser_role', ['saml_role']), + ('remove_superusers', True), + ('is_system_auditor_attr', 'saml_attr'), + ('is_system_auditor_value', ['value']), + ('is_system_auditor_role', ['saml_role']), + ('remove_system_auditors', True), + ], + ) -register( - 'LOCAL_PASSWORD_MIN_DIGITS', - field_class=fields.IntegerField, - min_value=0, - default=0, - label=_('Minimum number of digit characters in local password'), - help_text=_('Minimum number of digit characters required in a local password. 0 means no minimum'), - category=_('Authentication'), - category_slug='authentication', -) + register( + 'LOCAL_PASSWORD_MIN_LENGTH', + field_class=fields.IntegerField, + min_value=0, + default=0, + label=_('Minimum number of characters in local password'), + help_text=_('Minimum number of characters required in a local password. 0 means no minimum'), + category=_('Authentication'), + category_slug='authentication', + ) -register( - 'LOCAL_PASSWORD_MIN_UPPER', - field_class=fields.IntegerField, - min_value=0, - default=0, - label=_('Minimum number of uppercase characters in local password'), - help_text=_('Minimum number of uppercase characters required in a local password. 0 means no minimum'), - category=_('Authentication'), - category_slug='authentication', -) + register( + 'LOCAL_PASSWORD_MIN_DIGITS', + field_class=fields.IntegerField, + min_value=0, + default=0, + label=_('Minimum number of digit characters in local password'), + help_text=_('Minimum number of digit characters required in a local password. 0 means no minimum'), + category=_('Authentication'), + category_slug='authentication', + ) -register( - 'LOCAL_PASSWORD_MIN_SPECIAL', - field_class=fields.IntegerField, - min_value=0, - default=0, - label=_('Minimum number of special characters in local password'), - help_text=_('Minimum number of special characters required in a local password. 0 means no minimum'), - category=_('Authentication'), - category_slug='authentication', -) + register( + 'LOCAL_PASSWORD_MIN_UPPER', + field_class=fields.IntegerField, + min_value=0, + default=0, + label=_('Minimum number of uppercase characters in local password'), + help_text=_('Minimum number of uppercase characters required in a local password. 0 means no minimum'), + category=_('Authentication'), + category_slug='authentication', + ) + register( + 'LOCAL_PASSWORD_MIN_SPECIAL', + field_class=fields.IntegerField, + min_value=0, + default=0, + label=_('Minimum number of special characters in local password'), + help_text=_('Minimum number of special characters required in a local password. 0 means no minimum'), + category=_('Authentication'), + category_slug='authentication', + ) -def tacacs_validate(serializer, attrs): - if not serializer.instance or not hasattr(serializer.instance, 'TACACSPLUS_HOST') or not hasattr(serializer.instance, 'TACACSPLUS_SECRET'): + def tacacs_validate(serializer, attrs): + if not serializer.instance or not hasattr(serializer.instance, 'TACACSPLUS_HOST') or not hasattr(serializer.instance, 'TACACSPLUS_SECRET'): + return attrs + errors = [] + host = serializer.instance.TACACSPLUS_HOST + if 'TACACSPLUS_HOST' in attrs: + host = attrs['TACACSPLUS_HOST'] + secret = serializer.instance.TACACSPLUS_SECRET + if 'TACACSPLUS_SECRET' in attrs: + secret = attrs['TACACSPLUS_SECRET'] + if host and not secret: + errors.append('TACACSPLUS_SECRET is required when TACACSPLUS_HOST is provided.') + if errors: + raise serializers.ValidationError(_('\n'.join(errors))) return attrs - errors = [] - host = serializer.instance.TACACSPLUS_HOST - if 'TACACSPLUS_HOST' in attrs: - host = attrs['TACACSPLUS_HOST'] - secret = serializer.instance.TACACSPLUS_SECRET - if 'TACACSPLUS_SECRET' in attrs: - secret = attrs['TACACSPLUS_SECRET'] - if host and not secret: - errors.append('TACACSPLUS_SECRET is required when TACACSPLUS_HOST is provided.') - if errors: - raise serializers.ValidationError(_('\n'.join(errors))) - return attrs - - -register_validate('tacacsplus', tacacs_validate) + + register_validate('tacacsplus', tacacs_validate) diff --git a/awx/sso/tests/unit/test_ldap.py b/awx/sso/tests/unit/test_ldap.py index 300102934f79..aa54aaa49dbe 100644 --- a/awx/sso/tests/unit/test_ldap.py +++ b/awx/sso/tests/unit/test_ldap.py @@ -7,18 +7,18 @@ 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 == {} + 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 + 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(): diff --git a/awx/ui/src/components/Lookup/CredentialLookup.js b/awx/ui/src/components/Lookup/CredentialLookup.js index 5256c20e6b44..f1da6f391a2d 100644 --- a/awx/ui/src/components/Lookup/CredentialLookup.js +++ b/awx/ui/src/components/Lookup/CredentialLookup.js @@ -62,7 +62,7 @@ function CredentialLookup({ ? { credential_type: credentialTypeId } : {}; const typeKindParams = credentialTypeKind - ? { credential_type__kind: credentialTypeKind } + ? { credential_type__kind__in: credentialTypeKind } : {}; const typeNamespaceParams = credentialTypeNamespace ? { credential_type__namespace: credentialTypeNamespace } @@ -125,7 +125,7 @@ function CredentialLookup({ ? { credential_type: credentialTypeId } : {}; const typeKindParams = credentialTypeKind - ? { credential_type__kind: credentialTypeKind } + ? { credential_type__kind__in: credentialTypeKind } : {}; const typeNamespaceParams = credentialTypeNamespace ? { credential_type__namespace: credentialTypeNamespace } diff --git a/awx/ui/src/components/NotificationList/NotificationList.js b/awx/ui/src/components/NotificationList/NotificationList.js index 3b4171ec9034..e565d7fd1244 100644 --- a/awx/ui/src/components/NotificationList/NotificationList.js +++ b/awx/ui/src/components/NotificationList/NotificationList.js @@ -190,6 +190,7 @@ function NotificationList({ name: t`Notification type`, key: 'or__notification_type', options: [ + ['awssns', t`AWS SNS`], ['email', t`Email`], ['grafana', t`Grafana`], ['hipchat', t`Hipchat`], diff --git a/awx/ui/src/components/Workflow/WorkflowHelp.js b/awx/ui/src/components/Workflow/WorkflowHelp.js index 4b2251a7cef4..7789dc5ca08c 100644 --- a/awx/ui/src/components/Workflow/WorkflowHelp.js +++ b/awx/ui/src/components/Workflow/WorkflowHelp.js @@ -12,7 +12,7 @@ const Inner = styled.div` border-radius: 2px; color: white; left: 10px; - max-width: 300px; + max-width: 500px; padding: 5px 10px; position: absolute; top: 10px; diff --git a/awx/ui/src/components/Workflow/WorkflowNodeHelp.js b/awx/ui/src/components/Workflow/WorkflowNodeHelp.js index 30b423df9e32..3d66bd10f960 100644 --- a/awx/ui/src/components/Workflow/WorkflowNodeHelp.js +++ b/awx/ui/src/components/Workflow/WorkflowNodeHelp.js @@ -12,6 +12,7 @@ const GridDL = styled.dl` column-gap: 15px; display: grid; grid-template-columns: max-content; + overflow-wrap: anywhere; row-gap: 0px; dt { grid-column-start: 1; diff --git a/awx/ui/src/screens/Inventory/shared/Inventory.helptext.js b/awx/ui/src/screens/Inventory/shared/Inventory.helptext.js index 583862114bef..2be9d8b54d5d 100644 --- a/awx/ui/src/screens/Inventory/shared/Inventory.helptext.js +++ b/awx/ui/src/screens/Inventory/shared/Inventory.helptext.js @@ -22,7 +22,7 @@ const ansibleDocUrls = { constructed: 'https://docs.ansible.com/ansible/latest/collections/ansible/builtin/constructed_inventory.html', terraform: - 'https://github.com/ansible-collections/cloud.terraform/blob/stable-statefile-inventory/plugins/inventory/terraform_state.py', + 'https://github.com/ansible-collections/cloud.terraform/blob/main/docs/cloud.terraform.terraform_state_inventory.rst', }; const getInventoryHelpTextStrings = () => ({ diff --git a/awx/ui/src/screens/Inventory/shared/InventorySourceSubForms/SCMSubForm.js b/awx/ui/src/screens/Inventory/shared/InventorySourceSubForms/SCMSubForm.js index 043ddcebe7ac..5b772bf08a08 100644 --- a/awx/ui/src/screens/Inventory/shared/InventorySourceSubForms/SCMSubForm.js +++ b/awx/ui/src/screens/Inventory/shared/InventorySourceSubForms/SCMSubForm.js @@ -87,7 +87,7 @@ const SCMSubForm = ({ autoPopulateProject }) => { /> )} + {template.notification_type === 'awssns' && ( + <> + + + + + )} {template.notification_type === 'email' && ( <> diff --git a/awx/ui/src/screens/NotificationTemplate/NotificationTemplateList/NotificationTemplateList.js b/awx/ui/src/screens/NotificationTemplate/NotificationTemplateList/NotificationTemplateList.js index 5172fa3f38ba..bf5c430f8702 100644 --- a/awx/ui/src/screens/NotificationTemplate/NotificationTemplateList/NotificationTemplateList.js +++ b/awx/ui/src/screens/NotificationTemplate/NotificationTemplateList/NotificationTemplateList.js @@ -131,6 +131,7 @@ function NotificationTemplatesList() { name: t`Notification type`, key: 'or__notification_type', options: [ + ['awssns', t`AWS SNS`], ['email', t`Email`], ['grafana', t`Grafana`], ['hipchat', t`Hipchat`], diff --git a/awx/ui/src/screens/NotificationTemplate/constants.js b/awx/ui/src/screens/NotificationTemplate/constants.js index 5937e4874388..b376bdf2afd4 100644 --- a/awx/ui/src/screens/NotificationTemplate/constants.js +++ b/awx/ui/src/screens/NotificationTemplate/constants.js @@ -1,5 +1,6 @@ /* eslint-disable-next-line import/prefer-default-export */ export const NOTIFICATION_TYPES = { + awssns: 'AWS SNS', email: 'Email', grafana: 'Grafana', irc: 'IRC', diff --git a/awx/ui/src/screens/NotificationTemplate/shared/CustomMessagesSubForm.js b/awx/ui/src/screens/NotificationTemplate/shared/CustomMessagesSubForm.js index efdbd1c6e7db..2ff4e5e04129 100644 --- a/awx/ui/src/screens/NotificationTemplate/shared/CustomMessagesSubForm.js +++ b/awx/ui/src/screens/NotificationTemplate/shared/CustomMessagesSubForm.js @@ -11,8 +11,8 @@ import getDocsBaseUrl from 'util/getDocsBaseUrl'; function CustomMessagesSubForm({ defaultMessages, type }) { const [useCustomField, , useCustomHelpers] = useField('useCustomMessages'); - const showMessages = type !== 'webhook'; - const showBodies = ['email', 'pagerduty', 'webhook'].includes(type); + const showMessages = !['webhook', 'awssns'].includes(type); + const showBodies = ['email', 'pagerduty', 'webhook', 'awssns'].includes(type); const { setFieldValue } = useFormikContext(); const config = useConfig(); diff --git a/awx/ui/src/screens/NotificationTemplate/shared/NotificationTemplateForm.js b/awx/ui/src/screens/NotificationTemplate/shared/NotificationTemplateForm.js index 6c8a3493bb8f..75c4390ab826 100644 --- a/awx/ui/src/screens/NotificationTemplate/shared/NotificationTemplateForm.js +++ b/awx/ui/src/screens/NotificationTemplate/shared/NotificationTemplateForm.js @@ -78,6 +78,7 @@ function NotificationTemplateFormFields({ defaultMessages, template }) { label: t`Choose a Notification Type`, isDisabled: true, }, + { value: 'awssns', key: 'awssns', label: t`AWS SNS` }, { value: 'email', key: 'email', label: t`E-mail` }, { value: 'grafana', key: 'grafana', label: 'Grafana' }, { value: 'irc', key: 'irc', label: 'IRC' }, diff --git a/awx/ui/src/screens/NotificationTemplate/shared/TypeInputsSubForm.js b/awx/ui/src/screens/NotificationTemplate/shared/TypeInputsSubForm.js index 270737169fc8..187acbe4fed7 100644 --- a/awx/ui/src/screens/NotificationTemplate/shared/TypeInputsSubForm.js +++ b/awx/ui/src/screens/NotificationTemplate/shared/TypeInputsSubForm.js @@ -29,6 +29,7 @@ import Popover from '../../../components/Popover/Popover'; import getHelpText from './Notifications.helptext'; const TypeFields = { + awssns: AWSSNSFields, email: EmailFields, grafana: GrafanaFields, irc: IRCFields, @@ -58,6 +59,44 @@ TypeInputsSubForm.propTypes = { export default TypeInputsSubForm; +function AWSSNSFields() { + return ( + <> + + + + + + + ); +} + function EmailFields() { const helpText = getHelpText(); return ( diff --git a/awx/ui/src/screens/NotificationTemplate/shared/notification-template-default-messages.json b/awx/ui/src/screens/NotificationTemplate/shared/notification-template-default-messages.json index e2bd0ccaedba..47ee1d01bb2f 100644 --- a/awx/ui/src/screens/NotificationTemplate/shared/notification-template-default-messages.json +++ b/awx/ui/src/screens/NotificationTemplate/shared/notification-template-default-messages.json @@ -203,6 +203,39 @@ } } }, + "awssns": { + "started": { + "body": "{{ job_metadata }}" + }, + "success": { + "body": "{{ job_metadata }}" + }, + "error": { + "body": "{{ job_metadata }}" + }, + "workflow_approval": { + "running": { + "body": { + "body": "The approval node \"{{ approval_node_name }}\" needs review. This node can be viewed at: {{ workflow_url }}" + } + }, + "approved": { + "body": { + "body": "The approval node \"{{ approval_node_name }}\" was approved. {{ workflow_url }}" + } + }, + "timed_out": { + "body": { + "body": "The approval node \"{{ approval_node_name }}\" has timed out. {{ workflow_url }}" + } + }, + "denied": { + "body": { + "body": "The approval node \"{{ approval_node_name }}\" was denied. {{ workflow_url }}" + } + } + } + }, "mattermost": { "started": { "message": "{{ job_friendly_name }} #{{ job.id }} '{{ job.name }}' {{ job.status }}: {{ url }}", diff --git a/awx/ui/src/screens/NotificationTemplate/shared/typeFieldNames.js b/awx/ui/src/screens/NotificationTemplate/shared/typeFieldNames.js index acfbd88097f8..1acbd981e388 100644 --- a/awx/ui/src/screens/NotificationTemplate/shared/typeFieldNames.js +++ b/awx/ui/src/screens/NotificationTemplate/shared/typeFieldNames.js @@ -1,4 +1,11 @@ const typeFieldNames = { + awssns: [ + 'aws_region', + 'aws_access_key_id', + 'aws_secret_access_key', + 'aws_session_token', + 'sns_topic_arn', + ], email: [ 'username', 'password', diff --git a/awx/ui/src/types.js b/awx/ui/src/types.js index e81ee356ab9b..610dc33713eb 100644 --- a/awx/ui/src/types.js +++ b/awx/ui/src/types.js @@ -374,6 +374,7 @@ export const CredentialType = shape({ }); export const NotificationType = oneOf([ + 'awssns', 'email', 'grafana', 'irc', diff --git a/awx_collection/plugins/module_utils/controller_api.py b/awx_collection/plugins/module_utils/controller_api.py index 0f48fc2dff1c..541639306ac2 100644 --- a/awx_collection/plugins/module_utils/controller_api.py +++ b/awx_collection/plugins/module_utils/controller_api.py @@ -17,7 +17,7 @@ import re from json import loads, dumps from os.path import isfile, expanduser, split, join, exists, isdir -from os import access, R_OK, getcwd, environ +from os import access, R_OK, getcwd, environ, getenv try: @@ -107,7 +107,7 @@ def __init__(self, argument_spec=None, direct_params=None, error_callback=None, # Perform magic depending on whether controller_oauthtoken is a string or a dict if self.params.get('controller_oauthtoken'): token_param = self.params.get('controller_oauthtoken') - if type(token_param) is dict: + if isinstance(token_param, dict): if 'token' in token_param: self.oauth_token = self.params.get('controller_oauthtoken')['token'] else: @@ -148,9 +148,10 @@ def build_url(self, endpoint, query_params=None): # Make sure we start with /api/vX if not endpoint.startswith("/"): endpoint = "/{0}".format(endpoint) - prefix = self.url_prefix.rstrip("/") - if not endpoint.startswith(prefix + "/api/"): - endpoint = prefix + "/api/v2{0}".format(endpoint) + hostname_prefix = self.url_prefix.rstrip("/") + api_path = self.api_path() + if not endpoint.startswith(hostname_prefix + api_path): + endpoint = hostname_prefix + f"{api_path}v2{endpoint}" if not endpoint.endswith('/') and '?' not in endpoint: endpoint = "{0}/".format(endpoint) @@ -215,7 +216,7 @@ def load_config(self, config_path): try: config_data = yaml.load(config_string, Loader=yaml.SafeLoader) # If this is an actual ini file, yaml will return the whole thing as a string instead of a dict - if type(config_data) is not dict: + if not isinstance(config_data, dict): raise AssertionError("The yaml config file is not properly formatted as a dict.") try_config_parsing = False @@ -257,7 +258,7 @@ def load_config(self, config_path): if honorred_setting in config_data: # Veriffy SSL must be a boolean if honorred_setting == 'verify_ssl': - if type(config_data[honorred_setting]) is str: + if isinstance(config_data[honorred_setting], str): setattr(self, honorred_setting, strtobool(config_data[honorred_setting])) else: setattr(self, honorred_setting, bool(config_data[honorred_setting])) @@ -603,6 +604,14 @@ def make_request(self, method, endpoint, *args, **kwargs): status_code = response.status return {'status_code': status_code, 'json': response_json} + def api_path(self): + + default_api_path = "/api/" + if self._COLLECTION_TYPE != "awx": + default_api_path = "/api/controller/" + prefix = getenv('CONTROLLER_OPTIONAL_API_URLPATTERN_PREFIX', default_api_path) + return prefix + def authenticate(self, **kwargs): if self.username and self.password: # Attempt to get a token from /api/v2/tokens/ by giving it our username/password combo @@ -613,7 +622,7 @@ def authenticate(self, **kwargs): "scope": "write", } # Preserve URL prefix - endpoint = self.url_prefix.rstrip('/') + '/api/v2/tokens/' + endpoint = self.url_prefix.rstrip('/') + f'{self.api_path()}v2/tokens/' # Post to the tokens endpoint with baisc auth to try and get a token api_token_url = (self.url._replace(path=endpoint)).geturl() @@ -1002,7 +1011,7 @@ def logout(self): if self.authenticated and self.oauth_token_id: # Attempt to delete our current token from /api/v2/tokens/ # Post to the tokens endpoint with baisc auth to try and get a token - endpoint = self.url_prefix.rstrip('/') + '/api/v2/tokens/{0}/'.format(self.oauth_token_id) + endpoint = self.url_prefix.rstrip('/') + f'{self.api_path()}v2/tokens/{self.oauth_token_id}/' api_token_url = (self.url._replace(path=endpoint, query=None)).geturl() # in error cases, fail_json exists before exception handling try: diff --git a/awx_collection/plugins/modules/ad_hoc_command.py b/awx_collection/plugins/modules/ad_hoc_command.py index 5864d392a5c7..10d1c7e3520a 100644 --- a/awx_collection/plugins/modules/ad_hoc_command.py +++ b/awx_collection/plugins/modules/ad_hoc_command.py @@ -163,7 +163,7 @@ def main(): for arg in ['job_type', 'limit', 'forks', 'verbosity', 'extra_vars', 'become_enabled', 'diff_mode']: if module.params.get(arg): # extra_var can receive a dict or a string, if a dict covert it to a string - if arg == 'extra_vars' and type(module.params.get(arg)) is not str: + if arg == 'extra_vars' and not isinstance(module.params.get(arg), str): post_data[arg] = json.dumps(module.params.get(arg)) else: post_data[arg] = module.params.get(arg) diff --git a/awx_collection/plugins/modules/import.py b/awx_collection/plugins/modules/import.py index fe66b2a7a3c4..ae0180ccd173 100644 --- a/awx_collection/plugins/modules/import.py +++ b/awx_collection/plugins/modules/import.py @@ -56,7 +56,7 @@ # In this module we don't use EXPORTABLE_RESOURCES, we just want to validate that our installed awxkit has import/export try: - from awxkit.api.pages.api import EXPORTABLE_RESOURCES # noqa + from awxkit.api.pages.api import EXPORTABLE_RESOURCES # noqa: F401; pylint: disable=unused-import HAS_EXPORTABLE_RESOURCES = True except ImportError: diff --git a/awx_collection/plugins/modules/inventory_source.py b/awx_collection/plugins/modules/inventory_source.py index 6c65086e322f..738bf11bfd81 100644 --- a/awx_collection/plugins/modules/inventory_source.py +++ b/awx_collection/plugins/modules/inventory_source.py @@ -42,7 +42,7 @@ source: description: - The source to use for this group. - choices: [ "scm", "ec2", "gce", "azure_rm", "vmware", "satellite6", "openstack", "rhv", "controller", "insights", "openshift_virtualization" ] + choices: [ "scm", "ec2", "gce", "azure_rm", "vmware", "satellite6", "openstack", "rhv", "controller", "insights", "terraform", "openshift_virtualization" ] type: str source_path: description: @@ -170,7 +170,7 @@ def main(): # # How do we handle manual and file? The controller does not seem to be able to activate them # - source=dict(choices=["scm", "ec2", "gce", "azure_rm", "vmware", "satellite6", "openstack", "rhv", "controller", "insights", "openshift_virtualization"]), + source=dict(choices=["scm", "ec2", "gce", "azure_rm", "vmware", "satellite6", "openstack", "rhv", "controller", "insights", "terraform", "openshift_virtualization"]), source_path=dict(), source_vars=dict(type='dict'), enabled_var=dict(), diff --git a/awx_collection/plugins/modules/notification_template.py b/awx_collection/plugins/modules/notification_template.py index bb1df60d3857..e44e2be5e06c 100644 --- a/awx_collection/plugins/modules/notification_template.py +++ b/awx_collection/plugins/modules/notification_template.py @@ -50,6 +50,7 @@ description: - The type of notification to be sent. choices: + - 'awssns' - 'email' - 'grafana' - 'irc' @@ -219,7 +220,7 @@ def main(): copy_from=dict(), description=dict(), organization=dict(), - notification_type=dict(choices=['email', 'grafana', 'irc', 'mattermost', 'pagerduty', 'rocketchat', 'slack', 'twilio', 'webhook']), + notification_type=dict(choices=['awssns', 'email', 'grafana', 'irc', 'mattermost', 'pagerduty', 'rocketchat', 'slack', 'twilio', 'webhook']), notification_configuration=dict(type='dict'), messages=dict(type='dict'), state=dict(choices=['present', 'absent', 'exists'], default='present'), diff --git a/awx_collection/test/awx/conftest.py b/awx_collection/test/awx/conftest.py index b7fb6333dd31..42500342ac9c 100644 --- a/awx_collection/test/awx/conftest.py +++ b/awx_collection/test/awx/conftest.py @@ -19,7 +19,7 @@ from ansible_base.rbac.models import RoleDefinition, DABPermission from awx.main.tests.functional.conftest import _request -from awx.main.tests.functional.conftest import credentialtype_scm, credentialtype_ssh # noqa: F401; pylint: disable=unused-variable +from awx.main.tests.functional.conftest import credentialtype_scm, credentialtype_ssh # noqa: F401; pylint: disable=unused-import from awx.main.models import ( Organization, Project, diff --git a/awx_collection/tests/sanity/ignore-2.17.txt b/awx_collection/tests/sanity/ignore-2.17.txt new file mode 100644 index 000000000000..19512ea0c162 --- /dev/null +++ b/awx_collection/tests/sanity/ignore-2.17.txt @@ -0,0 +1 @@ +plugins/modules/export.py validate-modules:nonexistent-parameter-documented # needs awxkit to construct argspec diff --git a/awxkit/awxkit/api/pages/api.py b/awxkit/awxkit/api/pages/api.py index 13f82e3a06b9..2283f10c96ed 100644 --- a/awxkit/awxkit/api/pages/api.py +++ b/awxkit/awxkit/api/pages/api.py @@ -317,7 +317,10 @@ def _import_list(self, endpoint, assets): if asset['natural_key']['type'] == 'project' and 'local_path' in post_data and _page['scm_type'] == post_data['scm_type']: del post_data['local_path'] - _page = _page.put(post_data) + if asset['natural_key']['type'] == 'user': + _page = _page.patch(**post_data) + else: + _page = _page.put(post_data) changed = True except (exc.Common, AssertionError) as e: identifier = asset.get("name", None) or asset.get("username", None) or asset.get("hostname", None) diff --git a/awxkit/awxkit/api/pages/notification_templates.py b/awxkit/awxkit/api/pages/notification_templates.py index 3d33300ce87e..b12bbc8c9704 100644 --- a/awxkit/awxkit/api/pages/notification_templates.py +++ b/awxkit/awxkit/api/pages/notification_templates.py @@ -11,7 +11,7 @@ job_results = ('any', 'error', 'success') -notification_types = ('email', 'irc', 'pagerduty', 'slack', 'twilio', 'webhook', 'mattermost', 'grafana', 'rocketchat') +notification_types = ('awssns', 'email', 'irc', 'pagerduty', 'slack', 'twilio', 'webhook', 'mattermost', 'grafana', 'rocketchat') class NotificationTemplate(HasCopy, HasCreate, base.Base): @@ -58,7 +58,10 @@ def payload(self, organization, notification_type='slack', messages=not_provided if payload.notification_configuration == {}: services = config.credentials.notification_services - if notification_type == 'email': + if notification_type == 'awssns': + fields = ('aws_region', 'aws_access_key_id', 'aws_secret_access_key', 'aws_session_token', 'sns_topic_arn') + cred = services.awssns + elif notification_type == 'email': fields = ('host', 'username', 'password', 'port', 'use_ssl', 'use_tls', 'sender', 'recipients') cred = services.email elif notification_type == 'irc': diff --git a/awxkit/awxkit/cli/format.py b/awxkit/awxkit/cli/format.py index e7629a4b6918..de2de4726226 100644 --- a/awxkit/awxkit/cli/format.py +++ b/awxkit/awxkit/cli/format.py @@ -185,7 +185,7 @@ def format_human(output, fmt): def format_num(v): try: - return locale.format("%.*f", (0, int(v)), True) + return locale.format_string("%.*f", (0, int(v)), True) except (ValueError, TypeError): if isinstance(v, (list, dict)): return json.dumps(v) diff --git a/docs/docsite/rst/common/images/rbac_jt_team_access.png b/docs/docsite/rst/common/images/rbac_jt_team_access.png new file mode 100644 index 000000000000..ba4f0ce40854 Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_jt_team_access.png differ diff --git a/docs/docsite/rst/common/images/rbac_jt_user_access.png b/docs/docsite/rst/common/images/rbac_jt_user_access.png new file mode 100644 index 000000000000..1c5134a0780d Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_jt_user_access.png differ diff --git a/docs/docsite/rst/common/images/rbac_team_access_add-roles-review.png b/docs/docsite/rst/common/images/rbac_team_access_add-roles-review.png new file mode 100644 index 000000000000..fb380dddbc34 Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_team_access_add-roles-review.png differ diff --git a/docs/docsite/rst/common/images/rbac_team_access_add-roles-success.png b/docs/docsite/rst/common/images/rbac_team_access_add-roles-success.png new file mode 100644 index 000000000000..633dbbd96086 Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_team_access_add-roles-success.png differ diff --git a/docs/docsite/rst/common/images/rbac_team_access_add-roles.png b/docs/docsite/rst/common/images/rbac_team_access_add-roles.png new file mode 100644 index 000000000000..0597ea44a014 Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_team_access_add-roles.png differ diff --git a/docs/docsite/rst/common/images/rbac_team_access_apply-roles.png b/docs/docsite/rst/common/images/rbac_team_access_apply-roles.png new file mode 100644 index 000000000000..9f48984c99c8 Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_team_access_apply-roles.png differ diff --git a/docs/docsite/rst/common/images/rbac_user_access_add-roles-review.png b/docs/docsite/rst/common/images/rbac_user_access_add-roles-review.png new file mode 100644 index 000000000000..ba70d43fa072 Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_user_access_add-roles-review.png differ diff --git a/docs/docsite/rst/common/images/rbac_user_access_add-roles.png b/docs/docsite/rst/common/images/rbac_user_access_add-roles.png new file mode 100644 index 000000000000..af07da9e57a3 Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_user_access_add-roles.png differ diff --git a/docs/docsite/rst/common/images/rbac_user_access_apply-roles.png b/docs/docsite/rst/common/images/rbac_user_access_apply-roles.png new file mode 100644 index 000000000000..02f704d7ee8c Binary files /dev/null and b/docs/docsite/rst/common/images/rbac_user_access_apply-roles.png differ diff --git a/docs/docsite/rst/userguide/index.rst b/docs/docsite/rst/userguide/index.rst index 11d0ca09864c..01aa96857266 100644 --- a/docs/docsite/rst/userguide/index.rst +++ b/docs/docsite/rst/userguide/index.rst @@ -29,6 +29,7 @@ You can also find lots of AWX discussion and get answers to questions at `forum. organizations users teams + rbac credentials credential_types credential_plugins diff --git a/docs/docsite/rst/userguide/inventories.rst b/docs/docsite/rst/userguide/inventories.rst index 9a2cfb1a7839..e2b17bdf73d5 100644 --- a/docs/docsite/rst/userguide/inventories.rst +++ b/docs/docsite/rst/userguide/inventories.rst @@ -1096,7 +1096,7 @@ Terraform State pair: inventory source; Terraform state -This inventory source uses the `terraform_state `_ inventory plugin from the `cloud.terraform `_ collection. The plugin will parse a terraform state file and add hosts for AWS EC2, GCE, and Azure instances. +This inventory source uses the `terraform_state `_ inventory plugin from the `cloud.terraform `_ collection. The plugin will parse a terraform state file and add hosts for AWS EC2, GCE, and Azure instances. 1. To configure this type of sourced inventory, select **Terraform State** from the Source field. @@ -1104,7 +1104,7 @@ This inventory source uses the `terraform_state `. For Terraform, enable **Overwrite** and **Update on launch** options. -4. Use the **Source Variables** field to override variables used by the ``controller`` inventory plugin. Enter variables using either JSON or YAML syntax. Use the radio button to toggle between the two. For more information on these variables, see the `terraform_state `_ file for detail. +4. Use the **Source Variables** field to override variables used by the ``controller`` inventory plugin. Enter variables using either JSON or YAML syntax. Use the radio button to toggle between the two. For more information on these variables, see the `terraform_state `_ file for detail. The ``backend_type`` variable is required by the Terraform state inventory plugin. This should match the remote backend configured in the Terraform backend credential, here is an example for an Amazon S3 backend: diff --git a/docs/docsite/rst/userguide/notifications.rst b/docs/docsite/rst/userguide/notifications.rst index e7e823411188..ff7691c6fd19 100644 --- a/docs/docsite/rst/userguide/notifications.rst +++ b/docs/docsite/rst/userguide/notifications.rst @@ -84,6 +84,7 @@ Notification Types .. index:: pair: notifications; types + triple: notifications; types; AWS SNS triple: notifications; types; Email triple: notifications; types; Grafana triple: notifications; types; IRC @@ -101,6 +102,18 @@ Notification types supported with AWX: Each of these have their own configuration and behavioral semantics and testing them may need to be approached in different ways. Additionally, you can customize each type of notification down to a specific detail, or a set of criteria to trigger a notification. See :ref:`ug_custom_notifications` for more detail on configuring custom notifications. The following sections will give as much detail as possible on each type of notification. +AWS SNS +------- + +The AWS SNS(https://aws.amazon.com/sns/) notification type supports sending messages into an SNS topic. + +You must provide the following details to setup a SNS notification: + +- AWS Region +- AWS Access Key ID +- AWS Secret Access Key +- AWS SNS Topic ARN + Email ------- diff --git a/docs/docsite/rst/userguide/rbac.rst b/docs/docsite/rst/userguide/rbac.rst new file mode 100644 index 000000000000..62f02fa960ae --- /dev/null +++ b/docs/docsite/rst/userguide/rbac.rst @@ -0,0 +1,517 @@ +.. _rbac-ug: + +Role-Based Access Controls +========================== + +.. index:: + single: role-based access controls + pair: security; RBAC + +Role-Based Access Controls (RBAC) are built into AWX and allow administrators to delegate access to server inventories, organizations, and more. Administrators can also centralize the management of various credentials, allowing end users to leverage a needed secret without ever exposing that secret to the end user. RBAC controls allow AWX to help you increase security and streamline management. + +This chapter has two parts: the latest RBAC model (:ref:`rbac-dab-ug`) and the :ref:`existing RBAC ` implementation. + +.. _rbac-dab-ug: + +DAB RBAC +--------- + +.. index:: + single: DAB + single: roles + pair: DAB; RBAC + +This section describes the latest changes to RBAC, involving use of the ``django-ansible-base`` (DAB) library, to enhance existing roles, provide a uniformed model that is compatible with platform (enterprise) components, and allow creation of custom roles. However, the internals of the system in the backend have changes implemented, but they are not reflected yet in the AWX UI. The change to the backend maintains a compatibility layer so the “old” roles in the API still exists temporarily, until a fully-functional compatible UI replaces the existing roles. + +New functionality, specifically custom roles, are possible through direct API clients or the API browser, but the presentation in the AWX UI might not reflect the changes made in the API. + +The new DAB version of RBAC allows creation of custom roles which can be done via the ``/api/v2/role_definitions/`` endpoint. Then these can only be assigned using the new endpoints, ``/api/v2/role_user_assignments/`` and ``/api/v2/role_team_assignments/``. + +If you do not want to allow custom roles, you can change the setting ``ANSIBLE_BASE_ALLOW_CUSTOM_ROLES`` to ``False``. This is still a file-based setting for now. + +New “add” permissions are a major highlight of this change. You could create a custom organization role that allows users to create all (or some) types of resources, and apply it to a particular organization. So instead of allowing a user to edit all projects, they can create a new project, and after creating it, they will automatically get admin role just for the objects they created. + + +Resource access for teams +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This section provides a reference for managing team roles within individual resources as shown in the new UI and the corresponding API calls. + +Access the resource's **Team Access** tab to manage the team roles. + +.. image:: ../common/images/rbac_jt_team_access.png + +To obtain a list of team role assignments from the API: + +:: + + GET /api/v2/role_team_assignments/?object_id=&content_type__model=jobtemplate + +The columns are arranged so that the team name appears in the first column. The role name is under ``summary_fields.role_definition.name`` + +To revoke a role assignment for a team in the API: + +:: + + DELETE /api/v2/role_team_assignments// + + +Add roles +^^^^^^^^^^ + +Clicking the **Add roles** button from the **Team Access** tab opens the **Add roles** wizard, where you can select the teams to which you want to add roles. + +.. image:: ../common/images/rbac_team_access_add-roles.png + +To list the teams from the service endpoint: + +:: + + GET /api/v2/teams + + +The next step of the wizard in the controller UI is to apply roles to the selected team(s). + +.. image:: ../common/images/rbac_team_access_apply-roles.png + +To list available role definitions for the selected resource type in the API, issue the following, but replace ``content_type`` below to match the resource type: + +:: + + GET /api/v2/role_definitions/?content_type__model=jobtemplate + + +Finally, review your selections and click **Save** to save your changes. + +.. image:: ../common/images/rbac_team_access_add-roles-review.png + +To assign roles to selected teams in the API, you must assign a single role to individual teams separately by referencing the team ID and resource ID from the controller associated with the ``object_id``. + +Make a POST request to this resource (``jobtemplate.id`` in this example): + +:: + + POST /api/v2/role_team_assignments/ + +The following shows an example of the payload sent for the POST request made above: + +:: + + {"team": 25, "role_definition": 4, "object_id": "10"} + + +When changes are successfully applied via the UI, a message displays to confirm the changes: + +.. image:: ../common/images/rbac_team_access_add-roles-success.png + + +Resource access for users +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This section provides a reference for managing user roles within individual resources as shown in the new UI and the corresponding API calls. + +Access the resource's **User Access** tab to manage the user roles. + +.. image:: ../common/images/rbac_jt_user_access.png + +To obtain a list of user role assignments from the API: + +:: + + GET /api/v2/role_user_assignments/?object_id=&content_type__model=jobtemplate + +The columns are arranged so that the user name appears in the first column. The role name is under ``summary_fields.role_definition.name`` + +To revoke a role assignment for a user in the API: + +:: + + DELETE /api/v2/role_user_assignments// + + +Add roles +^^^^^^^^^^ + +Clicking the **Add roles** button from the **User Access** tab opens the **Add roles** wizard, where you can select the users to which you want to add roles. + +.. image:: ../common/images/rbac_user_access_add-roles.png + +To list the teams from the service endpoint: + +:: + + GET /api/v2/users + + +The next step of the wizard in the controller UI is to apply roles to the selected team(s). + +.. image:: ../common/images/rbac_user_access_apply-roles.png + +To list available role definitions for the selected resource type in the API, issue the following, but replace ``content_type`` below to match the resource type: + +:: + + GET /api/v2/role_definitions/?content_type__model=jobtemplate + + +Finally, review your selections and click **Save** to save your changes. + +.. image:: ../common/images/rbac_user_access_add-roles-review.png + +To assign roles to selected users in the API, you must assign a single role to individual users separately by referencing the user ID and resource ID from the controller associated with the ``object_id``. + +Make a POST request to this resource (``jobtemplate.id`` in this example): + +:: + + POST /api/v2/role_user_assignments/ + +The following shows an example of the payload sent for the POST request made above: + +:: + + {"user": 25, "role_definition": 4, "object_id": "10"} + +When changes are successfully applied via the UI, a message displays to confirm the changes: + +.. image:: ../common/images/rbac_team_access_add-roles-success.png + + +Custom roles +~~~~~~~~~~~~~ +.. index:: + single: DAB + single: custom roles + pair: custom; roles + +In the DAB RBAC model, Superusers have the ability to create, modify, and delete custom roles. + +To create a custom role, click the **Create role** button from the **Roles** resource in the UI, and provide the details of the new role: + +- **Name**: Required +- **Description**: Enter an arbitrary description as appropriate (optional) +- **Resource Type**: Required. Select the resource type from the drop-down menu (only one resource type per role allowed). This is equivalent to ``content_type`` in ``OPTIONS /api/v2/role_definitions`` for choices. +- Select permissions based on the selected of resource type. (Alan will provide an endpoint containing dictionary for available permissions based on content type (The UI can use this to maintain static readable translatable texts on the client side) TBD) + +Modifying a custom role only allows you to change the permissions but does not not allow changes to the content type. + +To delete a custom role: + +:: + + DELETE /api/v2/role_definitions/:id + + +.. _rbac-legacy-ug: + +Legacy RBAC model +------------------ + +.. index:: + single: roles + pair: legacy; RBAC + +As in the name, RBAC is role-based, and roles contain a list of permissions. This is a domain-centric concept, where organization-level roles can grant you a permission (like ``update_project``) to everything in that domain, including all projects in that organizations. + +There are a few main concepts that you should become familiar with regarding AWX's RBAC design--roles, resources, and users. Users can be members of a role, which gives them certain access to any resources associated with that role, or any resources associated with "descendant" roles. + +A role is essentially a list of permissions. Users are granted access to these capabilities and AWX's resources through the roles to which they are assigned or through roles inherited through the role hierarchy. + +Roles associate a group of capabilities with a group of users. All capabilities are derived from membership within a role. Users receive capabilities only through the roles to which they are assigned or through roles they inherit through the role hierarchy. All members of a role have all capabilities granted to that role. Within an organization, roles are relatively stable, while users and capabilities are both numerous and may change rapidly. Users can have many roles. + + +Role Hierarchy and Access Inheritance +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Imagine that you have an organization named "SomeCompany" and want to allow two people, "Josie" and "Carter", access to manage all the settings associated with that organization. You should make both people members of the organization's ``admin_role``. + +|user-role-relationship| + +.. |user-role-relationship| image:: ../common/images/user-role-relationship.png + +Often, you will have many Roles in a system and you will want some roles to include all of the capabilities of other roles. For example, you may want a System Administrator to have access to everything that an Organization Administrator has access to, who has everything that a Project Administrator has access to, and so on. + +This concept is referred to as the 'Role Hierarchy': + +- Parent roles get all capabilities bestowed on any child roles +- Members of roles automatically get all capabilities for the role they are a member of, as well as any child roles. + +The Role Hierarchy is represented by allowing Roles to have "Parent Roles". Any capability that a Role has is implicitly granted to any parent roles (or parents of those parents, and so on). + +|rbac-role-hierarchy| + +.. |rbac-role-hierarchy| image:: ../common/images/rbac-role-hierarchy.png + +Often, you will have many Roles in a system and you will want some roles to include all of the capabilities of other roles. For example, you may want a System Administrator to have access to everything that an Organization Administrator has access to, who has everything that a Project Administrator has access to, and so on. We refer to this concept as the 'Role Hierarchy' and it is represented by allowing Roles to have "Parent Roles". Any capability that a Role has is implicitly granted to any parent roles (or parents of those parents, and so on). Of course Roles can have more than one parent, and capabilities are implicitly granted to all parents. + +|rbac-heirarchy-morecomplex| + +.. |rbac-heirarchy-morecomplex| image:: ../common/images/rbac-heirarchy-morecomplex.png + +RBAC controls also give you the capability to explicitly permit User and Teams of Users to run playbooks against certain sets of hosts. Users and teams are restricted to just the sets of playbooks and hosts to which they are granted capabilities. And, with AWX, you can create or import as many Users and Teams as you require--create users and teams manually or import them from LDAP or Active Directory. + +RBACs are easiest to think of in terms of who or what can see, change, or delete an "object" for which a specific capability is being determined. + +Applying RBAC +~~~~~~~~~~~~~~~~~ + +The following sections cover how to apply AWX's RBAC system in your environment. + + +Editing Users +^^^^^^^^^^^^^^^ + +When editing a user, a AWX system administrator may specify the user as being either a *System Administrator* (also referred to as the Superuser) or a *System Auditor*. + +- System administrators implicitly inherit all capabilities for all objects (read/write/execute) within the AWX environment. +- System Auditors implicitly inherit the read-only capability for all objects within the AWX environment. + +Editing Organizations +^^^^^^^^^^^^^^^^^^^^^^^^ + +When editing an organization, system administrators may specify the following roles: + +- One or more users as organization administrators +- One or more users as organization auditors +- And one or more users (or teams) as organization members + + +Users/teams that are members of an organization can view their organization administrator. + +Users who are organization administrators implicitly inherit all capabilities for all objects within that AWX organization. + +Users who are organization auditors implicitly inherit the read-only capability for all objects within that AWX organization. + + +Editing Projects in an Organization +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When editing a project in an organization for which they are the administrator, system administrators and organization administrators may specify: + +- One or more users/teams that are project administrators +- One or more users/teams that are project members +- And one or more users/teams that may update the project from SCM, from among the users/teams that are members of that organization. + +Users who are members of a project can view their project administrators. + +Project administrators implicitly inherit the capability to update the project from SCM. + +Administrators can also specify one or more users/teams (from those that are members of that project) that can use that project in a job template. + + +Creating Inventories and Credentials within an Organization +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +All access that is granted to use, read, or write credentials is handled through roles, which use AWX's RBAC system to grant ownership, auditor, or usage roles. + +System administrators and organization administrators may create inventories and credentials within organizations under their administrative capabilities. + +Whether editing an inventory or a credential, System administrators and organization administrators may specify one or more users/teams (from those that are members of that organization) to be granted the usage capability for that inventory or credential. + +System administrators and organization administrators may specify one or more users/teams (from those that are members of that organization) that have the capabilities to update (dynamic or manually) an inventory. Administrators can also execute ad hoc commands for an inventory. + + +Editing Job Templates +^^^^^^^^^^^^^^^^^^^^^^ + +System administrators, organization administrators, and project administrators, within a project under their administrative capabilities, may create and modify new job templates for that project. + +When editing a job template, administrators (AWX, organization, and project) can select among the inventory and credentials in the organization for which they have usage capabilities or they may leave those fields blank so that they will be selected at runtime. + +Additionally, they may specify one or more users/teams (from those that are members of that project) that have execution capabilities for that job template. The execution capability is valid regardless of any explicit capabilities the user/team may have been granted against the inventory or credential specified in the job template. + +User View +^^^^^^^^^^^^^ + +A user can: + +- See any organization or project for which they are a member +- Create their own credential objects which only belong to them +- See and execute any job template for which they have been granted execution capabilities + +If a job template that a user has been granted execution capabilities on does not specify an inventory or credential, the user will be prompted at run-time to select among the inventory and credentials in the organization they own or have been granted usage capabilities. + +Users that are job template administrators can make changes to job templates; however, to change to the inventory, project, playbook, credentials, or instance groups used in the job template, the user must also have the "Use" role for the project and inventory currently being used or being set. + +.. _rbac-ug-roles: + +Roles +~~~~~~~~~~~~~ + +All access that is granted to use, read, or write credentials is handled through roles, and roles are defined for a resource. + + +Built-in roles +^^^^^^^^^^^^^^ + +The following table lists the RBAC system roles and a brief description of the how that role is defined with regard to privileges in AWX. + ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| System Role | What it can do | ++=======================================================================+==========================================================================================+ +| System Administrator - System wide singleton | Manages all aspects of the system | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| System Auditor - System wide singleton | Views all aspects of the system | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Ad Hoc Role - Inventory | Runs ad hoc commands on an Inventory | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Admin Role - Organizations, Teams, Inventory, Projects, Job Templates | Manages all aspects of a defined Organization, Team, Inventory, Project, or Job Template | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Auditor Role - All | Views all aspects of a defined Organization, Team, Inventory, Project, or Job Template | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Execute Role - Job Templates | Runs assigned Job Template | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Member Role - Organization, Team | User is a member of a defined Organization or Team | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Read Role - Organizations, Teams, Inventory, Projects, Job Templates | Views all aspects of a defined Organization, Team, Inventory, Project, or Job Template | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Update Role - Project | Updates the Project from the configured source control management system | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Update Role - Inventory | Updates the Inventory using the cloud source update system | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Owner Role - Credential | Owns and manages all aspects of this Credential | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ +| Use Role - Credential, Inventory, Project, IGs, CGs | Uses the Credential, Inventory, Project, IGs, or CGs in a Job Template | ++-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ + + +A Singleton Role is a special role that grants system-wide permissions. AWX currently provides two built-in Singleton Roles but the ability to create or customize a Singleton Role is not supported at this time. + +Common Team Roles - "Personas" +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Support personnel typically works on ensuring that AWX is available and manages it a way to balance supportability and ease-of-use for users. Often, support will assign “Organization Owner/Admin” to users in order to allow them to create a new Organization and add members from their team the respective access needed. This minimizes supporting individuals and focuses more on maintaining uptime of the service and assisting users who are using AWX. + +Below are some common roles managed by the AWX Organization: + ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ +| | System Role | | Common User | | Description | +| | (for Organizations) | | Roles | | ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ +| | Owner | | Team Lead - | | This user has the ability to control access for other users in their organization. | +| | | Technical Lead | | They can add/remove and grant users specific access to projects, inventories, and job templates. | +| | | | This user also has the ability to create/remove/modify any aspect of an organization’s projects, | +| | | | templates, inventories, teams, and credentials. | ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ +| | Auditor | | Security Engineer - | | This account can view all aspects of the organization in read-only mode. | +| | | Project Manager | | This may be good for a user who checks in and maintains compliance. | +| | | | This might also be a good role for a service account who manages or | +| | | | ships job data from AWX to some other data collector. | ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ +| | Member - | | All other users | | These users by default as an organization member do not receive any access to any aspect | +| | Team | | | of the organization. In order to grant them access the respective organization owner needs | +| | | | to add them to their respective team and grant them Admin, Execute, Use, Update, Ad-hoc | +| | | | permissions to each component of the organization’s projects, inventories, and job templates. | ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ +| | Member - | | Power users - | | Organization Owners can provide “admin” through the team interface, over any component | +| | Team “Owner” | | Lead Developer | | of their organization including projects, inventories, and job templates. These users are able | +| | | | to modify and utilize the respective component given access. | ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ +| | Member - | | Developers - | | This will be the most common and allows the organization member the ability to execute | +| | Team “Execute” | | Engineers | | job templates and read permission to the specific components. This is permission applies to templates. | ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ +| | Member - | | Developers - | | This permission applies to an organization’s credentials, inventories, and projects. | +| | Team “Use” | | Engineers | | This permission allows the ability for a user to use the respective component within their job template.| ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ +| | Member - | | Developers - | | This permission applies to projects. Allows the user to be able to run an SCM update on a project. | +| | Team “Update” | | Engineers | | ++-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ + + +Function of roles: editing and creating +------------------------------------------ + +Organization “resource roles” functionality are specific to a certain resource type - such as workflows. Being a member of such a role usually provides two types of permissions, in the case of workflows, where a user is given a "workflow admin role" for the organization "Default": + +- this user can create new workflows in the organization "Default" +- user can edit all workflows in the "Default" organization + +One exception is job templates, where having the role is irrelevant of creation permission (more details on its own section). + +Independence of resource roles and organization membership roles +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Resource-specific organization roles are independent of the organization roles of admin and member. Having the "workflow admin role" for the "Default" organization will not allow a user to view all users in the organization, but having a "member" role in the "Default" organization will. The two types of roles are delegated independently of each other. + + +Necessary permissions to edit job templates +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Users can edit fields not impacting job runs (non-sensitive fields) with a Job Template admin role alone. However, to edit fields that impact job runs in a job template, a user needs the following: + +- **admin** role to the job template and container groups +- **use** role to related project +- **use** role to related inventory +- **use** role to related instance groups + +An "organization job template admin" role was introduced, but having this role isn't sufficient by itself to edit a job template within the organization if the user does not have use role to the project / inventory / instance group or an admin role to the container group that a job template uses. + +In order to delegate *full* job template control (within an organization) to a user or team, you will need grant the team or user all 3 organization-level roles: + +- job template admin +- project admin +- inventory admin + +This will ensure that the user (or all users who are members of the team with these roles) have full access to modify job templates in the organization. If a job template uses an inventory or project from another organization, the user with these organization roles may still not have permission to modify that job template. For clarity of managing permissions, it is best-practice to not mix projects / inventories from different organizations. + +RBAC permissions +^^^^^^^^^^^^^^^^^^^ + +Each role should have a content object, for instance, the org admin role has a content object of the org. To delegate a role, you need admin permission to the content object, with some exceptions that would result in you being able to reset a user's password. + +**Parent** is the organization. + +**Allow** is what this new permission will explicitly allow. + +**Scope** is the parent resource that this new role will be created on. Example: ``Organization.project_create_role``. + +An assumption is being made that the creator of the resource should be given the admin role for that resource. If there are any instances where resource creation does not also imply resource administration, they will be explicitly called out. + +Here are the rules associated with each admin type: + +**Project Admin** + +- Allow: Create, read, update, delete any project +- Scope: Organization +- User Interface: *Project Add Screen - Organizations* + +**Inventory Admin** + +- Parent: Org admin +- Allow: Create, read, update, delete any inventory +- Scope: Organization +- User Interface: *Inventory Add Screen - Organizations* + +.. note:: + + As it is with the **Use** role, if you give a user Project Admin and Inventory Admin, it allows them to create Job Templates (not workflows) for your organization. + +**Credential Admin** + +- Parent: Org admin +- Allow: Create, read, update, delete shared credentials +- Scope: Organization +- User Interface: *Credential Add Screen - Organizations* + +**Notification Admin** + +- Parent: Org admin +- Allow: Assignment of notifications +- Scope: Organization + +**Workflow Admin** + +- Parent: Org admin +- Allow: Create a workflow +- Scope: Organization + +**Org Execute** + +- Parent: Org admin +- Allow: Executing JTs and WFJTs +- Scope: Organization + + +The following is a sample scenario showing an organization with its roles and which resource(s) each have access to: + +.. image:: ../common/images/rbac-multiple-resources-scenario.png \ No newline at end of file diff --git a/docs/docsite/rst/userguide/security.rst b/docs/docsite/rst/userguide/security.rst index 00420a5326c0..6834e12096a9 100644 --- a/docs/docsite/rst/userguide/security.rst +++ b/docs/docsite/rst/userguide/security.rst @@ -39,320 +39,4 @@ Isolation functionality and variables pair: isolation; functionality pair: isolation; variables -.. include:: ../common/isolation_variables.rst - -.. _rbac-ug: - -Role-Based Access Controls ------------------------------ - -.. index:: - single: role-based access controls - pair: security; RBAC - -Role-Based Access Controls (RBAC) are built into AWX and allow administrators to delegate access to server inventories, organizations, and more. Administrators can also centralize the management of various credentials, allowing end users to leverage a needed secret without ever exposing that secret to the end user. RBAC controls allow AWX to help you increase security and streamline management. - -RBACs are easiest to think of in terms of Roles which define precisely who or what can see, change, or delete an "object" for which a specific capability is being set. RBAC is the practice of granting roles to users or teams. - -There are a few main concepts that you should become familiar with regarding AWX's RBAC design--roles, resources, and users. Users can be members of a role, which gives them certain access to any resources associated with that role, or any resources associated with "descendant" roles. - -A role is essentially a collection of capabilities. Users are granted access to these capabilities and AWX's resources through the roles to which they are assigned or through roles inherited through the role hierarchy. - -Roles associate a group of capabilities with a group of users. All capabilities are derived from membership within a role. Users receive capabilities only through the roles to which they are assigned or through roles they inherit through the role hierarchy. All members of a role have all capabilities granted to that role. Within an organization, roles are relatively stable, while users and capabilities are both numerous and may change rapidly. Users can have many roles. - - -Role Hierarchy and Access Inheritance -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Imagine that you have an organization named "SomeCompany" and want to allow two people, "Josie" and "Carter", access to manage all the settings associated with that organization. You should make both people members of the organization's ``admin_role``. - -|user-role-relationship| - -.. |user-role-relationship| image:: ../common/images/user-role-relationship.png - -Often, you will have many Roles in a system and you will want some roles to include all of the capabilities of other roles. For example, you may want a System Administrator to have access to everything that an Organization Administrator has access to, who has everything that a Project Administrator has access to, and so on. - -This concept is referred to as the 'Role Hierarchy': - -- Parent roles get all capabilities bestowed on any child roles -- Members of roles automatically get all capabilities for the role they are a member of, as well as any child roles. - -The Role Hierarchy is represented by allowing Roles to have "Parent Roles". Any capability that a Role has is implicitly granted to any parent roles (or parents of those parents, and so on). - -|rbac-role-hierarchy| - -.. |rbac-role-hierarchy| image:: ../common/images/rbac-role-hierarchy.png - -Often, you will have many Roles in a system and you will want some roles to include all of the capabilities of other roles. For example, you may want a System Administrator to have access to everything that an Organization Administrator has access to, who has everything that a Project Administrator has access to, and so on. We refer to this concept as the 'Role Hierarchy' and it is represented by allowing Roles to have "Parent Roles". Any capability that a Role has is implicitly granted to any parent roles (or parents of those parents, and so on). Of course Roles can have more than one parent, and capabilities are implicitly granted to all parents. - -|rbac-heirarchy-morecomplex| - -.. |rbac-heirarchy-morecomplex| image:: ../common/images/rbac-heirarchy-morecomplex.png - -RBAC controls also give you the capability to explicitly permit User and Teams of Users to run playbooks against certain sets of hosts. Users and teams are restricted to just the sets of playbooks and hosts to which they are granted capabilities. And, with AWX, you can create or import as many Users and Teams as you require--create users and teams manually or import them from LDAP or Active Directory. - -RBACs are easiest to think of in terms of who or what can see, change, or delete an "object" for which a specific capability is being determined. - -Applying RBAC -~~~~~~~~~~~~~~~~~ - -The following sections cover how to apply AWX's RBAC system in your environment. - - -Editing Users -^^^^^^^^^^^^^^^ - -When editing a user, a AWX system administrator may specify the user as being either a *System Administrator* (also referred to as the Superuser) or a *System Auditor*. - -- System administrators implicitly inherit all capabilities for all objects (read/write/execute) within the AWX environment. -- System Auditors implicitly inherit the read-only capability for all objects within the AWX environment. - -Editing Organizations -^^^^^^^^^^^^^^^^^^^^^^^^ - -When editing an organization, system administrators may specify the following roles: - -- One or more users as organization administrators -- One or more users as organization auditors -- And one or more users (or teams) as organization members - - -Users/teams that are members of an organization can view their organization administrator. - -Users who are organization administrators implicitly inherit all capabilities for all objects within that AWX organization. - -Users who are organization auditors implicitly inherit the read-only capability for all objects within that AWX organization. - - -Editing Projects in an Organization -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -When editing a project in an organization for which they are the administrator, system administrators and organization administrators may specify: - -- One or more users/teams that are project administrators -- One or more users/teams that are project members -- And one or more users/teams that may update the project from SCM, from among the users/teams that are members of that organization. - -Users who are members of a project can view their project administrators. - -Project administrators implicitly inherit the capability to update the project from SCM. - -Administrators can also specify one or more users/teams (from those that are members of that project) that can use that project in a job template. - - -Creating Inventories and Credentials within an Organization -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -All access that is granted to use, read, or write credentials is handled through roles, which use AWX's RBAC system to grant ownership, auditor, or usage roles. - -System administrators and organization administrators may create inventories and credentials within organizations under their administrative capabilities. - -Whether editing an inventory or a credential, System administrators and organization administrators may specify one or more users/teams (from those that are members of that organization) to be granted the usage capability for that inventory or credential. - -System administrators and organization administrators may specify one or more users/teams (from those that are members of that organization) that have the capabilities to update (dynamic or manually) an inventory. Administrators can also execute ad hoc commands for an inventory. - - -Editing Job Templates -^^^^^^^^^^^^^^^^^^^^^^ - -System administrators, organization administrators, and project administrators, within a project under their administrative capabilities, may create and modify new job templates for that project. - -When editing a job template, administrators (AWX, organization, and project) can select among the inventory and credentials in the organization for which they have usage capabilities or they may leave those fields blank so that they will be selected at runtime. - -Additionally, they may specify one or more users/teams (from those that are members of that project) that have execution capabilities for that job template. The execution capability is valid regardless of any explicit capabilities the user/team may have been granted against the inventory or credential specified in the job template. - -User View -^^^^^^^^^^^^^ - -A user can: - -- See any organization or project for which they are a member -- Create their own credential objects which only belong to them -- See and execute any job template for which they have been granted execution capabilities - -If a job template that a user has been granted execution capabilities on does not specify an inventory or credential, the user will be prompted at run-time to select among the inventory and credentials in the organization they own or have been granted usage capabilities. - -Users that are job template administrators can make changes to job templates; however, to change to the inventory, project, playbook, credentials, or instance groups used in the job template, the user must also have the "Use" role for the project and inventory currently being used or being set. - -.. _rbac-ug-roles: - -Roles -~~~~~~~~~~~~~ - -All access that is granted to use, read, or write credentials is handled through roles, and roles are defined for a resource. - - -Built-in roles -^^^^^^^^^^^^^^ - -The following table lists the RBAC system roles and a brief description of the how that role is defined with regard to privileges in AWX. - -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| System Role | What it can do | -+=======================================================================+==========================================================================================+ -| System Administrator - System wide singleton | Manages all aspects of the system | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| System Auditor - System wide singleton | Views all aspects of the system | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Ad Hoc Role - Inventory | Runs ad hoc commands on an Inventory | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Admin Role - Organizations, Teams, Inventory, Projects, Job Templates | Manages all aspects of a defined Organization, Team, Inventory, Project, or Job Template | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Auditor Role - All | Views all aspects of a defined Organization, Team, Inventory, Project, or Job Template | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Execute Role - Job Templates | Runs assigned Job Template | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Member Role - Organization, Team | User is a member of a defined Organization or Team | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Read Role - Organizations, Teams, Inventory, Projects, Job Templates | Views all aspects of a defined Organization, Team, Inventory, Project, or Job Template | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Update Role - Project | Updates the Project from the configured source control management system | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Update Role - Inventory | Updates the Inventory using the cloud source update system | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Owner Role - Credential | Owns and manages all aspects of this Credential | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ -| Use Role - Credential, Inventory, Project, IGs, CGs | Uses the Credential, Inventory, Project, IGs, or CGs in a Job Template | -+-----------------------------------------------------------------------+------------------------------------------------------------------------------------------+ - - -A Singleton Role is a special role that grants system-wide permissions. AWX currently provides two built-in Singleton Roles but the ability to create or customize a Singleton Role is not supported at this time. - -Common Team Roles - "Personas" -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Support personnel typically works on ensuring that AWX is available and manages it a way to balance supportability and ease-of-use for users. Often, support will assign “Organization Owner/Admin” to users in order to allow them to create a new Organization and add members from their team the respective access needed. This minimizes supporting individuals and focuses more on maintaining uptime of the service and assisting users who are using AWX. - -Below are some common roles managed by the AWX Organization: - -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ -| | System Role | | Common User | | Description | -| | (for Organizations) | | Roles | | -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ -| | Owner | | Team Lead - | | This user has the ability to control access for other users in their organization. | -| | | Technical Lead | | They can add/remove and grant users specific access to projects, inventories, and job templates. | -| | | | This user also has the ability to create/remove/modify any aspect of an organization’s projects, | -| | | | templates, inventories, teams, and credentials. | -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ -| | Auditor | | Security Engineer - | | This account can view all aspects of the organization in read-only mode. | -| | | Project Manager | | This may be good for a user who checks in and maintains compliance. | -| | | | This might also be a good role for a service account who manages or | -| | | | ships job data from AWX to some other data collector. | -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ -| | Member - | | All other users | | These users by default as an organization member do not receive any access to any aspect | -| | Team | | | of the organization. In order to grant them access the respective organization owner needs | -| | | | to add them to their respective team and grant them Admin, Execute, Use, Update, Ad-hoc | -| | | | permissions to each component of the organization’s projects, inventories, and job templates. | -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ -| | Member - | | Power users - | | Organization Owners can provide “admin” through the team interface, over any component | -| | Team “Owner” | | Lead Developer | | of their organization including projects, inventories, and job templates. These users are able | -| | | | to modify and utilize the respective component given access. | -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ -| | Member - | | Developers - | | This will be the most common and allows the organization member the ability to execute | -| | Team “Execute” | | Engineers | | job templates and read permission to the specific components. This is permission applies to templates. | -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ -| | Member - | | Developers - | | This permission applies to an organization’s credentials, inventories, and projects. | -| | Team “Use” | | Engineers | | This permission allows the ability for a user to use the respective component within their job template.| -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ -| | Member - | | Developers - | | This permission applies to projects. Allows the user to be able to run an SCM update on a project. | -| | Team “Update” | | Engineers | | -+-----------------------+------------------------+-----------------------------------------------------------------------------------------------------------+ - - -Function of roles: editing and creating ------------------------------------------- - -Organization “resource roles” functionality are specific to a certain resource type - such as workflows. Being a member of such a role usually provides two types of permissions, in the case of workflows, where a user is given a "workflow admin role" for the organization "Default": - -- this user can create new workflows in the organization "Default" -- user can edit all workflows in the "Default" organization - -One exception is job templates, where having the role is irrelevant of creation permission (more details on its own section). - -Independence of resource roles and organization membership roles -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Resource-specific organization roles are independent of the organization roles of admin and member. Having the "workflow admin role" for the "Default" organization will not allow a user to view all users in the organization, but having a "member" role in the "Default" organization will. The two types of roles are delegated independently of each other. - - -Necessary permissions to edit job templates -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Users can edit fields not impacting job runs (non-sensitive fields) with a Job Template admin role alone. However, to edit fields that impact job runs in a job template, a user needs the following: - -- **admin** role to the job template and container groups -- **use** role to related project -- **use** role to related inventory -- **use** role to related instance groups - -An "organization job template admin" role was introduced, but having this role isn't sufficient by itself to edit a job template within the organization if the user does not have use role to the project / inventory / instance group or an admin role to the container group that a job template uses. - -In order to delegate *full* job template control (within an organization) to a user or team, you will need grant the team or user all 3 organization-level roles: - -- job template admin -- project admin -- inventory admin - -This will ensure that the user (or all users who are members of the team with these roles) have full access to modify job templates in the organization. If a job template uses an inventory or project from another organization, the user with these organization roles may still not have permission to modify that job template. For clarity of managing permissions, it is best-practice to not mix projects / inventories from different organizations. - -RBAC permissions -^^^^^^^^^^^^^^^^^^^ - -Each role should have a content object, for instance, the org admin role has a content object of the org. To delegate a role, you need admin permission to the content object, with some exceptions that would result in you being able to reset a user's password. - -**Parent** is the organization. - -**Allow** is what this new permission will explicitly allow. - -**Scope** is the parent resource that this new role will be created on. Example: ``Organization.project_create_role``. - -An assumption is being made that the creator of the resource should be given the admin role for that resource. If there are any instances where resource creation does not also imply resource administration, they will be explicitly called out. - -Here are the rules associated with each admin type: - -**Project Admin** - -- Allow: Create, read, update, delete any project -- Scope: Organization -- User Interface: *Project Add Screen - Organizations* - -**Inventory Admin** - -- Parent: Org admin -- Allow: Create, read, update, delete any inventory -- Scope: Organization -- User Interface: *Inventory Add Screen - Organizations* - -.. note:: - - As it is with the **Use** role, if you give a user Project Admin and Inventory Admin, it allows them to create Job Templates (not workflows) for your organization. - -**Credential Admin** - -- Parent: Org admin -- Allow: Create, read, update, delete shared credentials -- Scope: Organization -- User Interface: *Credential Add Screen - Organizations* - -**Notification Admin** - -- Parent: Org admin -- Allow: Assignment of notifications -- Scope: Organization - -**Workflow Admin** - -- Parent: Org admin -- Allow: Create a workflow -- Scope: Organization - -**Org Execute** - -- Parent: Org admin -- Allow: Executing JTs and WFJTs -- Scope: Organization - - -The following is a sample scenario showing an organization with its roles and which resource(s) each have access to: - -.. image:: ../common/images/rbac-multiple-resources-scenario.png +.. include:: ../common/isolation_variables.rst \ No newline at end of file diff --git a/docs/notification_system.md b/docs/notification_system.md index edd64275fe67..96502edfa9a9 100644 --- a/docs/notification_system.md +++ b/docs/notification_system.md @@ -70,6 +70,7 @@ Once a Notification Template has been created, its configuration can be tested b The currently-defined Notification Types are: +* AWS SNS * Email * Slack * Mattermost @@ -82,6 +83,10 @@ The currently-defined Notification Types are: Each of these have their own configuration and behavioral semantics and testing them may need to be approached in different ways. The following sections will give as much detail as possible. +## AWS SNS + +The AWS SNS notification type supports sending messages into an SNS topic. + ## Email The email notification type supports a wide variety of SMTP servers and has support for SSL/TLS connections and timeouts. diff --git a/licenses/deprecated.txt b/licenses/deprecated.txt new file mode 100644 index 000000000000..7898d9f648fc --- /dev/null +++ b/licenses/deprecated.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Laurent LAPORTE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/licenses/asyncpg.txt b/licenses/googleapis-common-protos.txt similarity index 98% rename from licenses/asyncpg.txt rename to licenses/googleapis-common-protos.txt index d931386122bb..d64569567334 100644 --- a/licenses/asyncpg.txt +++ b/licenses/googleapis-common-protos.txt @@ -1,4 +1,3 @@ -Copyright (C) 2016-present the asyncpg authors and contributors. Apache License Version 2.0, January 2004 @@ -188,8 +187,7 @@ Copyright (C) 2016-present the asyncpg authors and contributors. same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright (C) 2016-present the asyncpg authors and contributors - + Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/licenses/grpcio.txt b/licenses/grpcio.txt new file mode 100644 index 000000000000..0e09a3e90900 --- /dev/null +++ b/licenses/grpcio.txt @@ -0,0 +1,610 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +----------------------------------------------------------- + +BSD 3-Clause License + +Copyright 2016, Google Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from this +software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +----------------------------------------------------------- + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/licenses/opentelemetry-api.txt b/licenses/opentelemetry-api.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-api.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-exporter-otlp-proto-common.txt b/licenses/opentelemetry-exporter-otlp-proto-common.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-exporter-otlp-proto-common.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-exporter-otlp-proto-grpc.txt b/licenses/opentelemetry-exporter-otlp-proto-grpc.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-exporter-otlp-proto-grpc.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-exporter-otlp-proto-http.txt b/licenses/opentelemetry-exporter-otlp-proto-http.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-exporter-otlp-proto-http.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-exporter-otlp.txt b/licenses/opentelemetry-exporter-otlp.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-exporter-otlp.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-instrumentation-logging.txt b/licenses/opentelemetry-instrumentation-logging.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-instrumentation-logging.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-instrumentation.txt b/licenses/opentelemetry-instrumentation.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-instrumentation.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-proto.txt b/licenses/opentelemetry-proto.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-proto.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-sdk.txt b/licenses/opentelemetry-sdk.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-sdk.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/opentelemetry-semantic-conventions.txt b/licenses/opentelemetry-semantic-conventions.txt new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/licenses/opentelemetry-semantic-conventions.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/protobuf.txt b/licenses/protobuf.txt new file mode 100644 index 000000000000..19b305b00060 --- /dev/null +++ b/licenses/protobuf.txt @@ -0,0 +1,32 @@ +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. diff --git a/licenses/pyzstd.txt b/licenses/pyzstd.txt new file mode 100644 index 000000000000..e69dae4dd49f --- /dev/null +++ b/licenses/pyzstd.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2020-present, Ma Lin +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/wrapt.txt b/licenses/wrapt.txt new file mode 100644 index 000000000000..bd8c7124a7ca --- /dev/null +++ b/licenses/wrapt.txt @@ -0,0 +1,24 @@ +Copyright (c) 2013-2023, Graham Dumpleton +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/requirements/requirements.in b/requirements/requirements.in index 87cdd3367a7b..3dc2bb6a46a4 100644 --- a/requirements/requirements.in +++ b/requirements/requirements.in @@ -1,8 +1,7 @@ -aiohttp>=3.8.6 # CVE-2023-47627 +aiohttp>=3.9.4 # CVE-2024-30251 ansiconv==1.0.0 # UPGRADE BLOCKER: from 2013, consider replacing instead of upgrading asciichartpy asn1 -asyncpg azure-identity azure-keyvault boto3 @@ -10,10 +9,10 @@ botocore channels channels-redis==3.4.1 # see UPGRADE BLOCKERs cryptography>=41.0.7 # CVE-2023-49083 -Cython<3 # this is needed as a build dependency, one day we may have separated build deps +Cython<3 # due to https://github.com/yaml/pyyaml/pull/702 daphne distro -django==4.2.6 # CVE-2023-43665 +django==4.2.10 # CVE-2024-24680 django-auth-ldap django-cors-headers django-crum @@ -29,6 +28,7 @@ djangorestframework>=3.15.0 djangorestframework-yaml filelock GitPython>=3.1.37 # CVE-2023-41040 +grpcio<1.63.0 # 1.63.0+ requires cython>=3 hiredis==2.0.0 # see UPGRADE BLOCKERs irc jinja2>=3.1.3 # CVE-2024-22195 @@ -39,6 +39,10 @@ maturin # pydantic-core build dep msgpack<1.0.6 # 1.0.6+ requires cython>=3 msrestazure openshift +opentelemetry-api~=1.24 # new y streams can be drastically different, in a good way +opentelemetry-sdk~=1.24 +opentelemetry-instrumentation-logging +opentelemetry-exporter-otlp pexpect==4.7.0 # see library notes prometheus_client psycopg @@ -51,6 +55,7 @@ python-dsv-sdk>=1.0.4 python-tss-sdk>=1.2.1 python-ldap pyyaml>=6.0.1 +pyzstd # otel collector log file compression library receptorctl social-auth-core[openidconnect]==4.4.2 # see UPGRADE BLOCKERs social-auth-app-django==5.4.0 # see UPGRADE BLOCKERs diff --git a/requirements/requirements.txt b/requirements/requirements.txt index 205a2899fcae..59241c34fd36 100644 --- a/requirements/requirements.txt +++ b/requirements/requirements.txt @@ -1,6 +1,6 @@ adal==1.2.7 # via msrestazure -aiohttp==3.9.3 +aiohttp==3.9.5 # via # -r /awx_devel/requirements/requirements.in # aiohttp-retry @@ -31,10 +31,7 @@ async-timeout==4.0.3 # via # aiohttp # aioredis - # asyncpg # redis -asyncpg==0.29.0 - # via -r /awx_devel/requirements/requirements.in attrs==23.2.0 # via # aiohttp @@ -123,9 +120,14 @@ defusedxml==0.7.1 # via # python3-openid # social-auth-core +deprecated==1.2.14 + # via + # opentelemetry-api + # opentelemetry-exporter-otlp-proto-grpc + # opentelemetry-exporter-otlp-proto-http distro==1.9.0 # via -r /awx_devel/requirements/requirements.in -django==4.2.6 +django==4.2.10 # via # -r /awx_devel/requirements/requirements.in # channels @@ -191,6 +193,14 @@ gitpython==3.1.42 # via -r /awx_devel/requirements/requirements.in google-auth==2.28.1 # via kubernetes +googleapis-common-protos==1.63.0 + # via + # opentelemetry-exporter-otlp-proto-grpc + # opentelemetry-exporter-otlp-proto-http +grpcio==1.62.2 + # via + # -r /awx_devel/requirements/requirements.in + # opentelemetry-exporter-otlp-proto-grpc hiredis==2.0.0 # via # -r /awx_devel/requirements/requirements.in @@ -209,6 +219,7 @@ importlib-metadata==6.2.1 # via # ansible-runner # markdown + # opentelemetry-api incremental==22.10.0 # via twisted inflect==7.0.0 @@ -302,6 +313,40 @@ oauthlib==3.2.2 # social-auth-core openshift==0.13.2 # via -r /awx_devel/requirements/requirements.in +opentelemetry-api==1.24.0 + # via + # -r /awx_devel/requirements/requirements.in + # opentelemetry-exporter-otlp-proto-grpc + # opentelemetry-exporter-otlp-proto-http + # opentelemetry-instrumentation + # opentelemetry-instrumentation-logging + # opentelemetry-sdk +opentelemetry-exporter-otlp==1.24.0 + # via -r /awx_devel/requirements/requirements.in +opentelemetry-exporter-otlp-proto-common==1.24.0 + # via + # opentelemetry-exporter-otlp-proto-grpc + # opentelemetry-exporter-otlp-proto-http +opentelemetry-exporter-otlp-proto-grpc==1.24.0 + # via opentelemetry-exporter-otlp +opentelemetry-exporter-otlp-proto-http==1.24.0 + # via opentelemetry-exporter-otlp +opentelemetry-instrumentation==0.45b0 + # via opentelemetry-instrumentation-logging +opentelemetry-instrumentation-logging==0.45b0 + # via -r /awx_devel/requirements/requirements.in +opentelemetry-proto==1.24.0 + # via + # opentelemetry-exporter-otlp-proto-common + # opentelemetry-exporter-otlp-proto-grpc + # opentelemetry-exporter-otlp-proto-http +opentelemetry-sdk==1.24.0 + # via + # -r /awx_devel/requirements/requirements.in + # opentelemetry-exporter-otlp-proto-grpc + # opentelemetry-exporter-otlp-proto-http +opentelemetry-semantic-conventions==0.45b0 + # via opentelemetry-sdk packaging==23.2 # via # ansible-runner @@ -319,6 +364,10 @@ portalocker==2.8.2 # via msal-extensions prometheus-client==0.20.0 # via -r /awx_devel/requirements/requirements.in +protobuf==4.25.3 + # via + # googleapis-common-protos + # opentelemetry-proto psutil==5.9.8 # via -r /awx_devel/requirements/requirements.in psycopg==3.1.18 @@ -396,6 +445,8 @@ pyyaml==6.0.1 # djangorestframework-yaml # kubernetes # receptorctl +pyzstd==0.15.10 + # via -r /awx_devel/requirements/requirements.in receptorctl==1.4.4 # via -r /awx_devel/requirements/requirements.in redis==5.0.1 @@ -414,6 +465,7 @@ requests==2.31.0 # kubernetes # msal # msrest + # opentelemetry-exporter-otlp-proto-http # python-dsv-sdk # python-tss-sdk # requests-oauthlib @@ -498,6 +550,7 @@ typing-extensions==4.9.0 # azure-keyvault-secrets # inflect # jwcrypto + # opentelemetry-sdk # psycopg # pydantic # pydantic-core @@ -516,6 +569,10 @@ websocket-client==1.7.0 # via kubernetes wheel==0.42.0 # via -r /awx_devel/requirements/requirements.in +wrapt==1.16.0 + # via + # deprecated + # opentelemetry-instrumentation xmlsec==1.3.13 # via python3-saml yarl==1.9.4 @@ -533,6 +590,7 @@ setuptools==69.0.2 # -r /awx_devel/requirements/requirements.in # asciichartpy # autobahn + # opentelemetry-instrumentation # python-daemon # setuptools-rust # setuptools-scm diff --git a/requirements/requirements_dev.txt b/requirements/requirements_dev.txt index 4d087803fda0..059ada9be3f5 100644 --- a/requirements/requirements_dev.txt +++ b/requirements/requirements_dev.txt @@ -11,9 +11,9 @@ pytest!=7.0.0 pytest-asyncio pytest-cov pytest-django -pytest-mock==1.11.1 +pytest-mock pytest-timeout -pytest-xdist==1.34.0 # 2.0.0 broke zuul for some reason +pytest-xdist tox # for awxkit logutils jupyter @@ -21,7 +21,7 @@ jupyter backports.tempfile # support in unit tests for py32+ tempfile.TemporaryDirectory git+https://github.com/artefactual-labs/mockldap.git@master#egg=mockldap gprof2dot -atomicwrites==1.4.0 +atomicwrites flake8 yamllint pip>=21.3 # PEP 660 – Editable installs for pyproject.toml based builds (wheel based) @@ -30,3 +30,4 @@ pip>=21.3 # PEP 660 – Editable installs for pyproject.toml based builds (wheel debugpy remote-pdb sdb + diff --git a/tools/ansible/roles/dockerfile/templates/supervisor_task.conf.j2 b/tools/ansible/roles/dockerfile/templates/supervisor_task.conf.j2 index 90b6313635b2..b102a50977b1 100644 --- a/tools/ansible/roles/dockerfile/templates/supervisor_task.conf.j2 +++ b/tools/ansible/roles/dockerfile/templates/supervisor_task.conf.j2 @@ -31,7 +31,6 @@ command = awx-manage run_wsrelay directory = /var/lib/awx {% endif %} autorestart = true -startsecs = 30 stopasgroup=true killasgroup=true stdout_logfile=/dev/stdout diff --git a/tools/docker-compose/README.md b/tools/docker-compose/README.md index 8ac287945ce9..22a3c7b390e0 100644 --- a/tools/docker-compose/README.md +++ b/tools/docker-compose/README.md @@ -22,7 +22,7 @@ Once you have a local copy, run the commands in the following sections from the Here are the main `make` targets: -- `docker-compose-build` - used for building the development image, which is used by the `docker-compose` target +- `docker-compose-build` - used for building the development image, which is used by the `docker-compose` target. You can skip this target if you want to use the latest [ghcr.io/ansible/awx_devel:devel](https://github.com/ansible/awx/pkgs/container/awx_devel) image rather than build a new one. - `docker-compose` - make target for development, passes awx_devel image and tag Notable files: @@ -613,3 +613,13 @@ docker exec -it -e VAULT_TOKEN= tools_vault_1 vault kv get --address=http ### Prometheus and Grafana integration See docs at https://github.com/ansible/awx/blob/devel/tools/grafana/README.md + +### OpenTelemetry Integration + +```bash +OTEL=true GRAFANA=true LOKI=true PROMETHEUS=true make docker-compose +``` + +This will start the sidecar container `tools_otel_1` and configure AWX logging to send to it. The OpenTelemetry Collector is configured to export logs to Loki. Grafana is configured with Loki as a datasource. AWX logs can be viewed in Grafana. + +`http://localhost:3001` grafana diff --git a/tools/docker-compose/ansible/roles/sources/defaults/main.yml b/tools/docker-compose/ansible/roles/sources/defaults/main.yml index d336f29fc427..669f2cfe2002 100644 --- a/tools/docker-compose/ansible/roles/sources/defaults/main.yml +++ b/tools/docker-compose/ansible/roles/sources/defaults/main.yml @@ -4,6 +4,7 @@ awx_image: 'ghcr.io/ansible/awx_devel' pg_port: 5432 pg_username: 'awx' pg_database: 'awx' +pg_tls: false control_plane_node_count: 1 minikube_container_group: false receptor_socket_file: /var/run/awx-receptor/receptor.sock diff --git a/tools/docker-compose/ansible/roles/sources/templates/database.py.j2 b/tools/docker-compose/ansible/roles/sources/templates/database.py.j2 index 76bebff1591e..120a5c0d0a49 100644 --- a/tools/docker-compose/ansible/roles/sources/templates/database.py.j2 +++ b/tools/docker-compose/ansible/roles/sources/templates/database.py.j2 @@ -5,6 +5,9 @@ DATABASES = { 'NAME': "{{ pg_database }}", 'USER': "{{ pg_username }}", 'PASSWORD': "{{ pg_password }}", +{% if pg_tls|bool %} + 'OPTIONS': {'sslmode': 'require'}, +{% endif %} {% if enable_pgbouncer|bool %} 'HOST': "pgbouncer", 'PORT': "{{ pgbouncer_port }}", diff --git a/tools/docker-compose/ansible/roles/sources/templates/docker-compose.yml.j2 b/tools/docker-compose/ansible/roles/sources/templates/docker-compose.yml.j2 index e6cb929482e4..734b3ba47e32 100644 --- a/tools/docker-compose/ansible/roles/sources/templates/docker-compose.yml.j2 +++ b/tools/docker-compose/ansible/roles/sources/templates/docker-compose.yml.j2 @@ -237,13 +237,24 @@ services: image: quay.io/sclorg/postgresql-15-c9s container_name: tools_postgres_1 # additional logging settings for postgres can be found https://www.postgresql.org/docs/current/runtime-config-logging.html - command: run-postgresql -c log_destination=stderr -c log_min_messages=info -c log_min_duration_statement={{ pg_log_min_duration_statement|default(1000) }} -c max_connections={{ pg_max_connections|default(1024) }} + command: > + bash -c " +{% if pg_tls|bool %} + mkdir -p /opt/app-root/src/certs + && openssl genrsa -out /opt/app-root/src/certs/tls.key 2048 + && openssl req -new -x509 -key /opt/app-root/src/certs/tls.key -out /opt/app-root/src/certs/tls.crt -subj '/CN=postgres' + && chmod 600 /opt/app-root/src/certs/tls.crt /opt/app-root/src/certs/tls.key && +{% endif %} + run-postgresql -c log_destination=stderr -c log_min_messages=info -c log_min_duration_statement={{ pg_log_min_duration_statement|default(1000) }} -c max_connections={{ pg_max_connections|default(1024) }}" environment: POSTGRESQL_USER: {{ pg_username }} POSTGRESQL_DATABASE: {{ pg_database }} POSTGRESQL_PASSWORD: {{ pg_password }} volumes: - "awx_db_15:/var/lib/pgsql/data" +{% if pg_tls|bool %} + - "../../docker-compose/pgssl.conf:/opt/app-root/src/postgresql-cfg/pgssl.conf" +{% endif %} networks: - awx ports: @@ -269,6 +280,37 @@ services: # pg_notify will NOT work in transaction mode. PGBOUNCER_POOL_MODE: session {% endif %} +{% if enable_otel|bool %} + otel: + image: otel/opentelemetry-collector-contrib:0.88.0 + container_name: tools_otel_1 + hostname: otel + command: ["--config=/etc/otel-collector-config.yaml", ""] + networks: + - awx + ports: + - "4317:4317" # OTLP gRPC receiver + - "4318:4318" # OTLP http receiver + - "55679:55679" # zpages http://localhost:55679/debug/servicez /tracez + volumes: + - "../../otel/otel-collector-config.yaml:/etc/otel-collector-config.yaml" + - "../../otel/awx-logs:/awx-logs/" +{% endif %} +{% if enable_loki|bool %} + loki: + image: grafana/loki:2.9.5 + container_name: tools_loki_1 + hostname: loki + ports: + - "3100:3100" + command: -config.file=/etc/loki/local-config.yaml + networks: + - awx + volumes: + - "loki_storage:/loki:rw" + - "../../loki/local-config.yaml:/etc/loki/local-config.yaml" +{% endif %} + {% if execution_node_count|int > 0 %} receptor-hop: image: {{ receptor_image }} @@ -360,6 +402,10 @@ volumes: grafana_storage: name: tools_grafana_storage {% endif %} +{% if enable_loki|bool %} + loki_storage: + name: tools_loki_storage +{% endif %} networks: awx: diff --git a/tools/docker-compose/ansible/roles/sources/templates/local_settings.py.j2 b/tools/docker-compose/ansible/roles/sources/templates/local_settings.py.j2 index fe9596a7b02a..42a5d56366f4 100644 --- a/tools/docker-compose/ansible/roles/sources/templates/local_settings.py.j2 +++ b/tools/docker-compose/ansible/roles/sources/templates/local_settings.py.j2 @@ -46,6 +46,25 @@ OPTIONAL_API_URLPATTERN_PREFIX = '{{ api_urlpattern_prefix }}' # LOGGING['loggers']['django_auth_ldap']['handlers'] = ['console'] # LOGGING['loggers']['django_auth_ldap']['level'] = 'DEBUG' +{% if enable_otel|bool %} +LOGGING['handlers']['otel'] |= { + 'class': 'awx.main.utils.handlers.OTLPHandler', + 'endpoint': 'http://otel:4317', +} +# Add otel log handler to all log handlers where propagate is False +for name in LOGGING['loggers'].keys(): + if not LOGGING['loggers'][name].get('propagate', True): + handler = LOGGING['loggers'][name].get('handlers', []) + if 'otel' not in handler: + LOGGING['loggers'][name].get('handlers', []).append('otel') + +# Everything without explicit propagate=False ends up logging to 'awx' so add it +handler = LOGGING['loggers']['awx'].get('handlers', []) +if 'otel' not in handler: + LOGGING['loggers']['awx'].get('handlers', []).append('otel') + +{% endif %} + BROADCAST_WEBSOCKET_PORT = 8013 BROADCAST_WEBSOCKET_VERIFY_CERT = False BROADCAST_WEBSOCKET_PROTOCOL = 'http' diff --git a/tools/docker-compose/pgssl.conf b/tools/docker-compose/pgssl.conf new file mode 100644 index 000000000000..d34917d1ff75 --- /dev/null +++ b/tools/docker-compose/pgssl.conf @@ -0,0 +1,5 @@ +ssl = on +ssl_cert_file = '/opt/app-root/src/certs/tls.crt' # server certificate +ssl_key_file = '/opt/app-root/src/certs/tls.key' # server private key +#ssl_ca_file # trusted certificate authorities +#ssl_crl_file # certificates revoked by certificate authorities diff --git a/tools/grafana/dashboards/awx_dashboard.yml b/tools/grafana/dashboards/awx_dashboard.yml index 9692ffe1b738..2f25fc523f94 100644 --- a/tools/grafana/dashboards/awx_dashboard.yml +++ b/tools/grafana/dashboards/awx_dashboard.yml @@ -2,7 +2,9 @@ apiVersion: 1 providers: - - name: awx + - name: awx-dashboards + type: file allowUiUpdates: true options: - path: /etc/grafana/provisioning/dashboards/demo_dashboard.json + foldersFromFilesStructure: true + path: /etc/grafana/provisioning/dashboards/ diff --git a/tools/grafana/dashboards/services_dashboard.json b/tools/grafana/dashboards/services_dashboard.json new file mode 100644 index 000000000000..bcf91407244d --- /dev/null +++ b/tools/grafana/dashboards/services_dashboard.json @@ -0,0 +1,156 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "id": 4, + "links": [], + "panels": [ + { + "datasource": { + "type": "loki", + "uid": "P8E80F9AEF21F6940" + }, + "gridPos": { + "h": 22, + "w": 12, + "x": 0, + "y": 0 + }, + "id": 1, + "maxPerRow": 2, + "options": { + "dedupStrategy": "none", + "enableLogDetails": true, + "prettifyLogMessage": false, + "showCommonLabels": false, + "showLabels": false, + "showTime": true, + "sortOrder": "Descending", + "wrapLogMessage": false + }, + "repeat": "service", + "repeatDirection": "h", + "targets": [ + { + "datasource": { + "type": "loki", + "uid": "P8E80F9AEF21F6940" + }, + "editorMode": "code", + "expr": "{instance=~\"${instances:pipe}\", job=~\"${service}\"} | json | line_format \"{{.instance}} {{.body}}\"", + "maxLines": 100, + "queryType": "range", + "refId": "A" + } + ], + "title": "Service ${service}", + "type": "logs" + } + ], + "schemaVersion": 39, + "tags": [], + "templating": { + "list": [ + { + "current": { + "selected": false, + "text": "awx-1", + "value": "awx-1" + }, + "datasource": { + "type": "loki", + "uid": "P8E80F9AEF21F6940" + }, + "definition": "", + "hide": 0, + "includeAll": false, + "multi": true, + "name": "instances", + "options": [], + "query": { + "label": "instance", + "refId": "LokiVariableQueryEditor-VariableQuery", + "stream": "", + "type": 1 + }, + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + }, + { + "current": { + "selected": true, + "text": [ + "-b", + "provision_instance", + "run_callback_receiver", + "run_dispatcher", + "run_rsyslog_configurer", + "run_ws_heartbeat", + "run_wsrelay", + "uwsgi" + ], + "value": [ + "-b", + "provision_instance", + "run_callback_receiver", + "run_dispatcher", + "run_rsyslog_configurer", + "run_ws_heartbeat", + "run_wsrelay", + "uwsgi" + ] + }, + "datasource": { + "type": "loki", + "uid": "P8E80F9AEF21F6940" + }, + "definition": "", + "hide": 0, + "includeAll": false, + "multi": true, + "name": "service", + "options": [], + "query": { + "label": "job", + "refId": "LokiVariableQueryEditor-VariableQuery", + "stream": "", + "type": 1 + }, + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "type": "query" + } + ] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": {}, + "timezone": "browser", + "title": "AWX Service Logs", + "uid": "bdndgnhicrt34c", + "version": 12, + "weekStart": "" +} diff --git a/tools/grafana/datasources/loki_source.yml b/tools/grafana/datasources/loki_source.yml new file mode 100644 index 000000000000..4a6c740f3410 --- /dev/null +++ b/tools/grafana/datasources/loki_source.yml @@ -0,0 +1,11 @@ +--- +apiVersion: 1 + +datasources: + - name: Loki + type: loki + access: proxy + url: http://loki:3100 + jsonData: + timeout: 60 + maxLines: 100000 diff --git a/tools/loki/local-config.yaml b/tools/loki/local-config.yaml new file mode 100644 index 000000000000..dde03673aa70 --- /dev/null +++ b/tools/loki/local-config.yaml @@ -0,0 +1,96 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + grpc_server_max_recv_msg_size: 524288000 # 500 MB + grpc_server_max_send_msg_size: 524288000 # 500 MB, might be too much, be careful + +frontend_worker: + match_max_concurrent: true + grpc_client_config: + max_send_msg_size: 524288000 # 500 MB + + +ingester: + max_chunk_age: 8766h + +common: + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +# compactor: +# retention_enabled: true +# # cmeyers: YOLO. 1s seems wrong but it works so right +# compaction_interval: 1s # default 10m + +schema_config: + configs: + - from: 2020-10-24 + store: boltdb-shipper + object_store: filesystem + schema: v11 + index: + prefix: index_ + period: 24h + +storage_config: + boltdb_shipper: + active_index_directory: /loki/index + cache_location: /loki/boltdb-cache + +ruler: + alertmanager_url: http://localhost:9093 + +limits_config: + retention_period: 3y + # cmeyers: The default of 30m triggers a loop of queries that take a long time + # to complete and the UI times out + split_queries_by_interval: 1d + # cmeyers: Default of 30d1h limits grafana time queries. Can't, for example, + # query last 90 days + max_query_length: 3y + # cmeyers: Made the batch post request succeed. + reject_old_samples: false + reject_old_samples_max_age: 365d + + ingestion_rate_mb: 32 + ingestion_burst_size_mb: 32 + per_stream_rate_limit: 32M + per_stream_rate_limit_burst: 32M + ingestion_rate_strategy: local # Default: global + max_global_streams_per_user: 100000000 + max_entries_limit_per_query: 100000000 + max_query_series: 1000000 + max_query_parallelism: 32 # Old Default: 14 + max_streams_per_user: 100000000 # Old Default: 10000 + +# Taken from aap-log-visualizer +frontend: + max_outstanding_per_tenant: 2048 + +query_scheduler: + max_outstanding_requests_per_tenant: 2048 + +query_range: + parallelise_shardable_queries: false + split_queries_by_interval: 0 + +# By default, Loki will send anonymous, but uniquely-identifiable usage and configuration +# analytics to Grafana Labs. These statistics are sent to https://stats.grafana.org/ +# +# Statistics help us better understand how Loki is used, and they show us performance +# levels for most users. This helps us prioritize features and documentation. +# For more information on what's sent, look at +# https://github.com/grafana/loki/blob/main/pkg/usagestats/stats.go +# Refer to the buildReport method to see what goes into a report. +# +# If you would like to disable reporting, uncomment the following lines: +#analytics: +# reporting_enabled: false diff --git a/tools/otel/otel-collector-config.yaml b/tools/otel/otel-collector-config.yaml new file mode 100644 index 000000000000..26a330cf5dbb --- /dev/null +++ b/tools/otel/otel-collector-config.yaml @@ -0,0 +1,50 @@ +receivers: + otlp: + protocols: + grpc: + http: + +exporters: + debug: + verbosity: detailed + + file: + path: /awx-logs/awx-logs.json.zstd + rotation: + max_days: 14 + localtime: false + max_megabytes: 300 + max_backups: 200 + format: json + compression: zstd + + loki: + endpoint: http://loki:3100/loki/api/v1/push + tls: + insecure: true + headers: + "X-Scope-OrgID": "1" + default_labels_enabled: + exporter: true + job: true + instance: true + level: true + +processors: + batch: + +extensions: + health_check: + zpages: + endpoint: ":55679" + +service: + pipelines: + logs: + receivers: [otlp] + processors: [batch] + exporters: [file, loki] + + extensions: + - health_check + - zpages diff --git a/tools/scripts/ig-hotfix/.gitignore b/tools/scripts/ig-hotfix/.gitignore new file mode 100644 index 000000000000..c75dd77f731a --- /dev/null +++ b/tools/scripts/ig-hotfix/.gitignore @@ -0,0 +1,7 @@ +*~ +customer-backup.tar.* +*.db +*.log +*.dot +*.png +*.tar.* diff --git a/tools/scripts/ig-hotfix/README.md b/tools/scripts/ig-hotfix/README.md new file mode 100644 index 000000000000..614d2b096b85 --- /dev/null +++ b/tools/scripts/ig-hotfix/README.md @@ -0,0 +1,36 @@ +# Hotfix for Instance Groups and Roles after backup/restore corruption # + +## role_check.py ## + +`awx-manage shell < role_check.py 2> role_check.log > fix.py` + +This checks the roles and resources on the system, and constructs a +fix.py file that will change the linkages of the roles that it finds +are incorrect. The command line above also redirects logging output to +a file. The fix.py file (and the log file) can then be examined (and +potentially modified) before performing the actual fix. + +`awx-manage shell < fix.py > fix.log 2>&1` + +This performs the fix, while redirecting all output to another log +file. Ideally, this file should wind up being empty after execution +completes. + +`awx-manage shell < role_check.py 2> role_check2.log > fix2.py` + +Re-run the check script in order to see that there are no remaining +problems. Ideally the log file will only consist of the equal-sign +lines. + + +## foreignkeys.sql ## + +This script uses Postgres internals to determine all of the foreign +keys that cross the boundaries established by our (old) backup/restore +logic. Users have no need to run this. + + +## scenarios/test*.py ## + +These files were used to set up corruption similar to that caused by +faulty backup/restore, for testing purposes. Do not use. diff --git a/tools/scripts/ig-hotfix/foreignkeys.sql b/tools/scripts/ig-hotfix/foreignkeys.sql new file mode 100644 index 000000000000..ac9ba2a5de17 --- /dev/null +++ b/tools/scripts/ig-hotfix/foreignkeys.sql @@ -0,0 +1,38 @@ +DO $$ +DECLARE + -- add table names here when they get excluded from main / included in topology dump + topology text[] := ARRAY['main_instance', 'main_instancegroup', 'main_instancegroup_instances']; + + -- add table names here when they are handled by the special-case mapping + mapping text[] := ARRAY['main_organizationinstancegroupmembership', 'main_unifiedjobtemplateinstancegroupmembership', 'main_inventoryinstancegroupmembership']; +BEGIN + CREATE TABLE tmp_fk_from AS ( + SELECT DISTINCT + tc.table_name, + ccu.table_name AS foreign_table_name + FROM information_schema.table_constraints AS tc + JOIN information_schema.constraint_column_usage AS ccu + ON ccu.constraint_name = tc.constraint_name + WHERE tc.constraint_type = 'FOREIGN KEY' + AND tc.table_name = ANY (topology) + AND NOT ccu.table_name = ANY (topology || mapping) + ); + + CREATE TABLE tmp_fk_into AS ( + SELECT DISTINCT + tc.table_name, + ccu.table_name AS foreign_table_name + FROM information_schema.table_constraints AS tc + JOIN information_schema.constraint_column_usage AS ccu + ON ccu.constraint_name = tc.constraint_name + WHERE tc.constraint_type = 'FOREIGN KEY' + AND ccu.table_name = ANY (topology) + AND NOT tc.table_name = ANY (topology || mapping) + ); +END $$; + +SELECT * FROM tmp_fk_from; +SELECT * FROM tmp_fk_into; + +DROP TABLE tmp_fk_from; +DROP TABLE tmp_fk_into; diff --git a/tools/scripts/ig-hotfix/role_check.py b/tools/scripts/ig-hotfix/role_check.py new file mode 100644 index 000000000000..7da16b1e1cc3 --- /dev/null +++ b/tools/scripts/ig-hotfix/role_check.py @@ -0,0 +1,187 @@ +from collections import defaultdict +import json +import sys + +from django.contrib.contenttypes.models import ContentType +from django.db.models.fields.related_descriptors import ManyToManyDescriptor + +from awx.main.fields import ImplicitRoleField +from awx.main.models.rbac import Role + + +team_ct = ContentType.objects.get(app_label='main', model='team') + +crosslinked = defaultdict(lambda: defaultdict(dict)) +crosslinked_parents = defaultdict(list) +orphaned_roles = set() + + +def resolve(obj, path): + fname, _, path = path.partition('.') + new_obj = getattr(obj, fname, None) + if new_obj is None: + return set() + if not path: + return {new_obj,} + + if isinstance(new_obj, ManyToManyDescriptor): + return {x for o in new_obj.all() for x in resolve(o, path)} + + return resolve(new_obj, path) + + +for ct in ContentType.objects.order_by('id'): + cls = ct.model_class() + if cls is None: + sys.stderr.write(f"{ct!r} does not have a corresponding model class in the codebase. Skipping.\n") + continue + if not any(isinstance(f, ImplicitRoleField) for f in cls._meta.fields): + continue + for obj in cls.objects.all(): + for f in cls._meta.fields: + if not isinstance(f, ImplicitRoleField): + continue + r_id = getattr(obj, f'{f.name}_id', None) + try: + r = getattr(obj, f.name, None) + except Role.DoesNotExist: + sys.stderr.write(f"{cls} id={obj.id} {f.name} points to Role id={r_id}, which is not in the database.\n") + crosslinked[ct.id][obj.id][f'{f.name}_id'] = None + continue + if not r: + sys.stderr.write(f"{cls} id={obj.id} {f.name} does not have a Role object\n") + crosslinked[ct.id][obj.id][f'{f.name}_id'] = None + continue + if r.content_object != obj: + sys.stderr.write(f"{cls.__name__} id={obj.id} {f.name} is pointing to a Role that is assigned to a different object: role.id={r.id} {r.content_type!r} {r.object_id} {r.role_field}\n") + crosslinked[ct.id][obj.id][f'{f.name}_id'] = None + continue + + +sys.stderr.write('===================================\n') +for r in Role.objects.exclude(role_field__startswith='system_').order_by('id'): + + # The ancestor list should be a superset of both parents and implicit_parents. + # Also, parents should be a superset of implicit_parents. + parents = set(r.parents.values_list('id', flat=True)) + ancestors = set(r.ancestors.values_list('id', flat=True)) + implicit = set(json.loads(r.implicit_parents)) + + if not implicit: + sys.stderr.write(f"Role id={r.id} has no implicit_parents\n") + if not parents <= ancestors: + sys.stderr.write(f"Role id={r.id} has parents that are not in the ancestor list: {parents - ancestors}\n") + crosslinked[r.content_type_id][r.object_id][f'{r.role_field}_id'] = r.id + if not implicit <= parents: + sys.stderr.write(f"Role id={r.id} has implicit_parents that are not in the parents list: {implicit - parents}\n") + crosslinked[r.content_type_id][r.object_id][f'{r.role_field}_id'] = r.id + if not implicit <= ancestors: + sys.stderr.write(f"Role id={r.id} has implicit_parents that are not in the ancestor list: {implicit - ancestors}\n") + crosslinked[r.content_type_id][r.object_id][f'{r.role_field}_id'] = r.id + + # Check that the Role's generic foreign key points to a legitimate object + if not r.content_object: + sys.stderr.write(f"Role id={r.id} is missing a valid content_object: {r.content_type!r} {r.object_id} {r.role_field}\n") + orphaned_roles.add(r.id) + continue + + # Check the resource's role field parents for consistency with Role.parents.all(). + f = r.content_object._meta.get_field(r.role_field) + f_parent = set(f.parent_role) if isinstance(f.parent_role, list) else {f.parent_role,} + dotted = {x for p in f_parent if '.' in p for x in resolve(r.content_object, p)} + plus = set() + for p in r.parents.all(): + if p.singleton_name: + if f'singleton:{p.singleton_name}' not in f_parent: + plus.add(p) + elif (p.content_type, p.role_field) == (team_ct, 'member_role'): + # Team has been granted this role; probably legitimate. + continue + elif (p.content_type, p.object_id) == (r.content_type, r.object_id): + if p.role_field not in f_parent: + plus.add(p) + elif p in dotted: + continue + else: + plus.add(p) + + if plus: + plus_repr = [f"{x.content_type!r} {x.object_id} {x.role_field}" for x in plus] + sys.stderr.write(f"Role id={r.id} has cross-linked parents: {plus_repr}\n") + crosslinked_parents[r.id].extend(x.id for x in plus) + + try: + rev = getattr(r.content_object, r.role_field, None) + except Role.DoesNotExist: + sys.stderr.write(f"Role id={r.id} {r.content_type!r} {r.object_id} {r.role_field} points at an object with a broken role.\n") + crosslinked[r.content_type_id][r.object_id][f'{r.role_field}_id'] = r.id + continue + if rev is None or r.id != rev.id: + if rev and (r.content_type_id, r.object_id, r.role_field) == (rev.content_type_id, rev.object_id, rev.role_field): + sys.stderr.write(f"Role id={r.id} {r.content_type!r} {r.object_id} {r.role_field} is an orphaned duplicate of Role id={rev.id}, which is actually being used by the assigned resource\n") + orphaned_roles.add(r.id) + elif not rev: + sys.stderr.write(f"Role id={r.id} {r.content_type!r} {r.object_id} {r.role_field} is pointing to an object currently using no role\n") + crosslinked[r.content_type_id][r.object_id][f'{r.role_field}_id'] = r.id + else: + sys.stderr.write(f"Role id={r.id} {r.content_type!r} {r.object_id} {r.role_field} is pointing to an object using a different role: id={rev.id} {rev.content_type!r} {rev.object_id} {rev.role_field}\n") + crosslinked[r.content_type_id][r.object_id][f'{r.role_field}_id'] = r.id + continue + + +sys.stderr.write('===================================\n') + + +print(f"""\ +from collections import Counter + +from django.contrib.contenttypes.models import ContentType + +from awx.main.fields import ImplicitRoleField +from awx.main.models.rbac import Role + + +delete_counts = Counter() +update_counts = Counter() + +""") + + +print("# Resource objects that are pointing to the wrong Role. Some of these") +print("# do not have corresponding Roles anywhere, so delete the foreign key.") +print("# For those, new Roles will be constructed upon save.\n") +print("queue = set()\n") +for ct, objs in crosslinked.items(): + print(f"cls = ContentType.objects.get(id={ct}).model_class()\n") + for obj, kv in objs.items(): + print(f"c = cls.objects.filter(id={obj}).update(**{kv!r})") + print("update_counts.update({cls._meta.label: c})") + print(f"queue.add((cls, {obj}))") + +print("\n# Role objects that are assigned to objects that do not exist") +for r in orphaned_roles: + print(f"c = Role.objects.filter(id={r}).update(object_id=None)") + print("update_counts.update({'main.Role': c})") + print(f"_, c = Role.objects.filter(id={r}).delete()") + print("delete_counts.update(c)") + +print('\n\n') +for child, parents in crosslinked_parents.items(): + print(f"r = Role.objects.get(id={child})") + print(f"r.parents.remove(*Role.objects.filter(id__in={parents!r}))") + print(f"queue.add((r.content_object.__class__, r.object_id))") + +print('\n\n') +print('print("Objects deleted:", dict(delete_counts.most_common()))') +print('print("Objects updated:", dict(update_counts.most_common()))') + +print("\n\nfor cls, obj_id in queue:") +print(" role_fields = [f for f in cls._meta.fields if isinstance(f, ImplicitRoleField)]") +print(" obj = cls.objects.get(id=obj_id)") +print(" for f in role_fields:") +print(" r = getattr(obj, f.name, None)") +print(" if r is not None:") +print(" print(f'updating implicit parents on Role {r.id}')") +print(" r.implicit_parents = '[]'") +print(" r.save()") +print(" obj.save()") diff --git a/tools/scripts/ig-hotfix/scenarios/test.py b/tools/scripts/ig-hotfix/scenarios/test.py new file mode 100644 index 000000000000..c4791314e64d --- /dev/null +++ b/tools/scripts/ig-hotfix/scenarios/test.py @@ -0,0 +1,19 @@ +from django.db import connection +from awx.main.models import InstanceGroup + +InstanceGroup.objects.filter(name__in=('green', 'yellow', 'red')).delete() + +green = InstanceGroup.objects.create(name='green') +red = InstanceGroup.objects.create(name='red') +yellow = InstanceGroup.objects.create(name='yellow') + +for ig in InstanceGroup.objects.all(): + print((ig.id, ig.name, ig.use_role_id)) + +with connection.cursor() as cursor: + cursor.execute("UPDATE main_instancegroup SET use_role_id = NULL WHERE name = 'red'") + cursor.execute(f"UPDATE main_instancegroup SET use_role_id = {green.use_role_id} WHERE name = 'yellow'") + +print("=====================================") +for ig in InstanceGroup.objects.all(): + print((ig.id, ig.name, ig.use_role_id)) diff --git a/tools/scripts/ig-hotfix/scenarios/test2.py b/tools/scripts/ig-hotfix/scenarios/test2.py new file mode 100644 index 000000000000..66ec04d78a1d --- /dev/null +++ b/tools/scripts/ig-hotfix/scenarios/test2.py @@ -0,0 +1,20 @@ +from django.db import connection +from awx.main.models import InstanceGroup + +InstanceGroup.objects.filter(name__in=('green', 'yellow', 'red')).delete() + +green = InstanceGroup.objects.create(name='green') +red = InstanceGroup.objects.create(name='red') +yellow = InstanceGroup.objects.create(name='yellow') + +for ig in InstanceGroup.objects.all(): + print((ig.id, ig.name, ig.use_role_id)) + +with connection.cursor() as cursor: + cursor.execute(f"UPDATE main_rbac_roles SET object_id = NULL WHERE id = {red.use_role_id}") + cursor.execute("UPDATE main_instancegroup SET use_role_id = NULL WHERE name = 'red'") + cursor.execute(f"UPDATE main_instancegroup SET use_role_id = {green.use_role_id} WHERE name = 'yellow'") + +print("=====================================") +for ig in InstanceGroup.objects.all(): + print((ig.id, ig.name, ig.use_role_id)) diff --git a/tools/scripts/ig-hotfix/scenarios/test3.py b/tools/scripts/ig-hotfix/scenarios/test3.py new file mode 100644 index 000000000000..2bf17d705ea3 --- /dev/null +++ b/tools/scripts/ig-hotfix/scenarios/test3.py @@ -0,0 +1,28 @@ +from django.db import connection +from awx.main.models import InstanceGroup + +InstanceGroup.objects.filter(name__in=('green', 'yellow', 'red', 'blue')).delete() + +green = InstanceGroup.objects.create(name='green') +red = InstanceGroup.objects.create(name='red') +yellow = InstanceGroup.objects.create(name='yellow') +blue = InstanceGroup.objects.create(name='blue') + +for ig in InstanceGroup.objects.all(): + print((ig.id, ig.name, ig.use_role_id)) + +with connection.cursor() as cursor: + cursor.execute("ALTER TABLE main_instancegroup DROP CONSTRAINT main_instancegroup_use_role_id_48ea7ecc_fk_main_rbac_roles_id") + + cursor.execute(f"UPDATE main_rbac_roles SET object_id = NULL WHERE id = {red.use_role_id}") + cursor.execute(f"DELETE FROM main_rbac_roles_parents WHERE from_role_id = {blue.use_role_id} OR to_role_id = {blue.use_role_id}") + cursor.execute(f"DELETE FROM main_rbac_role_ancestors WHERE ancestor_id = {blue.use_role_id} OR descendent_id = {blue.use_role_id}") + cursor.execute(f"DELETE FROM main_rbac_roles WHERE id = {blue.use_role_id}") + cursor.execute("UPDATE main_instancegroup SET use_role_id = NULL WHERE name = 'red'") + cursor.execute(f"UPDATE main_instancegroup SET use_role_id = {green.use_role_id} WHERE name = 'yellow'") + + cursor.execute("ALTER TABLE main_instancegroup ADD CONSTRAINT main_instancegroup_use_role_id_48ea7ecc_fk_main_rbac_roles_id FOREIGN KEY (use_role_id) REFERENCES public.main_rbac_roles(id) DEFERRABLE INITIALLY DEFERRED NOT VALID") + +print("=====================================") +for ig in InstanceGroup.objects.all(): + print((ig.id, ig.name, ig.use_role_id)) diff --git a/tools/scripts/ig-hotfix/scenarios/test4.py b/tools/scripts/ig-hotfix/scenarios/test4.py new file mode 100644 index 000000000000..9198ac94f393 --- /dev/null +++ b/tools/scripts/ig-hotfix/scenarios/test4.py @@ -0,0 +1,26 @@ +from django.db import connection +from awx.main.models import InstanceGroup + +InstanceGroup.objects.filter(name__in=('green', 'yellow', 'red')).delete() + +green = InstanceGroup.objects.create(name='green') +red = InstanceGroup.objects.create(name='red') +yellow = InstanceGroup.objects.create(name='yellow') + +for ig in InstanceGroup.objects.all(): + print((ig.id, ig.name, ig.use_role_id)) + +with connection.cursor() as cursor: + cursor.execute("UPDATE main_instancegroup SET use_role_id = NULL WHERE name = 'red'") + cursor.execute(f"UPDATE main_instancegroup SET use_role_id = {green.use_role_id} WHERE name = 'yellow'") + +green.refresh_from_db() +red.refresh_from_db() +yellow.refresh_from_db() +green.save() +red.save() +yellow.save() + +print("=====================================") +for ig in InstanceGroup.objects.all(): + print((ig.id, ig.name, ig.use_role_id)) diff --git a/tools/sosreport/controller.py b/tools/sosreport/controller.py index 34a5bd525494..318e2cc7efd4 100644 --- a/tools/sosreport/controller.py +++ b/tools/sosreport/controller.py @@ -25,6 +25,7 @@ "ls -ll /var/run/awx-receptor", # list contents of dirctory where receptor socket should be "ls -ll /etc/receptor", "receptorctl --socket /var/run/awx-receptor/receptor.sock status", # Get information about the status of the mesh + "receptorctl --socket /var/run/awx-receptor/receptor.sock work list", # Get list of receptor work units "umask -p", # check current umask ]