Skip to content

Commit

Permalink
wip: barely works!
Browse files Browse the repository at this point in the history
  • Loading branch information
mdtro committed Aug 22, 2024
1 parent d7c1185 commit 8e8b54b
Show file tree
Hide file tree
Showing 6 changed files with 591 additions and 408 deletions.
52 changes: 41 additions & 11 deletions src/sentry/api/authentication.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import logging
import hashlib
import random
from collections.abc import Callable, Iterable
Expand All @@ -22,7 +23,11 @@
from sentry import options
from sentry.auth.services.auth import AuthenticatedToken
from sentry.auth.system import SystemToken, is_internal_ip
from sentry.hybridcloud.models import ApiKeyReplica, ApiTokenReplica, OrgAuthTokenReplica
from sentry.hybridcloud.models import (
ApiKeyReplica,
ApiTokenReplica,
OrgAuthTokenReplica,
)
from sentry.hybridcloud.rpc.service import compare_signature
from sentry.models.apiapplication import ApiApplication
from sentry.models.apikey import ApiKey
Expand All @@ -42,7 +47,12 @@
from sentry.users.services.user.service import user_service
from sentry.utils.linksign import process_signature
from sentry.utils.sdk import Scope
from sentry.utils.security.orgauthtoken_token import SENTRY_ORG_AUTH_TOKEN_PREFIX, hash_token
from sentry.utils.security.orgauthtoken_token import (
SENTRY_ORG_AUTH_TOKEN_PREFIX,
hash_token,
)

logger = logging.getLogger(__name__)


class AuthenticationSiloLimit(SiloLimit):
Expand Down Expand Up @@ -224,7 +234,9 @@ def authenticate_credentials(
raise AuthenticationFailed("Unknown relay")

try:
data = relay.public_key_object.unpack(request.body, relay_sig, max_age=60 * 5)
data = relay.public_key_object.unpack(
request.body, relay_sig, max_age=60 * 5
)
request.relay = relay
request.relay_request_data = data
except UnpackError:
Expand Down Expand Up @@ -330,7 +342,9 @@ class TokenStrLookupRequired(Exception):
class UserAuthTokenAuthentication(StandardAuthentication):
token_name = b"bearer"

def _find_or_update_token_by_hash(self, token_str: str) -> ApiToken | ApiTokenReplica:
def _find_or_update_token_by_hash(
self, token_str: str
) -> ApiToken | ApiTokenReplica:
"""
Find token by hash or update token's hash value if only found via plaintext.
Expand Down Expand Up @@ -377,9 +391,9 @@ def _find_or_update_token_by_hash(self, token_str: str) -> ApiToken | ApiTokenRe
except (ApiToken.DoesNotExist, TokenStrLookupRequired):
try:
# If we can't find it by hash, use the plaintext string
api_token = ApiToken.objects.select_related("user", "application").get(
token=token_str
)
api_token = ApiToken.objects.select_related(
"user", "application"
).get(token=token_str)
except ApiToken.DoesNotExist:
# If the token does not exist by plaintext either, it is not a valid token
raise AuthenticationFailed("Invalid token")
Expand All @@ -392,6 +406,8 @@ def _find_or_update_token_by_hash(self, token_str: str) -> ApiToken | ApiTokenRe
return api_token

def accepts_auth(self, auth: list[bytes]) -> bool:
logger.error(f"AUTH {auth}")

if not super().accepts_auth(auth):
return False

Expand All @@ -401,13 +417,20 @@ def accepts_auth(self, auth: list[bytes]) -> bool:
return True

token_str = force_str(auth[1])
return not token_str.startswith(SENTRY_ORG_AUTH_TOKEN_PREFIX)
user_auth_result = not token_str.startswith(SENTRY_ORG_AUTH_TOKEN_PREFIX)
startswith = token_str.startswith(SENTRY_ORG_AUTH_TOKEN_PREFIX)
logger.error(
f"USE USER AUTH? {user_auth_result} | prefix {SENTRY_ORG_AUTH_TOKEN_PREFIX} | token_str {token_str} | startswith {startswith}"
)

return user_auth_result

def authenticate_token(self, request: Request, token_str: str) -> tuple[Any, Any]:
logger.error(f"USER AUTH REQUEST HEADERS: {request.headers}")
user: AnonymousUser | User | RpcUser | None = AnonymousUser()

token: SystemToken | ApiTokenReplica | ApiToken | None = SystemToken.from_request(
request, token_str
token: SystemToken | ApiTokenReplica | ApiToken | None = (
SystemToken.from_request(request, token_str)
)

application_is_inactive = False
Expand Down Expand Up @@ -452,13 +475,16 @@ class OrgAuthTokenAuthentication(StandardAuthentication):
token_name = b"bearer"

def accepts_auth(self, auth: list[bytes]) -> bool:
logger.error(f"ORG AUTH: {auth}")
if not super().accepts_auth(auth) or len(auth) != 2:
return False

token_str = force_str(auth[1])
return token_str.startswith(SENTRY_ORG_AUTH_TOKEN_PREFIX)

def authenticate_token(self, request: Request, token_str: str) -> tuple[Any, Any]:
logger.error(f"REQUEST HEADERS: {request.headers}")

token_hashed = hash_token(token_str)

token: OrgAuthTokenReplica | OrgAuthToken
Expand All @@ -479,7 +505,11 @@ def authenticate_token(self, request: Request, token_str: str) -> tuple[Any, Any
raise AuthenticationFailed("Invalid org token")

return self.transform_auth(
None, token, "api_token", api_token_type=self.token_name, api_token_is_org_token=True
None,
token,
"api_token",
api_token_type=self.token_name,
api_token_is_org_token=True,
)


Expand Down
Loading

0 comments on commit 8e8b54b

Please sign in to comment.