mirror of
https://github.com/ZTatman/myst.git
synced 2026-11-21 04:17:59 +00:00
fix(web): address CodeRabbit review comments
- Fix logout cookie not reaching browser (same pattern as callback) - Add cascade delete on Grant.user_id FK - Bump httpx to >=0.28.1 - Return plain dict from /dashboard instead of ORM session - Add decrypt functions and key validation to crypto.py - Constrain session token_hash to String(64), add expires_at index - Move Session import to TYPE_CHECKING in user.py - Add indexes on email and LinkedIdentity.user_id
This commit is contained in:
parent
d382ad348f
commit
b6486b7d5a
10 changed files with 78 additions and 17 deletions
26
agents.md
26
agents.md
|
|
@ -66,4 +66,28 @@ This file is the single source of truth for codebase obstacles, oddities, and th
|
|||
**Area:** CLI commands using process.exit()
|
||||
**Obstacle:** process.exit(0) stops execution immediately, never runs cleanup code.
|
||||
**Solution:** Use process.exitCode = 1 and return instead of process.exit().
|
||||
**Preference:** Set exitCode and return to allow cleanup.
|
||||
**Preference:** Set exitCode and return to allow cleanup.
|
||||
|
||||
### Logout cookie not reaching browser
|
||||
**Area:** web/app/routers/auth.py, web/app/auth/session.py
|
||||
**Obstacle:** `revoke_session` set cookies on the injected `Response` parameter, but the logout handler returned a new `RedirectResponse` — so `Set-Cookie` was discarded.
|
||||
**Solution:** Create `RedirectResponse` first, then pass it into `revoke_session`. Same pattern used in `callback_forgejo` for `create_session`.
|
||||
**Preference:** Pass the actual response object that will be returned.
|
||||
|
||||
### Dashboard leaking ORM session object
|
||||
**Area:** web/app/main.py
|
||||
**Obstacle:** `/dashboard` returned the full ORM `Session` object (`sess`), leaking `token_hash`, `revoked_at`, etc. to the client.
|
||||
**Solution:** Return a plain dict with only safe fields: `user_id`, `display_name`, `email`, `session_id`, `created_at`.
|
||||
**Preference:** Never return ORM objects directly in API responses.
|
||||
|
||||
### crypto.py decrypt functions kept proactively
|
||||
**Area:** web/app/auth/crypto.py
|
||||
**Obstacle:** CodeRabbit flagged missing decryption functions and key validation. Added `decrypt_oauth_token`/`decrypt_optional` + key format validation in `fernet_from_encryption_key`.
|
||||
**Solution:** Added the functions even though no consumer exists yet. They will be used for PAT decryption in share link flow.
|
||||
**Preference:** Keep dead code if it's small, symmetric (`encrypt`/`decrypt`), and has an obvious future consumer.
|
||||
|
||||
### User model Session import direct instead of TYPE_CHECKING
|
||||
**Area:** web/app/models/user.py
|
||||
**Obstacle:** `Session` was imported directly (`from .session import Session`) while `Grant` used `TYPE_CHECKING`. Inconsistent and risked circular imports.
|
||||
**Solution:** Moved `Session` import under `TYPE_CHECKING`, changed relationship to string ref `"Session"`.
|
||||
**Preference:** Always use `TYPE_CHECKING` for model references within models to avoid circular imports.
|
||||
|
|
@ -10,7 +10,14 @@ def fernet_from_encryption_key(key: SecretStr) -> Fernet | None:
|
|||
raw = key.get_secret_value().strip()
|
||||
if not raw:
|
||||
return None
|
||||
return Fernet(raw.encode())
|
||||
try:
|
||||
return Fernet(raw.encode())
|
||||
except Exception as e:
|
||||
msg = (
|
||||
f"Invalid OAUTH_TOKEN_ENCRYPTION_KEY: {e}. "
|
||||
"Generate a valid key with cryptography.fernet.Fernet.generate_key().decode()"
|
||||
)
|
||||
raise ValueError(msg) from e
|
||||
|
||||
|
||||
def encrypt_oauth_token(fernet: Fernet, raw_token: str) -> str:
|
||||
|
|
@ -27,3 +34,19 @@ def encrypt_optional(fernet: Fernet | None, raw_token: str | None) -> str | None
|
|||
)
|
||||
raise ValueError(msg)
|
||||
return encrypt_oauth_token(fernet, raw_token)
|
||||
|
||||
|
||||
def decrypt_oauth_token(fernet: Fernet, encrypted_token: str) -> str:
|
||||
return fernet.decrypt(encrypted_token.encode()).decode()
|
||||
|
||||
|
||||
def decrypt_optional(fernet: Fernet | None, encrypted_token: str | None) -> str | None:
|
||||
if encrypted_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 decrypt_oauth_token(fernet, encrypted_token)
|
||||
|
|
|
|||
|
|
@ -17,7 +17,9 @@ SESSION_COOKIE = "myst_session"
|
|||
SESSION_DURATION_DAYS = 7
|
||||
|
||||
|
||||
async def create_session(db: AsyncSession, response: Response, user_id: uuid.UUID) -> None:
|
||||
async def create_session(
|
||||
db: AsyncSession, response: Response, user_id: uuid.UUID, secure: bool = True
|
||||
) -> None:
|
||||
raw_token = secrets.token_hex(32)
|
||||
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
|
||||
expires_at = datetime.now(UTC) + timedelta(days=SESSION_DURATION_DAYS)
|
||||
|
|
@ -33,6 +35,7 @@ async def create_session(db: AsyncSession, response: Response, user_id: uuid.UUI
|
|||
value=raw_token,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=secure,
|
||||
max_age=60 * 60 * 24 * SESSION_DURATION_DAYS,
|
||||
path="/",
|
||||
)
|
||||
|
|
|
|||
|
|
@ -45,7 +45,9 @@ async def root():
|
|||
@app.get("/dashboard")
|
||||
async def dashboard(sess: UserBrowserSession = Depends(get_current_session)):
|
||||
return {
|
||||
"session": sess,
|
||||
"user_id": str(sess.user.id),
|
||||
"display_name": sess.user.display_name,
|
||||
"email": sess.user.email,
|
||||
"session_id": str(sess.id),
|
||||
"created_at": sess.created_at.isoformat(),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,9 @@ class Grant(Base):
|
|||
server_default=func.gen_random_uuid(),
|
||||
)
|
||||
token_hash: Mapped[str] = mapped_column(String, unique=True, nullable=False, index=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id"), nullable=False)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.now())
|
||||
expires_at: Mapped[datetime] = mapped_column(nullable=False)
|
||||
revoked_at: Mapped[datetime | None] = mapped_column(nullable=True)
|
||||
|
|
|
|||
|
|
@ -22,9 +22,9 @@ class Session(Base):
|
|||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
token_hash: Mapped[str] = mapped_column(String, unique=True, nullable=False, index=True)
|
||||
token_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.now())
|
||||
expires_at: Mapped[datetime] = mapped_column(nullable=False)
|
||||
expires_at: Mapped[datetime] = mapped_column(nullable=False, index=True)
|
||||
last_seen_at: Mapped[datetime | None] = mapped_column(nullable=True)
|
||||
revoked_at: Mapped[datetime | None] = mapped_column(nullable=True)
|
||||
|
||||
|
|
|
|||
|
|
@ -8,10 +8,10 @@ from sqlalchemy import ForeignKey, String, Text, UniqueConstraint, Uuid, func
|
|||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database import Base
|
||||
from .session import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .grant import Grant
|
||||
from .session import Session
|
||||
|
||||
|
||||
class User(Base):
|
||||
|
|
@ -21,7 +21,7 @@ class User(Base):
|
|||
Uuid, primary_key=True, server_default=func.gen_random_uuid()
|
||||
)
|
||||
display_name: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
email: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
email: Mapped[str | None] = mapped_column(String, nullable=True, index=True)
|
||||
pat_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.now())
|
||||
|
||||
|
|
@ -30,7 +30,7 @@ class User(Base):
|
|||
cascade="all, delete-orphan",
|
||||
)
|
||||
sessions: Mapped[list[Session]] = relationship(
|
||||
Session,
|
||||
"Session",
|
||||
back_populates="user",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
|
@ -47,7 +47,7 @@ class LinkedIdentity(Base):
|
|||
Uuid, primary_key=True, server_default=func.gen_random_uuid()
|
||||
)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
provider: Mapped[str] = mapped_column(String, nullable=False)
|
||||
provider_user_id: Mapped[str] = mapped_column(String, nullable=False)
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ def _set_oauth_state_cookie(response: Response, state: str) -> None:
|
|||
value=state,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
path="/",
|
||||
max_age=600,
|
||||
)
|
||||
|
||||
|
|
@ -176,6 +177,12 @@ async def callback_forgejo(
|
|||
_require_forgejo_oauth_config(settings)
|
||||
_verify_oauth_state(state, oauth_state)
|
||||
|
||||
if not code:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Forgejo did not return an authorization code. The user may have denied consent.",
|
||||
)
|
||||
|
||||
redirect = RedirectResponse("/dashboard", status_code=status.HTTP_302_FOUND)
|
||||
redirect.delete_cookie("oauth_state")
|
||||
|
||||
|
|
@ -207,15 +214,15 @@ async def callback_forgejo(
|
|||
refresh_token_raw=refresh_plain,
|
||||
)
|
||||
|
||||
await create_session(db, redirect, user.id)
|
||||
await create_session(db, redirect, user.id, secure=request.url.scheme == "https")
|
||||
return redirect
|
||||
|
||||
|
||||
@router.get("/logout")
|
||||
async def logout(
|
||||
response: Response,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
myst_session: str | None = Cookie(default=None),
|
||||
) -> RedirectResponse:
|
||||
await revoke_session(db, response, myst_session)
|
||||
return RedirectResponse("/", status_code=status.HTTP_302_FOUND)
|
||||
redirect = RedirectResponse("/", status_code=status.HTTP_302_FOUND)
|
||||
await revoke_session(db, redirect, myst_session)
|
||||
return redirect
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ dependencies = [
|
|||
"asyncpg>=0.31.0",
|
||||
"cryptography>=46.0.0",
|
||||
"fastapi>=0.136.0",
|
||||
"httpx>=0.28.0",
|
||||
"httpx>=0.28.1",
|
||||
"pydantic-settings>=2.13.1",
|
||||
"pydantic[email]>=2.13.2",
|
||||
"sqlalchemy[asyncio]>=2.0.49",
|
||||
|
|
|
|||
2
web/uv.lock
generated
2
web/uv.lock
generated
|
|
@ -360,7 +360,7 @@ requires-dist = [
|
|||
{ name = "asyncpg", specifier = ">=0.31.0" },
|
||||
{ name = "cryptography", specifier = ">=46.0.0" },
|
||||
{ name = "fastapi", specifier = ">=0.136.0" },
|
||||
{ name = "httpx", specifier = ">=0.28.0" },
|
||||
{ name = "httpx", specifier = ">=0.28.1" },
|
||||
{ name = "pydantic", extras = ["email"], specifier = ">=2.13.2" },
|
||||
{ name = "pydantic-settings", specifier = ">=2.13.1" },
|
||||
{ name = "sqlalchemy", extras = ["asyncio"], specifier = ">=2.0.49" },
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue