Skip to content
This repository was archived by the owner on Jun 13, 2025. It is now read-only.

Commit 9c72d13

Browse files
committed
API Improvements: Fix typings for various files pt1
1 parent 7749e0b commit 9c72d13

File tree

7 files changed

+87
-46
lines changed

7 files changed

+87
-46
lines changed

billing/views.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import logging
22
from datetime import datetime
3-
from typing import List
3+
from typing import Any, List
44

55
import stripe
66
from django.conf import settings
@@ -410,7 +410,7 @@ def checkout_session_completed(
410410

411411
self._log_updated([owner])
412412

413-
def post(self, request: HttpRequest, *args, **kwargs) -> Response:
413+
def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Response:
414414
if settings.STRIPE_ENDPOINT_SECRET is None:
415415
log.critical(
416416
"Stripe endpoint secret improperly configured -- webhooks will not be processed."

codecov_auth/authentication/repo_auth.py

Lines changed: 54 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import json
22
import logging
3-
from typing import List
3+
from typing import Any, Dict, List, Optional, Tuple
44
from uuid import UUID
55

66
from django.core.exceptions import ObjectDoesNotExist
@@ -10,6 +10,7 @@
1010
from jwt import PyJWTError
1111
from rest_framework import authentication, exceptions, serializers
1212
from rest_framework.exceptions import NotAuthenticated
13+
from rest_framework.response import Response
1314
from rest_framework.views import exception_handler
1415
from shared.django_apps.codecov_auth.models import Owner
1516

@@ -32,7 +33,9 @@
3233
log = 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

6265
class 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

8184
class 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

133136
class 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

152157
class 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

165172
class 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

184193
class 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

221232
class 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

238251
class 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.

graphql_api/types/commit/commit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ async def resolve_yaml(commit: Commit, info) -> dict:
8484

8585

8686
@commit_bindable.field("yamlState")
87-
async def resolve_yaml_state(commit: Commit, info) -> YamlStates:
87+
async def resolve_yaml_state(commit: Commit, info) -> Optional[YamlStates]:
8888
command = info.context["executor"].get_command("commit")
8989
final_yaml = await command.get_final_yaml(commit)
9090
return get_yaml_state(yaml=final_yaml)

graphql_api/types/owner/owner.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from datetime import datetime
22
from hashlib import sha1
3-
from typing import Any, Iterable, List, Optional
3+
from typing import Any, Coroutine, Iterable, List, Optional
44

55
import shared.rate_limits as rate_limits
66
import stripe
@@ -62,7 +62,7 @@ def resolve_repositories(
6262
ordering: Optional[RepositoryOrdering] = RepositoryOrdering.ID,
6363
ordering_direction: Optional[OrderingDirection] = OrderingDirection.ASC,
6464
**kwargs: Any,
65-
) -> Connection:
65+
) -> Coroutine[Any, Any, Connection]:
6666
current_owner = info.context["request"].current_owner
6767
okta_account_auths: list[int] = info.context["request"].session.get(
6868
OKTA_SIGNED_IN_ACCOUNTS_SESSION_KEY, []

services/yaml.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import enum
22
import logging
33
from functools import lru_cache
4-
from typing import Dict
4+
from typing import Dict, Optional
55

66
from asgiref.sync import async_to_sync
77
from shared.yaml import UserYaml, fetch_current_yaml_from_provider_via_reference
@@ -70,6 +70,6 @@ def final_commit_yaml(commit: Commit, owner: Owner | None) -> UserYaml:
7070
)
7171

7272

73-
def get_yaml_state(yaml: UserYaml) -> YamlStates:
73+
def get_yaml_state(yaml: UserYaml) -> Optional[YamlStates]:
7474
if yaml == get_config("site", default={}):
7575
return YamlStates.DEFAULT

upload/views/commits.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import logging
2+
from typing import Any, Callable, Dict
23

4+
from django.db.models import QuerySet
5+
from django.http import HttpRequest
6+
from rest_framework import serializers
37
from rest_framework.exceptions import NotAuthenticated
48
from rest_framework.generics import ListCreateAPIView
9+
from rest_framework.response import Response
510
from shared.metrics import inc_counter
611

712
from codecov_auth.authentication.repo_auth import (
@@ -13,7 +18,7 @@
1318
UploadTokenRequiredAuthenticationCheck,
1419
repo_auth_custom_exception_handler,
1520
)
16-
from core.models import Commit
21+
from core.models import Commit, Repository
1722
from upload.helpers import (
1823
generate_upload_prometheus_metrics_labels,
1924
validate_activated_repo,
@@ -26,7 +31,9 @@
2631
log = logging.getLogger(__name__)
2732

2833

29-
def create_commit(serializer, repository):
34+
def create_commit(
35+
serializer: serializers.ModelSerializer, repository: Repository
36+
) -> Commit:
3037
validate_activated_repo(repository)
3138
commit = serializer.save(repository=repository)
3239
return commit
@@ -44,25 +51,25 @@ class CommitViews(ListCreateAPIView, GetterMixin):
4451
TokenlessAuthentication,
4552
]
4653

47-
def get_exception_handler(self):
54+
def get_exception_handler(self) -> Callable[[Exception, Dict[str, Any]], Response]:
4855
return repo_auth_custom_exception_handler
4956

50-
def get_queryset(self):
57+
def get_queryset(self) -> QuerySet:
5158
repository = self.get_repo()
5259
return Commit.objects.filter(repository=repository)
5360

54-
def list(self, request, *args, **kwargs):
61+
def list(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Response:
5562
repository = self.get_repo()
5663
if repository.private and isinstance(
5764
self.request.auth, TokenlessAuthentication
5865
):
5966
raise NotAuthenticated()
6067
return super().list(request, *args, **kwargs)
6168

62-
def create(self, request, *args, **kwargs):
69+
def create(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Response:
6370
return super().create(request, *args, **kwargs)
6471

65-
def perform_create(self, serializer):
72+
def perform_create(self, serializer: CommitSerializer) -> Commit:
6673
inc_counter(
6774
API_UPLOAD_COUNTER,
6875
labels=generate_upload_prometheus_metrics_labels(

0 commit comments

Comments
 (0)