11import json
22import logging
3- from typing import List
3+ from typing import Any , Dict , List , Optional , Tuple
44from uuid import UUID
55
66from django .core .exceptions import ObjectDoesNotExist
1010from jwt import PyJWTError
1111from rest_framework import authentication , exceptions , serializers
1212from rest_framework .exceptions import NotAuthenticated
13+ from rest_framework .response import Response
1314from rest_framework .views import exception_handler
1415from shared .django_apps .codecov_auth .models import Owner
1516
3233log = logging .getLogger (__name__ )
3334
3435
35- def repo_auth_custom_exception_handler (exc , context ):
36+ def repo_auth_custom_exception_handler (
37+ exc : Exception , context : Dict [str , Any ]
38+ ) -> Response :
3639 """
3740 User arrives here if they have correctly supplied a Token or the Tokenless Headers,
3841 but their Token has not matched with any of our Authentication methods. The goal is to
@@ -60,17 +63,17 @@ def repo_auth_custom_exception_handler(exc, context):
6063
6164
6265class LegacyTokenRepositoryAuth (RepositoryAuthInterface ):
63- def __init__ (self , repository , auth_data ) :
66+ def __init__ (self , repository : Repository , auth_data : Dict [ str , Any ]) -> None :
6467 self ._auth_data = auth_data
6568 self ._repository = repository
6669
67- def get_scopes (self ):
70+ def get_scopes (self ) -> List [ TokenTypeChoices ] :
6871 return [TokenTypeChoices .UPLOAD ]
6972
70- def get_repositories (self ):
73+ def get_repositories (self ) -> List [ Repository ] :
7174 return [self ._repository ]
7275
73- def allows_repo (self , repository ) :
76+ def allows_repo (self , repository : Repository ) -> bool :
7477 return repository in self .get_repositories ()
7578
7679
@@ -79,17 +82,17 @@ class OIDCTokenRepositoryAuth(LegacyTokenRepositoryAuth):
7982
8083
8184class TableTokenRepositoryAuth (RepositoryAuthInterface ):
82- def __init__ (self , repository , token ) :
85+ def __init__ (self , repository : Repository , token : RepositoryToken ) -> None :
8386 self ._token = token
8487 self ._repository = repository
8588
86- def get_scopes (self ):
89+ def get_scopes (self ) -> List [ str ] :
8790 return [self ._token .token_type ]
8891
89- def get_repositories (self ):
92+ def get_repositories (self ) -> List [ Repository ] :
9093 return [self ._repository ]
9194
92- def allows_repo (self , repository ) :
95+ def allows_repo (self , repository : Repository ) -> bool :
9396 return repository in self .get_repositories ()
9497
9598
@@ -98,10 +101,10 @@ def __init__(self, token: OrganizationLevelToken) -> None:
98101 self ._token = token
99102 self ._org = token .owner
100103
101- def get_scopes (self ):
104+ def get_scopes (self ) -> List [ str ] :
102105 return [self ._token .token_type ]
103106
104- def allows_repo (self , repository ) :
107+ def allows_repo (self , repository : Repository ) -> bool :
105108 return repository .author .ownerid == self ._org .ownerid
106109
107110 def get_repositories_queryset (self ) -> QuerySet :
@@ -120,18 +123,20 @@ class TokenlessAuth(RepositoryAuthInterface):
120123 def __init__ (self , repository : Repository ) -> None :
121124 self ._repository = repository
122125
123- def get_scopes (self ):
126+ def get_scopes (self ) -> List [ TokenTypeChoices ] :
124127 return [TokenTypeChoices .UPLOAD ]
125128
126- def allows_repo (self , repository ) :
129+ def allows_repo (self , repository : Repository ) -> bool :
127130 return repository in self .get_repositories ()
128131
129132 def get_repositories (self ) -> List [Repository ]:
130133 return [self ._repository ]
131134
132135
133136class RepositoryLegacyQueryTokenAuthentication (authentication .BaseAuthentication ):
134- def authenticate (self , request ):
137+ def authenticate (
138+ self , request : HttpRequest
139+ ) -> Optional [Tuple [RepositoryAsUser , LegacyTokenRepositoryAuth ]]:
135140 token = request .GET .get ("token" )
136141 if not token :
137142 return None
@@ -150,22 +155,26 @@ def authenticate(self, request):
150155
151156
152157class RepositoryLegacyTokenAuthentication (authentication .TokenAuthentication ):
153- def authenticate_credentials (self , token ):
158+ def authenticate_credentials (
159+ self , token : str
160+ ) -> Optional [Tuple [RepositoryAsUser , LegacyTokenRepositoryAuth ]]:
154161 try :
155- token = UUID (token )
156- repository = Repository .objects .get (upload_token = token )
162+ token_uuid = UUID (token )
163+ repository = Repository .objects .get (upload_token = token_uuid )
157164 except (ValueError , TypeError , Repository .DoesNotExist ):
158165 return None # continue to next auth class
159166 return (
160167 RepositoryAsUser (repository ),
161- LegacyTokenRepositoryAuth (repository , {"token" : token }),
168+ LegacyTokenRepositoryAuth (repository , {"token" : token_uuid }),
162169 )
163170
164171
165172class RepositoryTokenAuthentication (authentication .TokenAuthentication ):
166173 keyword = "Repotoken"
167174
168- def authenticate_credentials (self , key ):
175+ def authenticate_credentials (
176+ self , key : str
177+ ) -> Optional [Tuple [RepositoryAsUser , TableTokenRepositoryAuth ]]:
169178 try :
170179 token = RepositoryToken .objects .select_related ("repository" ).get (key = key )
171180 except RepositoryToken .DoesNotExist :
@@ -182,7 +191,9 @@ def authenticate_credentials(self, key):
182191
183192
184193class GlobalTokenAuthentication (authentication .TokenAuthentication ):
185- def authenticate (self , request ):
194+ def authenticate (
195+ self , request : HttpRequest
196+ ) -> Optional [Tuple [RepositoryAsUser , LegacyTokenRepositoryAuth ]]:
186197 global_tokens = get_global_tokens ()
187198 token = self .get_token (request )
188199 using_global_token = token in global_tokens
@@ -219,7 +230,9 @@ def get_token(self, request: HttpRequest) -> str | None:
219230
220231
221232class OrgLevelTokenAuthentication (authentication .TokenAuthentication ):
222- def authenticate_credentials (self , key ):
233+ def authenticate_credentials (
234+ self , key : str
235+ ) -> Optional [Tuple [Owner , OrgLevelTokenRepositoryAuth ]]:
223236 if is_uuid (key ): # else, continue to next auth class
224237 # Actual verification for org level tokens
225238 token = OrganizationLevelToken .objects .filter (token = key ).first ()
@@ -236,7 +249,9 @@ def authenticate_credentials(self, key):
236249
237250
238251class GitHubOIDCTokenAuthentication (authentication .TokenAuthentication ):
239- def authenticate_credentials (self , token ):
252+ def authenticate_credentials (
253+ self , token : str
254+ ) -> Optional [Tuple [RepositoryAsUser , OIDCTokenRepositoryAuth ]]:
240255 if not token or is_uuid (token ):
241256 return None # continue to next auth class
242257
@@ -283,7 +298,12 @@ def _get_info_from_request_path(
283298
284299 return repo , commitid
285300
286- def get_branch (self , request , repoid = None , commitid = None ):
301+ def get_branch (
302+ self ,
303+ request : HttpRequest ,
304+ repoid : Optional [int ] = None ,
305+ commitid : Optional [str ] = None ,
306+ ) -> Optional [str ]:
287307 if repoid and commitid :
288308 commit = Commit .objects .filter (
289309 repository_id = repoid , commitid = commitid
@@ -299,7 +319,9 @@ def get_branch(self, request, repoid=None, commitid=None):
299319 else :
300320 return body .get ("branch" )
301321
302- def authenticate (self , request ):
322+ def authenticate (
323+ self , request : HttpRequest
324+ ) -> Tuple [RepositoryAsUser , TokenlessAuth ]:
303325 repository , commitid = self ._get_info_from_request_path (request )
304326
305327 if repository is None or repository .private :
@@ -341,7 +363,12 @@ def _get_info_from_request_path(
341363 # Validate provider
342364 raise exceptions .AuthenticationFailed (self .auth_failed_message )
343365
344- def get_branch (self , request , repoid = None , commitid = None ):
366+ def get_branch (
367+ self ,
368+ request : HttpRequest ,
369+ repoid : Optional [int ] = None ,
370+ commitid : Optional [str ] = None ,
371+ ) -> str :
345372 body = json .loads (str (request .body , "utf8" ))
346373
347374 # If commit is not created yet (ie first upload for this commit), we just validate branch format.
@@ -419,7 +446,7 @@ class UploadTokenRequiredGetFromBodyAuthenticationCheck(
419446 then use the same authenticate() as parent class.
420447 """
421448
422- def _get_git (self , validated_data ) :
449+ def _get_git (self , validated_data : Dict [ str , str ]) -> Optional [ str ] :
423450 """
424451 BA sends this in as git_service, TA sends this in as service.
425452 Use this function so this Check class can be used by both views.
0 commit comments