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.
This commit is contained in:
Elyézer Rezende 2020-06-18 15:27:35 -04:00
parent e4eef82a39
commit 37218e1695
2 changed files with 38 additions and 0 deletions

View File

@ -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

View File

@ -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 = {