Merge branch 'devel' into rbac

This commit is contained in:
Akita Noek 2016-02-24 16:14:32 -05:00
commit e18592fa87
20 changed files with 530 additions and 121 deletions

View File

@ -1,4 +1,5 @@
PYTHON = python
PYTHON_VERSION = $(shell $(PYTHON) -c "from distutils.sysconfig import get_python_version; print get_python_version()")
SITELIB=$(shell $(PYTHON) -c "from distutils.sysconfig import get_python_lib; print get_python_lib()")
OFFICIAL ?= no
PACKER ?= packer
@ -241,7 +242,11 @@ requirements requirements_dev requirements_jenkins: %: real-%
# * --user (in conjunction with PYTHONUSERBASE="awx" may be a better option
# * --target implies --ignore-installed
real-requirements:
pip install -r requirements/requirements.txt --target awx/lib/site-packages/ --install-option="--install-platlib=\$$base/lib/python"
@if [ "$(PYTHON_VERSION)" = "2.6" ]; then \
pip install -r requirements/requirements_python26.txt --target awx/lib/site-packages/ --install-option="--install-platlib=\$$base/lib/python"; \
else \
pip install -r requirements/requirements.txt --target awx/lib/site-packages/ --install-option="--install-platlib=\$$base/lib/python"; \
fi
real-requirements_dev:
pip install -r requirements/requirements_dev.txt --target awx/lib/site-packages/ --install-option="--install-platlib=\$$base/lib/python"

View File

@ -155,6 +155,22 @@ class APIView(views.APIView):
context = self.get_description_context()
return render_to_string(template_list, context)
def update_raw_data(self, data):
# Remove the parent key if the view is a sublist, since it will be set
# automatically.
parent_key = getattr(self, 'parent_key', None)
if parent_key:
data.pop(parent_key, None)
# Use request data as-is when original request is an update and the
# submitted data was rejected.
request_method = getattr(self, '_raw_data_request_method', None)
response_status = getattr(self, '_raw_data_response_status', 0)
if request_method in ('POST', 'PUT', 'PATCH') and response_status in xrange(400, 500):
return self.request.data.copy()
return data
class GenericAPIView(generics.GenericAPIView, APIView):
# Base class for all model-based views.
@ -166,11 +182,14 @@ class GenericAPIView(generics.GenericAPIView, APIView):
def get_serializer(self, *args, **kwargs):
serializer = super(GenericAPIView, self).get_serializer(*args, **kwargs)
# Override when called from browsable API to generate raw data form;
# always remove read only fields from sample raw data.
# update serializer "validated" data to be displayed by the raw data
# form.
if hasattr(self, '_raw_data_form_marker'):
# Always remove read only fields from serializer.
for name, field in serializer.fields.items():
if getattr(field, 'read_only', None):
del serializer.fields[name]
serializer._data = self.update_raw_data(serializer.data)
return serializer
def get_queryset(self):
@ -439,6 +458,10 @@ class RetrieveUpdateAPIView(RetrieveAPIView, generics.RetrieveUpdateAPIView):
self.update_filter(request, *args, **kwargs)
return super(RetrieveUpdateAPIView, self).update(request, *args, **kwargs)
def partial_update(self, request, *args, **kwargs):
self.update_filter(request, *args, **kwargs)
return super(RetrieveUpdateAPIView, self).partial_update(request, *args, **kwargs)
def update_filter(self, request, *args, **kwargs):
''' scrub any fields the user cannot/should not put/patch, based on user context. This runs after read-only serialization filtering '''
pass

View File

@ -4,6 +4,7 @@
# Django
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.utils.encoding import force_text
# Django REST Framework
from rest_framework import exceptions
@ -17,8 +18,28 @@ from awx.main.models import InventorySource
class Metadata(metadata.SimpleMetadata):
# DRF 3.3 doesn't render choices for read-only fields
#
# We want to render choices for read-only fields
#
# Note: This works in conjuction with logic in serializers.py that sets
# field property editable=True before calling DRF build_standard_field()
# Note: Consider expanding this rendering for more than just choices fields
def _render_read_only_choices(self, field, field_info):
if field_info.get('read_only') and hasattr(field, 'choices'):
field_info['choices'] = [
{
'value': choice_value,
'display_name': force_text(choice_name, strings_only=True)
}
for choice_value, choice_name in field.choices.items()
]
return field_info
def get_field_info(self, field):
field_info = super(Metadata, self).get_field_info(field)
if hasattr(field, 'choices') and field.choices:
field_info = self._render_read_only_choices(field, field_info)
# Indicate if a field has a default value.
# FIXME: Still isn't showing all default values?

30
awx/api/parsers.py Normal file
View File

@ -0,0 +1,30 @@
# Python
from collections import OrderedDict
import json
# Django
from django.conf import settings
from django.utils import six
# Django REST Framework
from rest_framework import parsers
from rest_framework.exceptions import ParseError
class JSONParser(parsers.JSONParser):
"""
Parses JSON-serialized data, preserving order of dictionary keys.
"""
def parse(self, stream, media_type=None, parser_context=None):
"""
Parses the incoming bytestream as JSON and returns the resulting data.
"""
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
try:
data = stream.read().decode(encoding)
return json.loads(data, object_pairs_hook=OrderedDict)
except ValueError as exc:
raise ParseError('JSON parse error - %s' % six.text_type(exc))

