Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support API key as password for excel feeds #35698

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions corehq/apps/domain/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def real_decorator(view):
def wrapper(request, *args, **kwargs):
username, password = get_username_and_password_from_request(request)
if username and password:
request.check_for_password_as_api_key = True
request.check_for_api_key_as_password = True
user = authenticate(username=username, password=password, request=request)
if user is not None and user.is_active:
request.user = user
Expand Down Expand Up @@ -212,7 +212,7 @@ def _inner(request, *args, **kwargs):
class ApiKeyFallbackBackend(object):

def authenticate(self, request, username, password):
if not getattr(request, 'check_for_password_as_api_key', False):
if not getattr(request, 'check_for_api_key_as_password', False):
return None

try:
Expand Down
20 changes: 17 additions & 3 deletions corehq/apps/domain/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,9 @@ def login_or_oauth2_ex(allow_cc_users=False, allow_sessions=True, require_domain
)


def get_multi_auth_decorator(default, allow_formplayer=False, oauth_scopes=None, allow_creds_in_data=True):
def get_multi_auth_decorator(
default, allow_formplayer=False, oauth_scopes=None, allow_creds_in_data=True, allow_api_key_as_password=False
):
"""
:param allow_formplayer: If True this will allow one additional auth mechanism which is used
by Formplayer:
Expand All @@ -373,6 +375,7 @@ def get_multi_auth_decorator(default, allow_formplayer=False, oauth_scopes=None,
formplayer can not use the session cookie to auth. To allow formplayer access to the
endpoints we validate each formplayer request using a shared key. See the auth
function for more details.
:param allow_api_key_as_password: If True, allows API Key to be used in BASIC auth
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the thing that you were referring to with this comment?

my main concern is that we will start to use this on other endpoints, when in reality we should reserve this for exceptional use cases where it is our best, and possibly only option

If yes, maybe add that concern to this docstring to warn future devs not to use it in exceptional circumstances? Possibly even rename the parameter to something like allow_api_key_as_password_EXCEPTIONAL_USE_ONLY to force anyone who uses it to type that out and as a flag to reviewers?

"""
oauth_scopes = oauth_scopes or ['access_apis']

Expand All @@ -391,6 +394,7 @@ def _inner(request, *args, **kwargs):
allow_cc_users=True,
oauth_scopes=oauth_scopes,
allow_creds_in_data=allow_creds_in_data,
allow_api_key_as_password=allow_api_key_as_password,
)[authtype]
return function_wrapper(fn)(request, *args, **kwargs)
return _inner
Expand All @@ -410,12 +414,13 @@ def wrapped_view(*args, **kwargs):
return wraps(view_func)(wrapped_view)


def api_auth(*, allow_creds_in_data=True, oauth_scopes=None):
def api_auth(*, allow_creds_in_data=True, oauth_scopes=None, allow_api_key_as_password=False):
"""Allow any auth type basic, digest, session, apikey, or oauth"""
return get_multi_auth_decorator(
default=DIGEST,
oauth_scopes=oauth_scopes,
allow_creds_in_data=allow_creds_in_data,
allow_api_key_as_password=allow_api_key_as_password,
)


Expand All @@ -435,6 +440,7 @@ def get_auth_decorator_map(
allow_sessions=True,
oauth_scopes=None,
allow_creds_in_data=True,
allow_api_key_as_password=False,
):
# get a mapped set of decorators for different auth types with the specified parameters
oauth_scopes = oauth_scopes or ['access_apis']
Expand All @@ -443,9 +449,17 @@ def get_auth_decorator_map(
'require_domain': require_domain,
'allow_sessions': allow_sessions,
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re:

the only place we set require_domain to False is here, which we can safely say does not use the login_or_basic_or_api_key_ex function since allow_api_key_as_password defaults to False.

Would it make sense to assert that here?

Suggested change
assert not allow_api_key_as_password or require_domain, \
"It is unexpected to allow API key as password and not require domain"

I assume it's not easy or very meaningful to add tests to verify that our code never does that, but if it's possible to verify with a test then that might make sense too.

if allow_api_key_as_password:
copied_kwargs = decorator_function_kwargs.copy()
copied_kwargs.pop('require_domain')
basic_auth_fn = login_or_basic_or_api_key_ex(**copied_kwargs)
else:
basic_auth_fn = login_or_basic_ex(**decorator_function_kwargs)
gherceg marked this conversation as resolved.
Show resolved Hide resolved

return {
DIGEST: login_or_digest_ex(**decorator_function_kwargs),
BASIC: login_or_basic_ex(**decorator_function_kwargs),
BASIC: basic_auth_fn,
API_KEY: login_or_api_key_ex(allow_creds_in_data=allow_creds_in_data,
**decorator_function_kwargs),
OAUTH2: login_or_oauth2_ex(oauth_scopes=oauth_scopes, **decorator_function_kwargs),
Expand Down
17 changes: 15 additions & 2 deletions corehq/apps/domain/tests/test_api_key_auth.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import base64

from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponse
from django.test import RequestFactory, TestCase
Expand Down Expand Up @@ -53,9 +55,9 @@ def setUpClass(cls):
cls.user = WebUser.create(cls.domain, USERNAME, 'password', None, None)
cls.api_key = HQApiKey.objects.create(user=cls.user.get_django_user()).plaintext_key

def call_api(self, request, allow_creds_in_data):
def call_api(self, request, allow_creds_in_data=False, allow_api_key_as_password=False):

@api_auth(allow_creds_in_data=allow_creds_in_data)
@api_auth(allow_creds_in_data=allow_creds_in_data, allow_api_key_as_password=allow_api_key_as_password)
def api_view(request, domain):
return HttpResponse()

Expand All @@ -80,3 +82,14 @@ def test_credentials_in_data(self):

res = self.call_api(request, allow_creds_in_data=False)
self.assertEqual(res.status_code, 401)

def test_credentials_with_basic_auth(self):
request = self.factory.get('/myapi/')
encoded_creds = base64.b64encode(f"{USERNAME}:{self.api_key}".encode('utf-8')).decode('utf-8')
request.META['HTTP_AUTHORIZATION'] = f"basic {encoded_creds}"

res = self.call_api(request, allow_api_key_as_password=False)
self.assertEqual(res.status_code, 401)

res = self.call_api(request, allow_api_key_as_password=True)
self.assertEqual(res.status_code, 200)
2 changes: 1 addition & 1 deletion corehq/apps/domain/tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def _create_request(cls, can_use_api_key=True, for_domain='test-domain', ip='127
request.META['HTTP_X_FORWARDED_FOR'] = ip

if can_use_api_key:
request.check_for_password_as_api_key = True
request.check_for_api_key_as_password = True

return request

Expand Down
2 changes: 1 addition & 1 deletion corehq/apps/export/views/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,7 @@ def can_download_daily_saved_export(export, domain, couch_user):

@location_safe
@csrf_exempt
@api_auth()
@api_auth(allow_api_key_as_password=True)
@require_GET
def download_daily_saved_export(req, domain, export_instance_id):
with CriticalSection(['export-last-accessed-{}'.format(export_instance_id)]):
Expand Down
Loading