From 37218e169546886141657f363efdff5f7e04089f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ely=C3=A9zer=20Rezende?= Date: Thu, 18 Jun 2020 15:27:35 -0400 Subject: [PATCH] Enforce single owner field when serializing creds The CredentialSerializerCreate expect a single owner field according to its help text but was not validating that. This makes it validate for a single owner field when creating a Credential. --- awx/api/serializers.py | 8 +++++ .../tests/functional/api/test_credential.py | 30 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/awx/api/serializers.py b/awx/api/serializers.py index 23d71203bd..9f99cd8ab4 100644 --- a/awx/api/serializers.py +++ b/awx/api/serializers.py @@ -2644,9 +2644,17 @@ class CredentialSerializerCreate(CredentialSerializer): owner_fields.add(field) else: attrs.pop(field) + if not owner_fields: raise serializers.ValidationError({"detail": _("Missing 'user', 'team', or 'organization'.")}) + if len(owner_fields) > 1: + received = ", ".join(sorted(owner_fields)) + raise serializers.ValidationError({"detail": _( + "Only one of 'user', 'team', or 'organization' should be provided, " + "received {} fields.".format(received) + )}) + if attrs.get('team'): attrs['organization'] = attrs['team'].organization diff --git a/awx/main/tests/functional/api/test_credential.py b/awx/main/tests/functional/api/test_credential.py index 5b5d1f1d1b..d023ef5e4b 100644 --- a/awx/main/tests/functional/api/test_credential.py +++ b/awx/main/tests/functional/api/test_credential.py @@ -60,6 +60,36 @@ def test_credential_validation_error_with_bad_user(post, admin, credentialtype_s assert response.data['user'][0] == 'Incorrect type. Expected pk value, received str.' +@pytest.mark.django_db +def test_credential_validation_error_with_no_owner_field(post, admin, credentialtype_ssh): + params = { + 'credential_type': credentialtype_ssh.id, + 'inputs': {'username': 'someusername'}, + 'name': 'Some name', + } + response = post(reverse('api:credential_list'), params, admin) + assert response.status_code == 400 + assert response.data['detail'][0] == "Missing 'user', 'team', or 'organization'." + + +@pytest.mark.django_db +def test_credential_validation_error_with_multiple_owner_fields(post, admin, alice, team, organization, credentialtype_ssh): + params = { + 'credential_type': credentialtype_ssh.id, + 'inputs': {'username': 'someusername'}, + 'team': team.id, + 'user': alice.id, + 'organization': organization.id, + 'name': 'Some name', + } + response = post(reverse('api:credential_list'), params, admin) + assert response.status_code == 400 + assert response.data['detail'][0] == ( + "Only one of 'user', 'team', or 'organization' should be provided, " + "received organization, team, user fields." + ) + + @pytest.mark.django_db def test_create_user_credential_via_user_credentials_list(post, get, alice, credentialtype_ssh): params = {