View File

@ -17,17 +17,29 @@ class BrowsableAPIRenderer(renderers.BrowsableAPIRenderer):
return renderers.JSONRenderer()
return renderer
def get_context(self, data, accepted_media_type, renderer_context):
# Store the associated response status to know how to populate the raw
# data form.
try:
setattr(renderer_context['view'], '_raw_data_response_status', renderer_context['response'].status_code)
return super(BrowsableAPIRenderer, self).get_context(data, accepted_media_type, renderer_context)
finally:
delattr(renderer_context['view'], '_raw_data_response_status')
def get_raw_data_form(self, data, view, method, request):
# Set a flag on the view to indiciate to the view/serializer that we're
# creating a raw data form for the browsable API.
# creating a raw data form for the browsable API. Store the original
# request method to determine how to populate the raw data form.
try:
setattr(view, '_raw_data_form_marker', True)
setattr(view, '_raw_data_request_method', request.method)
return super(BrowsableAPIRenderer, self).get_raw_data_form(data, view, method, request)
finally:
delattr(view, '_raw_data_form_marker')
delattr(view, '_raw_data_request_method')
def get_rendered_html_form(self, data, view, method, request):
'''Never show auto-generated form (only raw form).'''
# Never show auto-generated form (only raw form).
obj = getattr(view, 'object', None)
if not self.show_form_for_method(view, method, request, obj):
return

View File

