myst/web/app/auth/crypto.py
ZTatman d382ad348f feat(web): OAuth CSRF protection, refactor, and cleanup
- Add CSRF state parameter to Forgejo OAuth flow
- Refactor callback route into focused helper functions
- Remove unused FORGEJO_PAT config from web service
- Add pat_encrypted field to User model
- Fix circular imports with TYPE_CHECKING guards
- Fix session cookie not reaching browser (secure=True + response object)
- Add ruff linting/formatting to web project
- Add env_file to docker-compose for OAuth credentials
- Document OAuth setup steps in README
2026-05-15 13:40:50 -04:00

29 lines
889 B
Python

"""Fernet (AES) encryption for OAuth tokens at rest."""
from __future__ import annotations
from cryptography.fernet import Fernet
from pydantic import SecretStr
def fernet_from_encryption_key(key: SecretStr) -> Fernet | None:
raw = key.get_secret_value().strip()
if not raw:
return None
return Fernet(raw.encode())
def encrypt_oauth_token(fernet: Fernet, raw_token: str) -> str:
return fernet.encrypt(raw_token.encode()).decode()
def encrypt_optional(fernet: Fernet | None, raw_token: str | None) -> str | None:
if raw_token is None:
return None
if fernet is None:
msg = (
"OAuth token encryption is not configured: set OAUTH_TOKEN_ENCRYPTION_KEY "
"to the output of cryptography.fernet.Fernet.generate_key().decode()"
)
raise ValueError(msg)
return encrypt_oauth_token(fernet, raw_token)