|
@@ -1,5 +1,6 @@
|
|
|
from __future__ import annotations
|
|
|
|
|
|
+import hashlib
|
|
|
import secrets
|
|
|
from collections.abc import Collection
|
|
|
from datetime import timedelta
|
|
@@ -22,16 +23,82 @@ from sentry.types.region import find_all_region_names
|
|
|
from sentry.types.token import AuthTokenType
|
|
|
|
|
|
DEFAULT_EXPIRATION = timedelta(days=30)
|
|
|
+TOKEN_REDACTED = "***REDACTED***"
|
|
|
|
|
|
|
|
|
def default_expiration():
|
|
|
return timezone.now() + DEFAULT_EXPIRATION
|
|
|
|
|
|
|
|
|
-def generate_token():
|
|
|
+def generate_token(token_type: AuthTokenType | str | None = AuthTokenType.__empty__) -> str:
|
|
|
+ if token_type:
|
|
|
+ return f"{token_type}{secrets.token_hex(nbytes=32)}"
|
|
|
+
|
|
|
return secrets.token_hex(nbytes=32)
|
|
|
|
|
|
|
|
|
+class PlaintextSecretAlreadyRead(Exception):
|
|
|
+ """the secret you are trying to read is read-once and cannot be accessed directly again"""
|
|
|
+
|
|
|
+ pass
|
|
|
+
|
|
|
+
|
|
|
+class NotSupported(Exception):
|
|
|
+ """the method you called is not supported by this token type"""
|
|
|
+
|
|
|
+ pass
|
|
|
+
|
|
|
+
|
|
|
+class ApiTokenManager(ControlOutboxProducingManager):
|
|
|
+ def create(self, *args, **kwargs):
|
|
|
+ token_type: AuthTokenType | None = kwargs.get("token_type", None)
|
|
|
+
|
|
|
+ # Typically the .create() method is called with `refresh_token=None` as an
|
|
|
+ # argument when we specifically do not want a refresh_token.
|
|
|
+ #
|
|
|
+ # But if it is not None or not specified, we should generate a token since
|
|
|
+ # that is the expected behavior... the refresh_token field on ApiToken has
|
|
|
+ # a default of generate_token()
|
|
|
+ #
|
|
|
+ # TODO(mdtro): All of these if/else statements will be cleaned up at a later time
|
|
|
+ # to use a match statment on the AuthTokenType. Move each of the various token type
|
|
|
+ # create calls one at a time.
|
|
|
+ if "refresh_token" in kwargs:
|
|
|
+ plaintext_refresh_token = kwargs["refresh_token"]
|
|
|
+ else:
|
|
|
+ plaintext_refresh_token = generate_token()
|
|
|
+
|
|
|
+ if token_type == AuthTokenType.USER:
|
|
|
+ plaintext_token = generate_token(token_type=AuthTokenType.USER)
|
|
|
+ plaintext_refresh_token = None # user auth tokens do not have refresh tokens
|
|
|
+ else:
|
|
|
+ # to maintain compatibility with current
|
|
|
+ # code that currently calls create with token= specified
|
|
|
+ if "token" in kwargs:
|
|
|
+ plaintext_token = kwargs["token"]
|
|
|
+ else:
|
|
|
+ plaintext_token = generate_token()
|
|
|
+
|
|
|
+ if options.get("apitoken.save-hash-on-create"):
|
|
|
+ kwargs["hashed_token"] = hashlib.sha256(plaintext_token.encode()).hexdigest()
|
|
|
+
|
|
|
+ if plaintext_refresh_token:
|
|
|
+ kwargs["hashed_refresh_token"] = hashlib.sha256(
|
|
|
+ plaintext_refresh_token.encode()
|
|
|
+ ).hexdigest()
|
|
|
+
|
|
|
+ kwargs["token"] = plaintext_token
|
|
|
+ kwargs["refresh_token"] = plaintext_refresh_token
|
|
|
+
|
|
|
+ api_token = super().create(*args, **kwargs)
|
|
|
+
|
|
|
+ # Store the plaintext tokens for one-time retrieval
|
|
|
+ api_token._set_plaintext_token(token=plaintext_token)
|
|
|
+ api_token._set_plaintext_refresh_token(token=plaintext_refresh_token)
|
|
|
+
|
|
|
+ return api_token
|
|
|
+
|
|
|
+
|
|
|
@control_silo_only_model
|
|
|
class ApiToken(ReplicatedControlModel, HasApiScopes):
|
|
|
__relocation_scope__ = {RelocationScope.Global, RelocationScope.Config}
|
|
@@ -50,7 +117,7 @@ class ApiToken(ReplicatedControlModel, HasApiScopes):
|
|
|
expires_at = models.DateTimeField(null=True, default=default_expiration)
|
|
|
date_added = models.DateTimeField(default=timezone.now)
|
|
|
|
|
|
- objects: ClassVar[ControlOutboxProducingManager[ApiToken]] = ControlOutboxProducingManager(
|
|
|
+ objects: ClassVar[ControlOutboxProducingManager[ApiToken]] = ApiTokenManager(
|
|
|
cache_fields=("token",)
|
|
|
)
|
|
|
|
|
@@ -63,12 +130,117 @@ class ApiToken(ReplicatedControlModel, HasApiScopes):
|
|
|
def __str__(self):
|
|
|
return force_str(self.token)
|
|
|
|
|
|
+ def _set_plaintext_token(self, token: str) -> None:
|
|
|
+ """Set the plaintext token for one-time reading
|
|
|
+ This function should only be called from the model's
|
|
|
+ manager class.
|
|
|
+
|
|
|
+ :param token: A plaintext string of the token
|
|
|
+ :raises PlaintextSecretAlreadyRead: when the token has already been read once
|
|
|
+ """
|
|
|
+ existing_token: str | None = None
|
|
|
+ try:
|
|
|
+ existing_token = self.__plaintext_token
|
|
|
+ except AttributeError:
|
|
|
+ self.__plaintext_token: str = token
|
|
|
+
|
|
|
+ if existing_token == TOKEN_REDACTED:
|
|
|
+ raise PlaintextSecretAlreadyRead()
|
|
|
+
|
|
|
+ def _set_plaintext_refresh_token(self, token: str) -> None:
|
|
|
+ """Set the plaintext refresh token for one-time reading
|
|
|
+ This function should only be called from the model's
|
|
|
+ manager class.
|
|
|
+
|
|
|
+ :param token: A plaintext string of the refresh token
|
|
|
+ :raises PlaintextSecretAlreadyRead: if the token has already been read once
|
|
|
+ """
|
|
|
+ existing_refresh_token: str | None = None
|
|
|
+ try:
|
|
|
+ existing_refresh_token = self.__plaintext_refresh_token
|
|
|
+ except AttributeError:
|
|
|
+ self.__plaintext_refresh_token: str = token
|
|
|
+
|
|
|
+ if existing_refresh_token == TOKEN_REDACTED:
|
|
|
+ raise PlaintextSecretAlreadyRead()
|
|
|
+
|
|
|
+ @property
|
|
|
+ def plaintext_token(self) -> str:
|
|
|
+ """The plaintext value of the token
|
|
|
+ To be called immediately after creation of a new `ApiToken` to return the
|
|
|
+ plaintext token to the user. After reading the token, the plaintext token
|
|
|
+ string will be set to `TOKEN_REDACTED` to prevent future accidental leaking
|
|
|
+ of the token in logs, exceptions, etc.
|
|
|
+
|
|
|
+ :raises PlaintextSecretAlreadyRead: if the token has already been read once
|
|
|
+ :return: the plaintext value of the token
|
|
|
+ """
|
|
|
+ token = self.__plaintext_token
|
|
|
+ if token == TOKEN_REDACTED:
|
|
|
+ raise PlaintextSecretAlreadyRead()
|
|
|
+
|
|
|
+ self.__plaintext_token = TOKEN_REDACTED
|
|
|
+
|
|
|
+ return token
|
|
|
+
|
|
|
+ @property
|
|
|
+ def plaintext_refresh_token(self) -> str:
|
|
|
+ """The plaintext value of the refresh token
|
|
|
+ To be called immediately after creation of a new `ApiToken` to return the
|
|
|
+ plaintext token to the user. After reading the token, the plaintext token
|
|
|
+ string will be set to `TOKEN_REDACTED` to prevent future accidental leaking
|
|
|
+ of the token in logs, exceptions, etc.
|
|
|
+
|
|
|
+ :raises PlaintextSecretAlreadyRead: if the refresh token has already been read once
|
|
|
+ :raises NotSupported: if called on a User Auth Token
|
|
|
+ :return: the plaintext value of the refresh token
|
|
|
+ """
|
|
|
+ if not self.refresh_token and not self.hashed_refresh_token:
|
|
|
+ raise NotSupported("This API token type does not support refresh tokens")
|
|
|
+
|
|
|
+ token = self.__plaintext_refresh_token
|
|
|
+ if token == TOKEN_REDACTED:
|
|
|
+ raise PlaintextSecretAlreadyRead()
|
|
|
+
|
|
|
+ self.__plaintext_refresh_token = TOKEN_REDACTED
|
|
|
+
|
|
|
+ return token
|
|
|
+
|
|
|
def save(self, *args: Any, **kwargs: Any) -> None:
|
|
|
+ if options.get("apitoken.save-hash-on-create"):
|
|
|
+ self.hashed_token = hashlib.sha256(self.token.encode()).hexdigest()
|
|
|
+
|
|
|
+ if self.refresh_token:
|
|
|
+ self.hashed_refresh_token = hashlib.sha256(self.refresh_token.encode()).hexdigest()
|
|
|
+ else:
|
|
|
+ # The backup tests create a token with a refresh_token and then clear it out.
|
|
|
+ # So if the refresh_token is None, wipe out any hashed value that may exist too.
|
|
|
+ # https://github.com/getsentry/sentry/blob/1fc699564e79c62bff6cc3c168a49bfceadcac52/tests/sentry/backup/test_imports.py#L1306
|
|
|
+ self.hashed_refresh_token = None
|
|
|
+
|
|
|
if options.get("apitoken.auto-add-last-chars"):
|
|
|
token_last_characters = self.token[-4:]
|
|
|
self.token_last_characters = token_last_characters
|
|
|
|
|
|
- return super().save(**kwargs)
|
|
|
+ return super().save(*args, **kwargs)
|
|
|
+
|
|
|
+ def update(self, *args: Any, **kwargs: Any) -> int:
|
|
|
+ # if the token or refresh_token was updated, we need to
|
|
|
+ # re-calculate the hashed values
|
|
|
+ if options.get("apitoken.save-hash-on-create"):
|
|
|
+ if "token" in kwargs:
|
|
|
+ kwargs["hashed_token"] = hashlib.sha256(kwargs["token"].encode()).hexdigest()
|
|
|
+
|
|
|
+ if "refresh_token" in kwargs:
|
|
|
+ kwargs["hashed_refresh_token"] = hashlib.sha256(
|
|
|
+ kwargs["refresh_token"].encode()
|
|
|
+ ).hexdigest()
|
|
|
+
|
|
|
+ if options.get("apitoken.auto-add-last-chars"):
|
|
|
+ if "token" in kwargs:
|
|
|
+ kwargs["token_last_characters"] = kwargs["token"][-4:]
|
|
|
+
|
|
|
+ return super().update(*args, **kwargs)
|
|
|
|
|
|
def outbox_region_names(self) -> Collection[str]:
|
|
|
return list(find_all_region_names())
|
|
@@ -104,10 +276,16 @@ class ApiToken(ReplicatedControlModel, HasApiScopes):
|
|
|
return ()
|
|
|
|
|
|
def refresh(self, expires_at=None):
|
|
|
+ if self.token_type == AuthTokenType.USER:
|
|
|
+ raise NotSupported("User auth tokens do not support refreshing the token")
|
|
|
+
|
|
|
if expires_at is None:
|
|
|
expires_at = timezone.now() + DEFAULT_EXPIRATION
|
|
|
|
|
|
- self.update(token=generate_token(), refresh_token=generate_token(), expires_at=expires_at)
|
|
|
+ new_token = generate_token(token_type=self.token_type)
|
|
|
+ new_refresh_token = generate_token(token_type=self.token_type)
|
|
|
+
|
|
|
+ self.update(token=new_token, refresh_token=new_refresh_token, expires_at=expires_at)
|
|
|
|
|
|
def get_relocation_scope(self) -> RelocationScope:
|
|
|
if self.application_id is not None:
|
|
@@ -125,9 +303,9 @@ class ApiToken(ReplicatedControlModel, HasApiScopes):
|
|
|
)
|
|
|
existing = self.__class__.objects.filter(query).first()
|
|
|
if existing:
|
|
|
- self.token = generate_token()
|
|
|
+ self.token = generate_token(token_type=self.token_type)
|
|
|
if self.refresh_token is not None:
|
|
|
- self.refresh_token = generate_token()
|
|
|
+ self.refresh_token = generate_token(token_type=self.token_type)
|
|
|
if self.expires_at is not None:
|
|
|
self.expires_at = timezone.now() + DEFAULT_EXPIRATION
|
|
|
|