diff --git a/service/Dockerfile b/service/Dockerfile index d984e6b2..cfbb7094 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -14,7 +14,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c "httpx~=0.27.0" \ "python-multipart~=0.0.19"\ "openai~=2.41.0" \ - "sqlmodel~=0.0.33" + "sqlmodel~=0.0.33" \ + "argon2-cffi~=25.1.0" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py index ed954b00..31b6825f 100644 --- a/service/src/main/inse/auth/model.py +++ b/service/src/main/inse/auth/model.py @@ -1,7 +1,8 @@ +import uuid from datetime import datetime from enum import StrEnum from typing import List -import uuid + from pydantic import BaseModel from sqlmodel import Field, Relationship, SQLModel @@ -22,7 +23,7 @@ class Durable(SQLModel): ) -class Organization(SQLModel, table=True): +class Organization(Durable, table=True): id: uuid.UUID | None = Field( default_factory=uuid.uuid4, primary_key=True, diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 5f9eaf6e..e8ec22ec 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -8,8 +8,8 @@ from sqlmodel import Session from inse.tags import Tags import inse.auth.service as auth_service -from inse.auth.model import IdToken, RefreshToken -from inse.database import SessionDep +from inse.auth.model import IdToken, RefreshToken, AccessToken +from inse.database import SessionDep, get_session logger = logging.getLogger(__name__) @@ -93,23 +93,34 @@ async def refresh_access_token( responses={status.HTTP_200_OK: {"description": "Logout successful."}}, ) async def logout( - session: SessionDep, + session: Annotated[Session, Depends(get_session)], + access_token: AccessToken = auth_service.CurrentUserTokenPayloadDep, ): - auth_service.logout() + return auth_service.logout(session, access_token) @router.post( "/change-password", summary="Change Password", - description="Change the user's password and optionally invalidate existing tokens.", + description="Change the user's password and invalidate existing tokens.", operation_id="changePassword", responses={status.HTTP_200_OK: {"description": "Password changed successfully."}}, ) async def change_password( - session: SessionDep, - new_password: Annotated[str, Body(description="New password", min_length=8)], - invalidate_tokens: Annotated[ - bool, Body(description="Whether to invalidate existing tokens") - ] = True, + session: Annotated[Session, Depends(get_session)], + current_password: Annotated[ + str, + Body(description="Current password"), + ], + new_password: Annotated[ + str, + Body(description="New password", min_length=8), + ], + access_token: AccessToken = auth_service.CurrentUserTokenPayloadDep, ): - auth_service.change_password(new_password, invalidate_tokens) + return auth_service.change_password( + session, + access_token, + current_password, + new_password, + ) diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 64e46d94..6cbaf648 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -1,16 +1,18 @@ import datetime import hashlib import secrets -from typing import Annotated, Any, Literal, Optional, Dict import uuid +from typing import Annotated, Any, Dict, Literal, Optional +import jwt +from argon2 import PasswordHasher +from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError 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.auth.model import AccessToken, Account, RefreshToken, UserRole from inse.config import get_settings - +from inse.database import get_session +from sqlmodel import Session ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes @@ -27,6 +29,19 @@ settings = get_settings() security_scheme = HTTPBearer() +_password_hasher = PasswordHasher() + + +def _hash_password(password: str) -> str: + return _password_hasher.hash(password) + + +def _verify_password(password: str, password_hash: str) -> bool: + try: + return _password_hasher.verify(password_hash, password) + except (VerifyMismatchError, VerificationError, InvalidHashError): + return False + def request_otk(email: str, password: str): pass @@ -42,6 +57,7 @@ def login(response: Response, emailCode: str) -> str: def _get_current_user_token_payload( + session: Annotated[Session, Depends(get_session)], request: Request, credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], ) -> AccessToken: @@ -57,7 +73,12 @@ def _get_current_user_token_payload( token = credentials.credentials - access_token_payload = _verify_fp_token(request, "__Secure-Fgp-Act", token) + access_token_payload = _verify_fp_token( + request=request, + cookie_key="__Secure-Fgp-Act", + token=token, + session=session, + ) # If reaches here, the access token is valid and the fingerprint matches return AccessToken( @@ -75,17 +96,19 @@ def _get_current_user_token_payload( 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. +def _get_account_epoch( + account_id: uuid.UUID, + session: Session, +) -> int: + account = session.get(Account, account_id) - Args: - account_id (uuid.UUID): The unique identifier of the account for which to retrieve the epoch. + if account is None or account.deleted: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is not active.", + ) - Returns: - int: The current epoch for the given account ID. - """ - - return 0 # TODO: Replace with actual logic to retrieve the epoch for the account + return account.epoch def _get_account_role(account_id: uuid.UUID) -> UserRole: @@ -136,6 +159,7 @@ def get_access_token( response: Response, id_token: str, real_account_id: uuid.UUID, + session: Session, 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. @@ -159,6 +183,7 @@ def get_access_token( request=request, cookie_key="__Secure-Fgp-ID", token=id_token, + session=session, ) # If reaches here, the id_token is valid and the fingerprint matches @@ -179,7 +204,7 @@ def get_access_token( effective_account_id = real_account_id role = _get_account_role(effective_account_id) - epoch = _get_account_epoch(real_account_id) + epoch = _get_account_epoch(effective_account_id, session=session) organization_id = _get_account_organization(effective_account_id) user_fingerprint_hash = _set_act_fp_cookie(response=response) @@ -254,7 +279,11 @@ def _set_fingerprint_cookie( return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest() -def _refresh_access_token(request: Request, refresh_token: str) -> str: +def _refresh_access_token( + request: Request, + refresh_token: str, + session: Session, +) -> str: """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies. Args: @@ -269,6 +298,7 @@ def _refresh_access_token(request: Request, refresh_token: str) -> str: request=request, cookie_key="__Secure-Fgp-Act", token=refresh_token, + session=session, ) access_payload = { @@ -356,7 +386,12 @@ def _build_token(payload: Dict[str, Any], expiration_min: int) -> str: return token -def _verify_fp_token(request: Request, cookie_key: str, token: str) -> Dict[str, Any]: +def _verify_fp_token( + request: Request, + cookie_key: str, + token: str, + session: Session, +) -> Dict[str, Any]: """Verifies the provided token against the fingerprint stored in the specified cookie and returns the decoded payload if valid. Args: @@ -412,9 +447,19 @@ def _verify_fp_token(request: Request, cookie_key: str, token: str) -> Dict[str, detail="Token missing real account ID", ) - real_account_epoch = _get_account_epoch(uuid.UUID(real_account_id)) + epoch_account_id = uuid.UUID(real_account_id) + + effective_account_id = payload.get(EFFECTIVE_ACCOUNT_ID_KEY) + if effective_account_id: + epoch_account_id = uuid.UUID(effective_account_id) + + current_account_epoch = _get_account_epoch( + epoch_account_id, + session=session, + ) + token_epoch = payload.get(EPOCH_KEY) - if token_epoch is None or token_epoch != real_account_epoch: + if token_epoch is None or token_epoch != current_account_epoch: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token epoch mismatch", @@ -438,9 +483,47 @@ def refresh_access_token(refresh_token: RefreshToken): pass -def logout(): - pass +def _get_active_account(session: Session, account_id: uuid.UUID) -> Account: + account = session.get(Account, account_id) + + if account is None or account.deleted: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Account is not active.", + ) + + return account -def change_password(new_password: str, invalidate_tokens: bool = True): - pass +def logout(session: Session, access_token: AccessToken) -> dict: + account = _get_active_account(session, access_token.effective_account_id) + + account.epoch += 1 + + session.add(account) + session.commit() + + return {"status": "ok"} + + +def change_password( + session: Session, + access_token: AccessToken, + current_password: str, + new_password: str, +) -> dict: + account = _get_active_account(session, access_token.effective_account_id) + + if not _verify_password(current_password, account.password_hash): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Current password is incorrect.", + ) + + account.password_hash = _hash_password(new_password) + account.epoch += 1 + + session.add(account) + session.commit() + + return {"status": "ok"}