@ -8,7 +8,6 @@ import re
import logging
from collections import OrderedDict
from dateutil import rrule
from ast import literal_eval
from rest_framework_mongoengine.serializers import DocumentSerializer
@ -399,7 +398,22 @@ class BaseSerializer(serializers.ModelSerializer):
return obj.active
def build_standard_field(self, field_name, model_field):
# DRF 3.3 serializers.py::build_standard_field() -> utils/field_mapping.py::get_field_kwargs() short circuits
# when a Model's editable field is set to False. The short circuit skips choice rendering.
#
# This logic is to force rendering choice's on an uneditable field.
# Note: Consider expanding this rendering for more than just choices fields
# Note: This logic works in conjuction with
if hasattr(model_field, 'choices') and model_field.choices:
was_editable = model_field.editable
model_field.editable = True
field_class, field_kwargs = super(BaseSerializer, self).build_standard_field(field_name, model_field)
if hasattr(model_field, 'choices') and model_field.choices:
model_field.editable = was_editable
if was_editable is False:
field_kwargs['read_only'] = True
# Update help text for common fields.
opts = self.Meta.model._meta.concrete_model._meta
@ -532,21 +546,7 @@ class BaseSerializer(serializers.ModelSerializer):
return attrs
def to_representation(self, obj):
# FIXME: Doesn't get called anymore for an new raw data form!
# When rendering the raw data form, create an instance of the model so
# that the model defaults will be filled in.
view = self.context.get('view', None)
parent_key = getattr(view, 'parent_key', None)
if not obj and hasattr(view, '_raw_data_form_marker'):
obj = self.Meta.model()
# FIXME: Would be nice to include any posted data for the raw data
# form, so that a submission with errors can be modified in place
# and resubmitted.
ret = super(BaseSerializer, self).to_representation(obj)
# Remove parent key from raw form data, since it will be automatically
# set by the sub list create view.
if parent_key and hasattr(view, '_raw_data_form_marker'):
ret.pop(parent_key, None)
if 'resource_id' in ret and ret['resource_id'] is None:
ret.pop('resource_id')
return ret
@ -681,6 +681,12 @@ class UnifiedJobListSerializer(UnifiedJobSerializer):
class Meta:
fields = ('*', '-job_args', '-job_cwd', '-job_env', '-result_traceback', '-result_stdout')
def get_field_names(self, declared_fields, info):
field_names = super(UnifiedJobListSerializer, self).get_field_names(declared_fields, info)
# Meta multiple inheritance and -field_name options don't seem to be
# taking effect above, so remove the undesired fields here.
return tuple(x for x in field_names if x not in ('job_args', 'job_cwd', 'job_env', 'result_traceback', 'result_stdout'))
def get_types(self):
if type(self) is UnifiedJobListSerializer:
return ['project_update', 'inventory_update', 'job', 'ad_hoc_command', 'system_job']
@ -1066,6 +1072,14 @@ class HostSerializer(BaseSerializerWithVariables):
'last_job_host_summary')
read_only_fields = ('last_job', 'last_job_host_summary')
def build_relational_field(self, field_name, relation_info):
field_class, field_kwargs = super(HostSerializer, self).build_relational_field(field_name, relation_info)
# Inventory is read-only unless creating a new host.
if self.instance and field_name == 'inventory':
field_kwargs['read_only'] = True
field_kwargs.pop('queryset', None)
return field_class, field_kwargs
def get_related(self, obj):
res = super(HostSerializer, self).get_related(obj)
res.update(dict(
@ -1124,15 +1138,12 @@ class HostSerializer(BaseSerializerWithVariables):
return value
def validate(self, attrs):
name = force_text(attrs.get('name', ''))
name = force_text(attrs.get('name', self.instance and self.instance.name or ''))
host, port = self._get_host_port_from_name(name)
if port:
attrs['name'] = host
if self.instance:
variables = force_text(attrs.get('variables', self.instance.variables) or '')
else:
variables = force_text(attrs.get('variables', ''))
variables = force_text(attrs.get('variables', self.instance and self.instance.variables or ''))
try:
vars_dict = json.loads(variables.strip() or '{}')
vars_dict['ansible_ssh_port'] = port
@ -1170,6 +1181,14 @@ class GroupSerializer(BaseSerializerWithVariables):
'total_hosts', 'hosts_with_active_failures', 'total_groups',
'groups_with_active_failures', 'has_inventory_sources')
def build_relational_field(self, field_name, relation_info):
field_class, field_kwargs = super(GroupSerializer, self).build_relational_field(field_name, relation_info)
# Inventory is read-only unless creating a new group.
if self.instance and field_name == 'inventory':
field_kwargs['read_only'] = True
field_kwargs.pop('queryset', None)
return field_class, field_kwargs
def get_related(self, obj):
res = super(GroupSerializer, self).get_related(obj)
res.update(dict(
@ -1318,8 +1337,9 @@ class InventorySourceOptionsSerializer(BaseSerializer):
# TODO: Validate source, validate source_regions
errors = {}
source_script = attrs.get('source_script', None)
if 'source' in attrs and attrs.get('source', '') == 'custom':
source = attrs.get('source', self.instance and self.instance.source or '')
source_script = attrs.get('source_script', self.instance and self.instance.source_script or '')
if source == 'custom':
if source_script is None or source_script == '':
errors['source_script'] = 'source_script must be provided'
else:
@ -1472,7 +1492,6 @@ class RoleSerializer(BaseSerializer):
# a model that no longer exists. This is dirty data and ideally
# doesn't exist, but in case it does, let's not puke.
pass
return ret
@ -1613,9 +1632,10 @@ class JobOptionsSerializer(BaseSerializer):
def validate(self, attrs):
if 'project' in self.fields and 'playbook' in self.fields:
project = attrs.get('project', None)
playbook = attrs.get('playbook', '')
if not project and attrs.get('job_type') != PERM_INVENTORY_SCAN:
project = attrs.get('project', self.instance and self.instance.project or None)
playbook = attrs.get('playbook', self.instance and self.instance.playbook or '')
job_type = attrs.get('job_type', self.instance and self.instance.job_type or None)
if not project and job_type != PERM_INVENTORY_SCAN:
raise serializers.ValidationError({'project': 'This field is required.'})
if project and playbook and force_text(playbook) not in project.playbooks:
raise serializers.ValidationError({'playbook': 'Playbook not found for project'})
@ -1669,8 +1689,8 @@ class JobTemplateSerializer(UnifiedJobTemplateSerializer, JobOptionsSerializer):
return d
def validate(self, attrs):
survey_enabled = attrs.get('survey_enabled', False)
job_type = attrs.get('job_type', None)
survey_enabled = attrs.get('survey_enabled', self.instance and self.instance.survey_enabled or False)
job_type = attrs.get('job_type', self.instance and self.instance.job_type or None)
if survey_enabled and job_type == PERM_INVENTORY_SCAN:
raise serializers.ValidationError({'survey_enabled': 'Survey Enabled can not be used with scan jobs'})
@ -1828,8 +1848,8 @@ class AdHocCommandSerializer(UnifiedJobSerializer):
def get_field_names(self, declared_fields, info):
field_names = super(AdHocCommandSerializer, self).get_field_names(declared_fields, info)
# Meta inheritance and -field_name options don't seem to be taking
# effect above, so remove the undesired fields here.
# Meta multiple inheritance and -field_name options don't seem to be
# taking effect above, so remove the undesired fields here.
return tuple(x for x in field_names if x not in ('unified_job_template', 'description'))
def build_standard_field(self, field_name, model_field):
@ -1861,19 +1881,7 @@ class AdHocCommandSerializer(UnifiedJobSerializer):
return res
def to_representation(self, obj):
# In raw data form, populate limit field from host/group name.
view = self.context.get('view', None)
parent_model = getattr(view, 'parent_model', None)
if not (obj and obj.pk) and view and hasattr(view, '_raw_data_form_marker'):
if not obj:
obj = self.Meta.model()
ret = super(AdHocCommandSerializer, self).to_representation(obj)
# Hide inventory and limit fields from raw data, since they will be set
# automatically by sub list create view.
if not (obj and obj.pk) and view and hasattr(view, '_raw_data_form_marker'):
if parent_model in (Host, Group):
ret.pop('inventory', None)
ret.pop('limit', None)
if 'inventory' in ret and (not obj.inventory or not obj.inventory.active):
ret['inventory'] = None
if 'credential' in ret and (not obj.credential or not obj.credential.active):
@ -2051,6 +2059,7 @@ class JobLaunchSerializer(BaseSerializer):
variables_needed_to_start = serializers.ReadOnlyField()
credential_needed_to_start = serializers.SerializerMethodField()
survey_enabled = serializers.SerializerMethodField()
extra_vars = VerbatimField(required=False)
class Meta:
model = JobTemplate
@ -2084,7 +2093,7 @@ class JobLaunchSerializer(BaseSerializer):
obj = self.context.get('obj')
data = self.context.get('data')
credential = attrs.get('credential', None) or (obj and obj.credential)
credential = attrs.get('credential', obj and obj.credential or None)
if not credential or not credential.active:
errors['credential'] = 'Credential not provided'
@ -2097,20 +2106,16 @@ class JobLaunchSerializer(BaseSerializer):
except KeyError:
errors['passwords_needed_to_start'] = credential.passwords_needed
extra_vars = force_text(attrs.get('extra_vars', {}))
try:
extra_vars = literal_eval(extra_vars)
extra_vars = json.dumps(extra_vars)
except Exception:
pass
extra_vars = attrs.get('extra_vars', {})
try:
extra_vars = json.loads(extra_vars)
except (ValueError, TypeError):
if isinstance(extra_vars, basestring):
try:
extra_vars = yaml.safe_load(extra_vars)
except (yaml.YAMLError, TypeError, AttributeError):
errors['extra_vars'] = 'Must be valid JSON or YAML'
extra_vars = json.loads(extra_vars)
except (ValueError, TypeError):
try:
extra_vars = yaml.safe_load(extra_vars)
except (yaml.YAMLError, TypeError, AttributeError):
errors['extra_vars'] = 'Must be valid JSON or YAML'
if not isinstance(extra_vars, dict):
extra_vars = {}

View File

@ -228,7 +228,7 @@ class ApiV1ConfigView(APIView):
def post(self, request):
if not request.user.is_superuser:
return Response(None, status=status.HTTP_404_NOT_FOUND)
if not type(request.data) == dict:
if not isinstance(request.data, dict):
return Response({"error": "Invalid license data"}, status=status.HTTP_400_BAD_REQUEST)
if "eula_accepted" not in request.data:
return Response({"error": "Missing 'eula_accepted' property"}, status=status.HTTP_400_BAD_REQUEST)
@ -570,8 +570,21 @@ class AuthTokenView(APIView):
serializer_class = AuthTokenSerializer
model = AuthToken
def get_serializer(self, *args, **kwargs):
serializer = self.serializer_class(*args, **kwargs)
# Override when called from browsable API to generate raw data form;
# update serializer "validated" data to be displayed by the raw data
# form.
if hasattr(self, '_raw_data_form_marker'):
# Always remove read only fields from serializer.
for name, field in serializer.fields.items():
if getattr(field, 'read_only', None):
del serializer.fields[name]
serializer._data = self.update_raw_data(serializer.data)
return serializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
request_hash = AuthToken.get_request_hash(self.request)
try:
@ -1212,6 +1225,19 @@ class HostGroupsList(SubListCreateAttachDetachAPIView):
parent_model = Host
relationship = 'groups'
def update_raw_data(self, data):
data.pop('inventory', None)
return super(HostGroupsList, self).update_raw_data(data)
def create(self, request, *args, **kwargs):
# Inject parent host inventory ID into new group data.
data = request.data
# HACK: Make request data mutable.
if getattr(data, '_mutable', None) is False:
data._mutable = True
data['inventory'] = self.get_parent_object().inventory_id
return super(HostGroupsList, self).create(request, *args, **kwargs)
class HostAllGroupsList(SubListAPIView):
''' the list of all groups of which the host is directly or indirectly a member '''
@ -1368,6 +1394,19 @@ class GroupChildrenList(SubListCreateAttachDetachAPIView):
parent_model = Group
relationship = 'children'
def update_raw_data(self, data):
data.pop('inventory', None)
return super(GroupChildrenList, self).update_raw_data(data)
def create(self, request, *args, **kwargs):
# Inject parent group inventory ID into new group data.
data = request.data
# HACK: Make request data mutable.
if getattr(data, '_mutable', None) is False:
data._mutable = True
data['inventory'] = self.get_parent_object().inventory_id
return super(GroupChildrenList, self).create(request, *args, **kwargs)
def unattach(self, request, *args, **kwargs):
sub_id = request.data.get('id', None)
if sub_id is not None:
@ -1428,8 +1467,14 @@ class GroupHostsList(SubListCreateAttachDetachAPIView):
parent_model = Group
relationship = 'hosts'
def update_raw_data(self, data):
data.pop('inventory', None)
return super(GroupHostsList, self).update_raw_data(data)
def create(self, request, *args, **kwargs):
parent_group = Group.objects.get(id=self.kwargs['pk'])
# Inject parent group inventory ID into new host data.
request.data['inventory'] = parent_group.inventory_id
existing_hosts = Host.objects.filter(inventory=parent_group.inventory, name=request.data['name'])
if existing_hosts.count() > 0 and ('variables' not in request.data or
request.data['variables'] == '' or
@ -1930,13 +1975,13 @@ class JobTemplateSurveySpec(GenericAPIView):
return Response(dict(error="'description' missing from survey spec"), status=status.HTTP_400_BAD_REQUEST)
if "spec" not in obj.survey_spec:
return Response(dict(error="'spec' missing from survey spec"), status=status.HTTP_400_BAD_REQUEST)
if type(obj.survey_spec["spec"]) != list:
if not isinstance(obj.survey_spec["spec"], list):
return Response(dict(error="'spec' must be a list of items"), status=status.HTTP_400_BAD_REQUEST)
if len(obj.survey_spec["spec"]) < 1:
return Response(dict(error="'spec' doesn't contain any items"), status=status.HTTP_400_BAD_REQUEST)
idx = 0
for survey_item in obj.survey_spec["spec"]:
if type(survey_item) != dict:
if not isinstance(survey_item, dict):
return Response(dict(error="survey element %s is not a json object" % str(idx)), status=status.HTTP_400_BAD_REQUEST)
if "type" not in survey_item:
return Response(dict(error="'type' missing from survey element %s" % str(idx)), status=status.HTTP_400_BAD_REQUEST)
@ -2617,6 +2662,15 @@ class AdHocCommandList(ListCreateAPIView):
def dispatch(self, *args, **kwargs):
return super(AdHocCommandList, self).dispatch(*args, **kwargs)
def update_raw_data(self, data):
# Hide inventory and limit fields from raw data, since they will be set
# automatically by sub list create view.
parent_model = getattr(self, 'parent_model', None)
if parent_model in (Host, Group):
data.pop('inventory', None)
data.pop('limit', None)
return super(AdHocCommandList, self).update_raw_data(data)
def create(self, request, *args, **kwargs):
# Inject inventory ID and limit if parent objects is a host/group.
if hasattr(self, 'get_parent_object') and not getattr(self, 'parent_key', None):

View File

@ -26,7 +26,7 @@ class Migration(migrations.Migration):
('key', models.CharField(unique=True, max_length=255)),
('description', models.TextField()),
('category', models.CharField(max_length=128)),
('value', models.TextField()),
('value', models.TextField(blank=True)),
('value_type', models.CharField(max_length=12, choices=[(b'string', 'String'), (b'int', 'Integer'), (b'float', 'Decimal'), (b'json', 'JSON'), (b'bool', 'Boolean'), (b'password', 'Password'), (b'list', 'List')])),
('user', models.ForeignKey(related_name='settings', default=None, editable=False, to=settings.AUTH_USER_MODEL, null=True)),
],

View File

@ -324,7 +324,7 @@ class JobTemplate(UnifiedJobTemplate, JobOptions, ResourceMixin):
except Exception:
try:
kwargs_extra_vars = yaml.safe_load(kwargs_extra_vars)
assert type(kwargs_extra_vars) is dict
assert isinstance(kwargs_extra_vars, dict)
except:
kwargs_extra_vars = {}
else:
@ -504,7 +504,7 @@ class Job(UnifiedJob, JobOptions):
def handle_extra_data(self, extra_data):
extra_vars = {}
if type(extra_data) == dict:
if isinstance(extra_data, dict):
extra_vars = extra_data
elif extra_data is None:
return
@ -1087,7 +1087,7 @@ class SystemJob(UnifiedJob, SystemJobOptions):
def handle_extra_data(self, extra_data):
extra_vars = {}
if type(extra_data) == dict:
if isinstance(extra_data, dict):
extra_vars = extra_data
elif extra_data is None:
return

View File

@ -321,7 +321,7 @@ class UnifiedJobTemplate(PolymorphicModel, CommonModelNameNotUnique):
value = value.id
create_kwargs[id_field_name] = value
elif field_name in kwargs:
if field_name == 'extra_vars' and type(kwargs[field_name]) == dict:
if field_name == 'extra_vars' and isinstance(kwargs[field_name], dict):
create_kwargs[field_name] = json.dumps(kwargs['extra_vars'])
else:
create_kwargs[field_name] = kwargs[field_name]

View File

@ -0,0 +1,17 @@
import pytest
from awx.main.models import UnifiedJob
from django.core.urlresolvers import reverse
@pytest.mark.django_db
def test_options_fields_choices(instance, options, user):
url = reverse('api:unified_job_list')
response = options(url, None, user('admin', True))
assert 'launch_type' in response.data['actions']['GET']
assert 'choice' == response.data['actions']['GET']['launch_type']['type']
assert UnifiedJob.LAUNCH_TYPE_CHOICES == response.data['actions']['GET']['launch_type']['choices']
assert 'choice' == response.data['actions']['GET']['status']['type']
assert UnifiedJob.STATUS_CHOICES == response.data['actions']['GET']['status']['choices']

View File

@ -758,6 +758,7 @@ class ProjectsTest(BaseTransactionTest):
team_permission['name'] += '2'
team_permission['user'] = user.pk
self.post(url, team_permission, expect=400, auth=self.get_super_credentials())
del team_permission['user']
# can list permissions on a user
url = reverse('api:user_permissions_list', args=(user.pk,))

View File

@ -38,6 +38,7 @@ import os
import pwd
import urlparse
import re
from copy import deepcopy
# Requests
import requests
@ -72,6 +73,40 @@ else:
pass
statsd = NoStatsClient()
CENSOR_FIELD_WHITELIST=[
'msg',
'failed',
'changed',
'results',
'start',
'end',
'delta',
'cmd',
'_ansible_no_log',
'cmd',
'rc',
'failed_when_result',
'skipped',
'skip_reason',
]
def censor(obj):
if obj.get('_ansible_no_log', False):
new_obj = {}
for k in CENSOR_FIELD_WHITELIST:
if k in obj:
new_obj[k] = obj[k]
if k == 'cmd' and k in obj:
if re.search(r'\s', obj['cmd']):
new_obj['cmd'] = re.sub(r'^(([^\s\\]|\\\s)+).*$',
r'\1 <censored>',
obj['cmd'])
new_obj['censored'] = "the output has been hidden due to the fact that 'no_log: true' was specified for this result"
obj = new_obj
if 'results' in obj:
for i in xrange(len(obj['results'])):
obj['results'][i] = censor(obj['results'][i])
return obj
class TokenAuth(requests.auth.AuthBase):
@ -211,6 +246,9 @@ class BaseCallbackModule(object):
response.raise_for_status()
def _log_event(self, event, **event_data):
if 'res' in event_data:
event_data['res'] = censor(deepcopy(event_data['res']))
if self.callback_consumer_port:
with statsd.timer('zmq_post_event_msg.{0}'.format(event)):
self._post_job_event_queue_msg(event, event_data)

View File

@ -133,7 +133,10 @@ class InventoryScript(object):
else:
sys.stderr.write('%s\n' % str(e))
if hasattr(e, 'response'):
sys.stderr.write('%s\n' % e.response.content)
if hasattr(e.response, 'content'):
sys.stderr.write('%s\n' % e.response.content)
else:
sys.stderr.write('%s\n' % e.response)
sys.exit(1)
def main():

View File

@ -216,7 +216,7 @@ REST_FRAMEWORK = {
'awx.api.filters.OrderByBackend',
),
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'awx.api.parsers.JSONParser',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
@ -662,10 +662,7 @@ ACTIVITY_STREAM_ENABLED = True
ACTIVITY_STREAM_ENABLED_FOR_INVENTORY_SYNC = False
# Internal API URL for use by inventory scripts and callback plugin.
if 'devserver' in INSTALLED_APPS:
INTERNAL_API_URL = 'http://127.0.0.1:%s' % DEVSERVER_DEFAULT_PORT
else:
INTERNAL_API_URL = 'http://127.0.0.1:8000'
INTERNAL_API_URL = 'http://127.0.0.1:%s' % DEVSERVER_DEFAULT_PORT
# ZeroMQ callback settings.
CALLBACK_CONSUMER_PORT = "tcp://127.0.0.1:5556"

View File

@ -29,8 +29,7 @@
window.pendo_options = {
// This is required to be able to load data client side
usePendoAgentAPI: true,
disableGuides: true
usePendoAgentAPI: true
};
</script>

View File

@ -0,0 +1,73 @@
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.

View File

@ -1,21 +1,22 @@
amqp==1.4.5
git+https://github.com/chrismeyersfsu/ansiconv.git@tower_1.0.0#egg=ansiconv
amqp==1.4.5
anyjson==0.3.3
apache-libcloud==0.15.1
appdirs==1.4.0
argparse==1.2.1
azure==0.9.0
Babel==1.3
Babel==2.2.0
billiard==3.3.0.16
boto==2.34.0
celery==3.1.10
cffi==1.1.2
cliff==1.13.0
cffi==1.5.0
cliff==1.15.0
cmd2==0.6.8
cryptography==0.9.3
d2to1==0.2.11
defusedxml==0.4.1
Django==1.8.8
debtcollector==1.2.0
decorator==4.0.6
django-auth-ldap==1.2.6
django-celery==3.1.17
django-crum==0.6.1
@ -28,9 +29,7 @@ django-split-settings==0.1.1
django-statsd-mozilla==0.3.16
django-taggit==0.17.6
git+https://github.com/matburt/dm.xmlsec.binding.git@master#egg=dm.xmlsec.binding
dogpile.cache==0.5.6
dogpile.core==0.4.1
enum34==1.0.4
#functools32==3.2.3-2
gevent==1.1rc3
gevent-websocket==0.9.3
@ -39,85 +38,95 @@ git+https://github.com/chrismeyersfsu/django-qsstats-magic.git@tower_0.7.2#egg=d
git+https://github.com/umutbozkurt/django-rest-framework-mongoengine.git@5dfa1df79f81765d36c0de31dc1c2f390e42d428#egg=django-rest-framework-mongoengine
git+https://github.com/chrismeyersfsu/gevent-socketio.git@tower_0.3.6#egg=gevent-socketio
git+https://github.com/chrismeyersfsu/python-ipy.git@fix-127_localhost#egg=IPy
git+https://github.com/chrismeyersfsu/python-keystoneclient.git@1.3.0#egg=python-keystoneclient
git+https://github.com/chrismeyersfsu/shade.git@tower_0.5.0#egg=shade
git+https://github.com/chrismeyersfsu/sitecustomize.git#egg=sitecustomize
greenlet==0.4.9
httplib2==0.9
dogpile.cache==0.5.7
enum34==1.1.2
futures==3.0.4
httplib2==0.9.2
idna==2.0
importlib==1.0.3
ipaddress==1.0.14
iso8601==0.1.10
ip-associations-python-novaclient-ext==0.1
ipaddress==1.0.16
iso8601==0.1.11
isodate==0.5.1
jsonpatch==1.11
jsonpointer==1.9
jsonpatch==1.12
jsonpointer==1.10
jsonschema==2.5.1
keyring==4.1
kombu==3.0.30
lxml==3.4.4
M2Crypto==0.22.3
Markdown==2.4.1
M2Crypto==0.22.3
mock==1.0.1
mongoengine==0.9.0
msgpack-python==0.4.6
netaddr==0.7.14
monotonic==0.6
msgpack-python==0.4.7
munch==2.0.4
netaddr==0.7.18
netifaces==0.10.4
oauthlib==1.0.3
ordereddict==1.1
os-client-config==1.6.1
os-diskconfig-python-novaclient-ext==0.1.2
oslo.config==1.9.3
oslo.i18n==1.5.0
oslo.serialization==1.4.0
oslo.utils==1.4.0
os-client-config==1.14.0
os-diskconfig-python-novaclient-ext==0.1.3
os-networksv2-python-novaclient-ext==0.25
os-virtual-interfacesv2-python-novaclient-ext==0.19
pbr==0.11.1
oslo.config==3.3.0
oslo.i18n==3.2.0
oslo.serialization==2.2.0
oslo.utils==3.4.0
pexpect==3.1
pip==1.5.4
prettytable==0.7.2
psphere==0.5.2
psutil==3.1.1
psycopg2
pyasn1==0.1.8
pycparser==2.14
pyasn1==0.1.9
pycrypto==2.6.1
pycparser==2.14
PyJWT==1.4.0
pymongo==2.8
pyOpenSSL==0.15.1
pyparsing==2.0.3
pyparsing==2.0.7
pyrad==2.0
pyrax==1.9.3
python-cinderclient==1.1.1
pyrax==1.9.7
python-cinderclient==1.5.0
python-dateutil==2.4.0
python-glanceclient==0.17.0
python-ironicclient==0.5.0
python-glanceclient==1.1.0
python-heatclient==0.8.1
python-ironicclient==1.0.0
python-keystoneclient==2.1.1
python-ldap==2.4.20
python-neutronclient==2.3.11
python-novaclient==2.20.0
python-neutronclient==4.0.0
python-novaclient==3.2.0
python-openid==2.2.5
python-openstackclient==2.0.0
python-radius==1.0
git+https://github.com/matburt/python-social-auth.git@master#egg=python-social-auth
python-saml==2.1.4
python-swiftclient==2.2.0
python-troveclient==1.0.9
pytz==2014.10
git+https://github.com/matburt/python-social-auth.git@master#egg=python-social-auth
python-swiftclient==2.7.0
python-troveclient==1.4.0
pytz==2015.7
pywinrm==0.1.1
PyYAML==3.11
pyzmq==14.5.0
rackspace-auth-openstack==1.3
rackspace-novaclient==1.4
rax-default-network-flags-python-novaclient-ext==0.2.3
rax-scheduled-images-python-novaclient-ext==0.2.1
rackspace-novaclient==1.5
rax-default-network-flags-python-novaclient-ext==0.3.2
rax-scheduled-images-python-novaclient-ext==0.3.1
redis==2.10.3
requests==2.5.1
requests-oauthlib==0.5.0
simplejson==3.6.0
requests==2.5.1
requestsexceptions==1.1.1
shade==1.4.0
simplejson==3.8.1
six==1.9.0
statsd==3.2.1
stevedore==1.3.0
stevedore==1.10.0
suds==0.4
warlock==1.1.0
unicodecsv==0.14.1
warlock==1.2.0
wheel==0.24.0
wrapt==1.10.6
wsgiref==0.1.2
xmltodict==0.9.2

View File

@ -0,0 +1,121 @@
amqp==1.4.5
git+https://github.com/chrismeyersfsu/ansiconv.git@tower_1.0.0#egg=ansiconv
anyjson==0.3.3
apache-libcloud==0.15.1
appdirs==1.4.0
argparse==1.2.1
azure==0.9.0
Babel==1.3
billiard==3.3.0.16
boto==2.34.0
celery==3.1.10
cffi==1.1.2
cliff==1.13.0
cmd2==0.6.8
cryptography==0.9.3
d2to1==0.2.11
defusedxml==0.4.1
Django==1.6.7
django-auth-ldap==1.2.6
django-celery==3.1.10
django-crum==0.6.1
django-extensions==1.3.3
django-polymorphic==0.5.3
django-radius==1.0.0
djangorestframework==2.3.13
django-split-settings==0.1.1
django-taggit==0.11.2
git+https://github.com/matburt/dm.xmlsec.binding.git@master#egg=dm.xmlsec.binding
dogpile.cache==0.5.6
dogpile.core==0.4.1
enum34==1.0.4
#functools32==3.2.3-2
gevent==1.1rc3
gevent-websocket==0.9.3
git+https://github.com/chrismeyersfsu/django-jsonfield.git@tower_0.9.12#egg=django-jsonfield
git+https://github.com/chrismeyersfsu/django-qsstats-magic.git@tower_0.7.2#egg=django-qsstats-magic
git+https://github.com/chrismeyersfsu/django-rest-framework-mongoengine.git@0c79515257a33a0ce61500b65fa497398628a03d#egg=django-rest-framework-mongoengine
git+https://github.com/chrismeyersfsu/gevent-socketio.git@tower_0.3.6#egg=gevent-socketio
git+https://github.com/chrismeyersfsu/python-ipy.git@fix-127_localhost#egg=IPy
git+https://github.com/chrismeyersfsu/python-keystoneclient.git@1.3.0#egg=python-keystoneclient
git+https://github.com/chrismeyersfsu/shade.git@tower_0.5.0#egg=shade
git+https://github.com/chrismeyersfsu/sitecustomize.git#egg=sitecustomize
greenlet==0.4.9
httplib2==0.9
idna==2.0
importlib==1.0.3
ipaddress==1.0.14
iso8601==0.1.10
isodate==0.5.1
jsonpatch==1.11
jsonpointer==1.9
jsonschema==2.5.1
keyring==4.1
kombu==3.0.21
lxml==3.4.4
M2Crypto==0.22.3
Markdown==2.4.1
mock==1.0.1
mongoengine==0.9.0
msgpack-python==0.4.6
netaddr==0.7.14
netifaces==0.10.4
oauthlib==1.0.3
ordereddict==1.1
os-client-config==1.6.1
os-diskconfig-python-novaclient-ext==0.1.2
oslo.config==1.9.3
oslo.i18n==1.5.0
oslo.serialization==1.4.0
oslo.utils==1.4.0
os-networksv2-python-novaclient-ext==0.25
os-virtual-interfacesv2-python-novaclient-ext==0.19
pbr==0.11.1
pexpect==3.1
pip==1.5.4
prettytable==0.7.2
psphere==0.5.2
psutil==3.1.1
psycopg2
pyasn1==0.1.8
pycparser==2.14
pycrypto==2.6.1
PyJWT==1.4.0
pymongo==2.8
pyOpenSSL==0.15.1
pyparsing==2.0.3
pyrad==2.0
pyrax==1.9.3
python-cinderclient==1.1.1
python-dateutil==2.4.0
python-glanceclient==0.17.0
python-ironicclient==0.5.0
python-ldap==2.4.20
python-neutronclient==2.3.11
python-novaclient==2.20.0
python-openid==2.2.5
python-radius==1.0
git+https://github.com/matburt/python-social-auth.git@master#egg=python-social-auth
python-saml==2.1.4
python-swiftclient==2.2.0
python-troveclient==1.0.9
pytz==2014.10
pywinrm==0.1.1
PyYAML==3.11
pyzmq==14.5.0
rackspace-auth-openstack==1.3
rackspace-novaclient==1.4
rax-default-network-flags-python-novaclient-ext==0.2.3
rax-scheduled-images-python-novaclient-ext==0.2.1
redis==2.10.3
requests==2.5.1
requests-oauthlib==0.5.0
simplejson==3.6.0
six==1.9.0
South==1.0.2
stevedore==1.3.0
suds==0.4
warlock==1.1.0
wheel==0.24.0
wsgiref==0.1.2
xmltodict==0.9.2

View File

@ -5,7 +5,7 @@ ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
RUN apt-get update && apt-get install -y software-properties-common python-software-properties curl
RUN add-apt-repository -y ppa:chris-lea/redis-server; add-apt-repository -y ppa:chris-lea/zeromq; add-apt-repository -y ppa:chris-lea/node.js; add-apt-repository -y ppa:ansible/ansible
RUN add-apt-repository -y ppa:chris-lea/redis-server; add-apt-repository -y ppa:chris-lea/zeromq; add-apt-repository -y ppa:chris-lea/node.js; add-apt-repository -y ppa:ansible/ansible; add-apt-repository -y ppa:jal233/proot;
RUN curl -sL https://deb.nodesource.com/setup_0.12 | bash -
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 && apt-key adv --fetch-keys http://www.postgresql.org/media/keys/ACCC4CF8.asc
RUN echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.0.list && echo "deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main" | tee /etc/apt/sources.list.d/postgres-9.4.list
@ -13,6 +13,7 @@ RUN apt-get update
RUN apt-get install -y openssh-server ansible mg vim tmux git mercurial subversion python-dev python-psycopg2 make postgresql-client libpq-dev nodejs python-psutil libxml2-dev libxslt-dev lib32z1-dev libsasl2-dev libldap2-dev libffi-dev libzmq-dev proot python-pip libxmlsec1-dev swig redis-server && rm -rf /var/lib/apt/lists/*
RUN pip install flake8
RUN pip install pytest pytest-pythonpath pytest-django pytest-cov
RUN pip install dateutils # for private/license_writer.py
RUN /usr/bin/ssh-keygen -q -t rsa -N "" -f /root/.ssh/id_rsa
RUN mkdir -p /etc/tower
RUN mkdir -p /data/db