Skip to content

Commit b6ec2e8

Browse files
authored
AAP-49910 - Delete legacy authenticator code (#780)
## Description <!-- Mandatory: Provide a clear, concise description of the changes and their purpose --> - What is being changed? Remove code no longer needed, as the legacy authenticator is now removed. - Why is this change needed? Since the legacy authenticators have been removed, the related DAB code is no longer needed and can be removed - How does this change address the issue? This change addresses the issue by removing the now unnecessary code. [Jira](https://issues.redhat.com/browse/AAP-49910) ## Type of Change <!-- Mandatory: Check one or more boxes that apply --> - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] Documentation update - [ ] Test update - [x] Refactoring (no functional changes) - [ ] Development environment change - [ ] Configuration change ## Self-Review Checklist <!-- These items help ensure quality - they complement our automated CI checks --> - [x] I have performed a self-review of my code - [x] I have added relevant comments to complex code sections - [x] I have updated documentation where needed - [x] I have considered the security impact of these changes - [x] I have considered performance implications - [x] I have thought about error handling and edge cases - [x] I have tested the changes in my local environment ## Testing Instructions <!-- Optional for test-only changes. Mandatory for all other changes --> <!-- Must be detailed enough for reviewers to reproduce --> ### Prerequisites <!-- List any specific setup required --> ### Steps to Test 1. Deploy this PR in aap-dev, validate all functionality works as expected 2. This change just removes unnecessary code, so no functionality should be impacted. 3. ### Expected Results <!-- Describe what should happen after following the steps --> ## Additional Context ### Required Actions After this PR merges, we can merge in the following PR in quick succession - 1. [EDA-Server](ansible/eda-server#1371) ### Screenshots/Logs <!-- Add if relevant to demonstrate the changes -->
1 parent 7dfca80 commit b6ec2e8

File tree

7 files changed

+1
-104
lines changed

7 files changed

+1
-104
lines changed

ansible_base/resource_registry/rest_client.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,9 +133,6 @@ def _get_request_dict(self, data: ResourceRequestBody):
133133
req_dict[k] = raw_dict[k]
134134
return req_dict
135135

136-
def validate_local_user(self, username: str, password: str):
137-
return self._make_request("post", "validate-local-account/", {"username": username, "password": password})
138-
139136
def get_service_metadata(self):
140137
return self._make_request("get", "metadata/")
141138

ansible_base/resource_registry/urls.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
service = [
1616
path('metadata/', views.ServiceMetadataView.as_view(), name="service-metadata"),
17-
path('validate-local-account/', views.ValidateLocalUserView.as_view(), name="validate-local-account"),
1817
path('', include(service_router.urls)),
1918
path('', views.ServiceIndexRootView.as_view(), name='service-index-root'),
2019
]

ansible_base/resource_registry/views.py

Lines changed: 1 addition & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,13 @@
22
from collections import OrderedDict
33

44
from django.conf import settings
5-
from django.contrib.auth import get_user_model
65
from django.db.models import Q
76
from django.http import HttpResponseNotFound
87
from django.shortcuts import get_object_or_404
98
from django.urls.exceptions import NoReverseMatch
109
from rest_framework import permissions
1110
from rest_framework.decorators import action
1211
from rest_framework.pagination import PageNumberPagination
13-
from rest_framework.permissions import AllowAny
1412
from rest_framework.response import Response
1513
from rest_framework.viewsets import GenericViewSet, mixins
1614

@@ -19,8 +17,7 @@
1917
from ansible_base.lib.utils.views.permissions import try_add_oauth2_scope_permission
2018
from ansible_base.resource_registry.models import Resource, ResourceType, service_id
2119
from ansible_base.resource_registry.registry import get_registry
22-
from ansible_base.resource_registry.serializers import ResourceListSerializer, ResourceSerializer, ResourceTypeSerializer, UserAuthenticationSerializer
23-
from ansible_base.resource_registry.utils.auth_code import get_user_auth_code
20+
from ansible_base.resource_registry.serializers import ResourceListSerializer, ResourceSerializer, ResourceTypeSerializer
2421
from ansible_base.rest_filters.rest_framework.field_lookup_backend import FieldLookupBackend
2522
from ansible_base.rest_filters.rest_framework.order_backend import OrderByBackend
2623
from ansible_base.rest_filters.rest_framework.type_filter_backend import TypeFilterBackend
@@ -193,43 +190,3 @@ def get(self, request, format=None):
193190
except NoReverseMatch:
194191
logger.info('DAB RBAC service-index views were not included, so not linked')
195192
return Response(data)
196-
197-
198-
class ValidateLocalUserView(AnsibleBaseDjangoAppApiView):
199-
"""
200-
Validate a user's username and password.
201-
"""
202-
203-
custom_action_label = "validate-local-user"
204-
205-
permission_classes = [AllowAny]
206-
207-
def post(self, request, **kwargs):
208-
serializer = UserAuthenticationSerializer(data=request.data)
209-
serializer.is_valid(raise_exception=True)
210-
211-
# Ensure the users exists before authenticating
212-
PREFIX = getattr(settings, "RENAMED_USERNAME_PREFIX", "")
213-
viable_usernames = [serializer.validated_data["username"], PREFIX + serializer.validated_data["username"]]
214-
if not get_user_model().objects.filter(username__in=viable_usernames).exists():
215-
logger.debug(f"User {serializer.validated_data['username']} does not exist, not validating authentication")
216-
return Response(status=401)
217-
218-
api_config = get_registry().api_config
219-
user = api_config.authenticate_local_user(serializer.validated_data["username"], serializer.validated_data["password"])
220-
221-
if not user:
222-
return Response(status=401)
223-
224-
try:
225-
auth_code = get_user_auth_code(user)
226-
except AttributeError:
227-
logger.exception(f"Cannot generate auth code for user {user}")
228-
auth_code = None
229-
230-
response = {
231-
"ansible_id": Resource.get_resource_for_object(user).ansible_id,
232-
"auth_code": auth_code,
233-
}
234-
235-
return Response(data=response)

docs/apps/oauth2_provider.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,6 @@ settings logic:
171171

172172
```python
173173
ANSIBLE_BASE_OAUTH2_PROVIDER_PERMISSIONS_CHECK_IGNORED_VIEWS = [
174-
'ansible_base.resource_registry.views.ValidateLocalUserView',
175174
'test_app.views.SomeOtherViewSet',
176175
]
177176
```

test_app/tests/oauth2_provider/checks/test_permissions_check.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
from ansible_base.authentication.views.ui_auth import UIAuth
1717
from ansible_base.lib.utils.views.urls import get_api_view_functions
1818
from ansible_base.oauth2_provider.checks.permisssions_check import oauth2_permission_scope_check, view_in_app_configs
19-
from ansible_base.resource_registry.views import ValidateLocalUserView
2019
from test_app import views
2120

2221
urlpatterns = [
@@ -32,8 +31,6 @@
3231
path('/docs/', SpectacularSwaggerView.as_view()),
3332
# Fully permissive APIView (via empty permission classes)
3433
path('/ui-auth/', UIAuth.as_view()),
35-
# Fully permissive APIView (via AllowAny)
36-
path('/validate-users-view/', ValidateLocalUserView.as_view()),
3734
# Non-ApiView view
3835
path('/non-api-view/', SAMLMetadataView.as_view()),
3936
]
@@ -109,11 +106,6 @@ def test_check_function(
109106
id="ansible_base.oauth2_provider.D03",
110107
obj=SpectacularSwaggerView,
111108
),
112-
Debug(
113-
"View object is fully permissive, OAuth2ScopePermission is not required",
114-
obj=ValidateLocalUserView,
115-
id="ansible_base.oauth2_provider.D04",
116-
),
117109
Debug(
118110
"View object is fully permissive, OAuth2ScopePermission is not required",
119111
obj=UIAuth,

test_app/tests/resource_registry/test_resources_api_rest_client.py

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
import uuid
22

3-
import jwt
43
import pytest
54
from requests.exceptions import HTTPError
65

76
from ansible_base.authentication.models import AuthenticatorUser
87
from ansible_base.rbac import permission_registry
98
from ansible_base.rbac.models import RoleDefinition
109
from ansible_base.resource_registry.models import Resource, service_id
11-
from ansible_base.resource_registry.resource_server import get_resource_server_config
1210
from ansible_base.resource_registry.rest_client import ResourceAPIClient, ResourceRequestBody
1311
from test_app.models import Inventory
1412

@@ -300,22 +298,6 @@ def test_additional_data_write(resource_client, partial):
300298
assert {perm.api_slug for perm in rd.permissions.all()} == {'aap.view_inventory'}
301299

302300

303-
@pytest.mark.django_db
304-
def test_validate_local_user(resource_client, admin_user, member_rd):
305-
resp = resource_client.validate_local_user(username=admin_user.username, password="password")
306-
307-
assert resp.status_code == 200
308-
json = resp.json()
309-
json["ansible_id"] == str(admin_user.resource.ansible_id)
310-
311-
config = get_resource_server_config()
312-
jwt_decoded = jwt.decode(json["auth_code"], config["SECRET_KEY"], config["JWT_ALGORITHM"])
313-
assert jwt_decoded['username'] == admin_user.username
314-
315-
resp = resource_client.validate_local_user(username=admin_user.username, password="fake password")
316-
assert resp.status_code == 401
317-
318-
319301
@pytest.mark.django_db
320302
def test_list_user_assignments(resource_client, org_admin_rd, user, organization):
321303
"""Test listing user role assignments."""

test_app/tests/resource_registry/test_views.py

Lines changed: 0 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,6 @@
33
from ansible_base.lib.utils.response import get_relative_url
44

55

6-
def test_validate_local_user(unauthenticated_api_client, admin_user, local_authenticator, settings_override_mutable, settings):
7-
url = get_relative_url('validate-local-account')
8-
data = {
9-
"username": admin_user.username,
10-
"password": "password",
11-
}
12-
response = unauthenticated_api_client.post(url, data=data)
13-
assert response.status_code == 200
14-
assert 'ansible_id' in response.data
15-
assert response.data['auth_code'] is not None
16-
17-
# If we're missing RESOURCE_SERVER, we can't generate an auth code, so return null instead.
18-
with settings_override_mutable('RESOURCE_SERVER'):
19-
delattr(settings, 'RESOURCE_SERVER')
20-
21-
response = unauthenticated_api_client.post(url, data=data)
22-
assert response.status_code == 200
23-
assert 'ansible_id' in response.data
24-
assert response.data['auth_code'] is None
25-
26-
# Should return 401 for non-existent user
27-
data = {
28-
"username": "fakeuser",
29-
"password": "doesnotexist",
30-
}
31-
response = unauthenticated_api_client.post(url, data=data)
32-
assert response.status_code == 401
33-
34-
356
def get_users_manifest(client, data=None, expect=200):
367
if data is None:
378
data = {}

0 commit comments

Comments
 (0)