Skip to content

Commit

Permalink
Add validator for scope field
Browse files Browse the repository at this point in the history
Signed-off-by: Rick Elrod <[email protected]>
  • Loading branch information
relrod committed Jun 6, 2024
1 parent 3f50e26 commit 5431fe9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
15 changes: 14 additions & 1 deletion ansible_base/oauth2_provider/models/access_token.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import oauth2_provider.models as oauth2_models
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import connection, models
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
Expand All @@ -10,6 +11,18 @@
from ansible_base.lib.utils.settings import get_setting
from ansible_base.oauth2_provider.utils import is_external_account

SCOPES = ['read', 'write']


def validate_scope(value):
given_scopes = value.split(' ')
if not given_scopes:
raise ValidationError(_('Scope must be a simple space-separated string with allowed scopes: %(scopes)s') % {'scopes': ', '.join(SCOPES)})
for scope in given_scopes:
if scope not in SCOPES:
raise ValidationError(_('Invalid scope: %(scope)s. Must be one of: %(scopes)s') % {'scope': scope, 'scopes': ', '.join(SCOPES)})


activitystream = object
if 'ansible_base.activitystream' in settings.INSTALLED_APPS:
from ansible_base.activitystream.models import AuditableModel
Expand Down Expand Up @@ -52,10 +65,10 @@ class Meta(oauth2_models.AbstractAccessToken.Meta):
editable=False,
)
scope = models.CharField(
blank=True,
default='write',
max_length=32,
help_text=_("Allowed scopes, further restricts user's permissions. Must be a simple space-separated string with allowed scopes ['read', 'write']."),
validators=[validate_scope],
)
token = prevent_search(
models.CharField(
Expand Down
30 changes: 30 additions & 0 deletions test_app/tests/oauth2_provider/views/test_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,33 @@ def test_oauth2_tokens_list_for_user(
response = admin_api_client.get(url)
assert response.status_code == 200
assert len(response.data['results']) == 6


@pytest.mark.parametrize(
'given,error',
[
('read write', None),
('read', None),
('write', None),
('read write foo', 'Invalid scope: foo'),
('foo', 'Invalid scope: foo'),
('', None), # default scope is 'write'
],
)
@pytest.mark.django_db
def test_oauth2_token_scope_validator(user_api_client, given, error):
"""
Ensure that the scope validator works as expected.
"""

url = reverse("token-list")

# Create PAT
data = {
'description': 'new PAT',
'scope': given,
}
response = user_api_client.post(url, data=data)
assert response.status_code == 400 if error else 201
if error:
assert error in str(response.data['scope'][0])

0 comments on commit 5431fe9

Please sign in to comment.