From bea26c70ec822cb5d0fbfbdf33dcf2486f70fbba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20Paul=20Ton=C4=8Dik?= Date: Wed, 24 Jun 2026 22:31:44 +0200 Subject: [PATCH] Added prototype for fingerprinted token generation --- service/src/main/inse/.env | 3 + service/src/main/inse/auth/model.py | 4 +- service/src/main/inse/auth/service.py | 429 +++++++++++++++++++++++++- service/src/main/inse/config.py | 3 + 4 files changed, 432 insertions(+), 7 deletions(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index e886c6a1..492450e9 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -14,3 +14,6 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=paraphrase-multilingual-mpnet-base-v2 + +TOKEN_ISSUER_ID=inse +TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7 \ No newline at end of file diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index 3ffe0cb2..ed954b00 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -139,13 +139,13 @@ class AccessToken(Token): nullable=False, description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.", ) - role: UserRole = Field( + effective_role: UserRole = Field( default=UserRole.USER, index=True, nullable=False, description="The specific role this access token grants within its organization.", ) - organization_id: uuid.UUID = Field( + effective_organization_id: uuid.UUID = Field( nullable=False, description="The unique identifier of the organization associated with this access token.", ) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index e54f8550..64e46d94 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -1,18 +1,437 @@ +import datetime +import hashlib +import secrets +from typing import Annotated, Any, Literal, Optional, Dict import uuid -from inse.auth.model import IdToken, RefreshToken +from fastapi import Depends, HTTPException, Request, Response, status +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +import jwt + +from inse.auth.model import AccessToken, RefreshToken, UserRole +from inse.config import get_settings + + +ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days +REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes +ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes + +REAL_ACCOUNT_ID_KEY = "real_account_id" +EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id" +EFFECTIVE_ROLE_KEY = "effective_role" +EPOCH_KEY = "epoch" +ORGANIZATION_ID_KEY = "organization_id" +USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash" + +settings = get_settings() + +security_scheme = HTTPBearer() def request_otk(email: str, password: str): pass -def login(emailCode: str): - pass +def login(response: Response, emailCode: str) -> str: + # TODO: validate emailCode and retrieve the associated account IDF + real_account_id = uuid.uuid4() + # TODO: Replace with actual account ID retrieval logic + + epoch = _get_account_epoch(real_account_id) + return _build_id_token(response, real_account_id, epoch) -def get_access_token(account_id: uuid.UUID, id_token: IdToken): - pass +def _get_current_user_token_payload( + request: Request, + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], +) -> AccessToken: + """Extracts and verifies the current user's token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies. + + Args: + request (Request): The FastAPI request object containing the cookies. + credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials extracted from the request. + + Returns: + Dict[str, Any]: The verified token payload. + """ + + token = credentials.credentials + + access_token_payload = _verify_fp_token(request, "__Secure-Fgp-Act", token) + # If reaches here, the access token is valid and the fingerprint matches + + return AccessToken( + real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]), + effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), + expires_at=datetime.datetime.fromtimestamp( + access_token_payload["exp"], tz=datetime.timezone.utc + ), + epoch=access_token_payload[EPOCH_KEY], + effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]), + effective_organization_id=uuid.UUID(access_token_payload[ORGANIZATION_ID_KEY]), + ) + + +CurrentUserTokenPayloadDep = Depends(_get_current_user_token_payload) + + +def _get_account_epoch(account_id: uuid.UUID) -> int: + """Retrieves the current epoch for the given account ID. The epoch is used to manage token versioning and invalidation. + + Args: + account_id (uuid.UUID): The unique identifier of the account for which to retrieve the epoch. + + Returns: + int: The current epoch for the given account ID. + """ + + return 0 # TODO: Replace with actual logic to retrieve the epoch for the account + + +def _get_account_role(account_id: uuid.UUID) -> UserRole: + """Retrieves the role for the given account ID. + + Args: + account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role. + + Returns: + UserRole: The role associated with the given account ID. + """ + return ( + UserRole.USER + ) # TODO: Replace with actual logic to retrieve the role for the account + + +def _get_account_organization(account_id: uuid.UUID) -> uuid.UUID: + """Retrieves the organization ID for the given account ID. + + Args: + account_id (uuid.UUID): The unique identifier of the account for which to retrieve the organization ID. + + Returns: + uuid.UUID: The organization ID associated with the given account ID. + """ + return ( + uuid.uuid4() + ) # TODO: Replace with actual logic to retrieve the organization ID for the account + + +def _is_valid_impersonation( + real_account_id: uuid.UUID, effective_account_id: uuid.UUID +) -> bool: + """Checks if the real account is allowed to impersonate the effective account. + + Args: + real_account_id (uuid.UUID): The unique identifier of the real account. + effective_account_id (uuid.UUID): The unique identifier of the effective account. + + Returns: + bool: True if impersonation is allowed, False otherwise. + """ + return True # TODO: Replace with actual logic to check if impersonation is allowed + + +def get_access_token( + request: Request, + response: Response, + id_token: str, + real_account_id: uuid.UUID, + effective_account_id: Optional[uuid.UUID] = None, +) -> Dict[str, Any]: + """Generates access and refresh tokens for the specified real and effective account IDs, verifying the provided ID token and ensuring that the fingerprint matches the one stored in the cookies. + + Args: + request (Request): The FastAPI request object containing the cookies. + response (Response): The FastAPI response object to which the cookies will be added. + id_token (str): The ID token to verify. + real_account_id (uuid.UUID): The unique identifier of the real account associated with this token. + effective_account_id (Optional[uuid.UUID], optional): The unique identifier of the effective account associated with this token. If not provided, it defaults to the real account ID. + + Raises: + HTTPException: If the ID token is invalid, expired, or does not match the real account ID. + HTTPException: If impersonation is not allowed. + + Returns: + Dict[str, Any]: A dictionary containing the generated access and refresh tokens. + """ + + id_token_payload = _verify_fp_token( + request=request, + cookie_key="__Secure-Fgp-ID", + token=id_token, + ) + # If reaches here, the id_token is valid and the fingerprint matches + + if str(real_account_id) != id_token_payload[REAL_ACCOUNT_ID_KEY]: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Real account ID does not match ID token", + ) + + if effective_account_id: + if not _is_valid_impersonation(real_account_id, effective_account_id): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Impersonation not allowed", + ) + else: + # No impersonation, set effective_account_id to real_account_id + effective_account_id = real_account_id + + role = _get_account_role(effective_account_id) + epoch = _get_account_epoch(real_account_id) + organization_id = _get_account_organization(effective_account_id) + + user_fingerprint_hash = _set_act_fp_cookie(response=response) + + access_token_payload = { + REAL_ACCOUNT_ID_KEY: str(real_account_id), + EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id), + EPOCH_KEY: epoch, + EFFECTIVE_ROLE_KEY: role.value, + ORGANIZATION_ID_KEY: str(organization_id), + USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, + } + + return _build_action_tokens( + payload=access_token_payload, + ) + + +def _set_id_fp_cookie(response: Response) -> str: + """Sets a secure fingerprint cookie for ID tokens and returns the hashed value of the fingerprint. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + + Returns: + str: The hashed value of the fingerprint. + """ + return _set_fingerprint_cookie( + response, "__Secure-Fgp-ID", max_age=ID_TOKEN_EXPIRATION_MINUTES * 60 + ) + + +def _set_act_fp_cookie(response: Response) -> str: + """Sets a secure fingerprint cookie for access tokens and returns the hashed value of the fingerprint. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + + Returns: + str: The hashed value of the fingerprint. + """ + return _set_fingerprint_cookie( + response, "__Secure-Fgp-Act" + ) # Setting no max age to make it a session cookie, which will be deleted when the browser is closed. + + +def _set_fingerprint_cookie( + response: Response, + key: Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"], + max_age: Optional[int] = None, +) -> str: + """Sets a secure fingerprint cookie and returns the hashed value of the fingerprint. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + key (Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"]): The name of the cookie to set. + max_age (Optional[int], optional): The maximum age of the cookie in seconds. Defaults to None. + + Returns: + str: The hashed value of the fingerprint. + """ + user_fingerprint = secrets.token_hex(50) + secure = False if settings.environment == "dev" else True + response.set_cookie( + key=key, + value=user_fingerprint, + httponly=True, + secure=secure, + samesite="strict", + max_age=max_age, + ) + return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() + + +def _refresh_access_token(request: Request, refresh_token: str) -> str: + """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. + + Args: + request (Request): The FastAPI request object containing the cookies. + refresh_token (str): The refresh token to verify. + current_user_epoch (int): The epoch value for the tokens. + + Returns: + str: The refreshed access token. + """ + refresh_payload = _verify_fp_token( + request=request, + cookie_key="__Secure-Fgp-Act", + token=refresh_token, + ) + + access_payload = { + REAL_ACCOUNT_ID_KEY: refresh_payload[REAL_ACCOUNT_ID_KEY], + EFFECTIVE_ACCOUNT_ID_KEY: refresh_payload[EFFECTIVE_ACCOUNT_ID_KEY], + EPOCH_KEY: refresh_payload[EPOCH_KEY], + EFFECTIVE_ROLE_KEY: refresh_payload[EFFECTIVE_ROLE_KEY], + ORGANIZATION_ID_KEY: refresh_payload[ORGANIZATION_ID_KEY], + USER_FINGERPRINT_HASH_KEY: refresh_payload[USER_FINGERPRINT_HASH_KEY], + } + return _build_token( + payload=access_payload, expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES + ) + + +def _build_id_token(response: Response, real_account_id: uuid.UUID, epoch: int) -> str: + """Builds an ID token for the specified real account ID and sets the appropriate fingerprint cookie. + + Args: + response (Response): The FastAPI response object to which the cookie will be added. + real_account_id (uuid.UUID): The UUID of the real account. + epoch (int): The epoch value for the tokens. + + Returns: + str: The built ID token. + """ + + user_fingerprint_hash = _set_id_fp_cookie(response) + payload = { + REAL_ACCOUNT_ID_KEY: str(real_account_id), + EPOCH_KEY: epoch, + USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash, + } + return _build_token(payload=payload, expiration_min=ID_TOKEN_EXPIRATION_MINUTES) + + +def _build_action_tokens( + payload: Dict[str, Any], +) -> Dict[str, str]: + """Builds both access and refresh tokens for the specified account IDs and sets the appropriate fingerprint cookies. + + Args: + response (Response): The FastAPI response object to which the cookies will be added. + real_account_id (uuid.UUID): The UUID of the real account. + effective_account_id (uuid.UUID): The UUID of the effective account. + epoch (int): The epoch value for the tokens. + + Returns: + Dict[str, str]: A dictionary containing the built access and refresh tokens. + """ + + return { + "access_token": _build_token( + payload=payload, expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES + ), + "refresh_token": _build_token( + payload=payload, expiration_min=REFRESH_TOKEN_EXPIRATION_MINUTES + ), + } + + +def _build_token(payload: Dict[str, Any], expiration_min: int) -> str: + """Builds a JWT token with the given payload and expiration time. + + Args: + payload (Dict[str, Any]): The payload to encode in the JWT. + expiration_min (int): The expiration time in minutes. + + Returns: + str: The encoded JWT token. + """ + now = datetime.datetime.now(datetime.timezone.utc) + expiration_date = now + datetime.timedelta(minutes=expiration_min) + payload.update( + { + "exp": expiration_date, + "iss": settings.token_issuer_id, + "iat": now, + "nbf": now, + } + ) + if not settings.token_hmac_key: + raise ValueError("Token HMAC key is not set in the configuration.") + token = jwt.encode(payload, settings.token_hmac_key, algorithm="HS256") + return token + + +def _verify_fp_token(request: Request, cookie_key: str, token: str) -> Dict[str, Any]: + """Verifies the provided token against the fingerprint stored in the specified cookie and returns the decoded payload if valid. + + Args: + request (Request): The FastAPI request object containing the cookies. + cookie_key (str): The name of the cookie that contains the fingerprint. + token (str): The JWT token to verify. + + Raises: + ValueError: If the token HMAC key is not set in the configuration. + HTTPException: If the fingerprint cookie is missing or does not match the token's fingerprint. + HTTPException: If the token has expired. + HTTPException: If the token is invalid. + HTTPException: If the token's epoch does not match the current user epoch. + + Returns: + Dict[str, Any]: The decoded payload of the JWT token if verification is successful. + """ + if not settings.token_hmac_key: + raise ValueError("Token HMAC key is not set in the configuration.") + + secure_fgp = request.cookies.get(cookie_key) + if not secure_fgp: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Fingerprint cookie missing", + ) + + fingerprint_bytes = secure_fgp.encode("utf-8") + expected_fingerprint_hash = hashlib.sha256(fingerprint_bytes).hexdigest() + + try: + payload = jwt.decode( + token, + settings.token_hmac_key, + algorithms=["HS256"], + issuer=settings.token_issuer_id, + ) + + token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY) + if ( + not token_fingerprint_hash + or token_fingerprint_hash != expected_fingerprint_hash + ): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid context fingerprint", + ) + + real_account_id = payload.get(REAL_ACCOUNT_ID_KEY) + if not real_account_id: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token missing real account ID", + ) + + real_account_epoch = _get_account_epoch(uuid.UUID(real_account_id)) + token_epoch = payload.get(EPOCH_KEY) + if token_epoch is None or token_epoch != real_account_epoch: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token epoch mismatch", + ) + + return payload + + except jwt.ExpiredSignatureError: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token has expired", + ) + except jwt.InvalidTokenError: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid token", + ) def refresh_access_token(refresh_token: RefreshToken): diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 9aa5fb17..8e7639ff 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -64,6 +64,9 @@ class Settings(BaseSettings): environment: Literal["dev", "prod"] = "dev" + token_issuer_id: Optional[str] = None + token_hmac_key: Optional[str] = None + settings = Settings()