mirror of
https://github.com/ZTatman/myst.git
synced 2026-11-21 04:17:59 +00:00
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
This commit is contained in:
parent
5fec547983
commit
d382ad348f
14 changed files with 257 additions and 150 deletions
24
README.md
24
README.md
|
|
@ -92,6 +92,30 @@ FORGEJO_PAT=forgejo_pat_xxxxxxxxxxxx
|
|||
|
||||
When using the provided Docker Compose example, DATABASE_URL is injected automatically. For other deployment approaches (e.g., bare metal, Kubernetes), you must supply DATABASE_URL yourself.
|
||||
|
||||
### 4. Register an OAuth application in Forgejo
|
||||
|
||||
The web service authenticates users via Forgejo OAuth. You need to register Myst as an OAuth consumer:
|
||||
|
||||
1. In Forgejo, go to **Settings** → **Applications** → **Create OAuth2 Application**
|
||||
2. Set the redirect URI to `https://your-myst-domain.com/auth/callback/forgejo` (or `http://localhost:8000/auth/callback/forgejo` for local dev)
|
||||
3. Copy the **Client ID** and **Client Secret** Forgejo gives you
|
||||
4. Generate a Fernet encryption key for OAuth token storage:
|
||||
|
||||
```bash
|
||||
python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
||||
```
|
||||
|
||||
5. Add these to your `.env`:
|
||||
|
||||
```env
|
||||
FORGEJO_OAUTH_CLIENT_ID=your_client_id
|
||||
FORGEJO_OAUTH_CLIENT_SECRET=your_client_secret
|
||||
OAUTH_TOKEN_ENCRYPTION_KEY=your_fernet_key_from_step_4
|
||||
MYST_PUBLIC_BASE_URL=https://your-myst-domain.com # omit trailing slash; omit for local dev
|
||||
```
|
||||
|
||||
`MYST_PUBLIC_BASE_URL` is used as the OAuth redirect URI base. In local development, the redirect URI is inferred from the request (Default: `http://localhost:8000/auth/callback/forgejo`). In production, set this to your public Myst domain.
|
||||
|
||||
## Phase 1 Progress
|
||||
|
||||
- [x] Project renamed from Embargo to Myst
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ services:
|
|||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "8000:8000"
|
||||
env_file: ./web/.env
|
||||
environment:
|
||||
- DATABASE_URL=postgresql+asyncpg://myst:myst@db:5432/myst_db
|
||||
depends_on:
|
||||
|
|
|
|||
|
|
@ -107,11 +107,13 @@ function showCommandHelp(
|
|||
lines.push("");
|
||||
}
|
||||
|
||||
const hasSubcommands = cmdConf.subcommands && Object.keys(cmdConf.subcommands).length > 0;
|
||||
const hasSubcommands =
|
||||
cmdConf.subcommands && Object.keys(cmdConf.subcommands).length > 0;
|
||||
const usageCmd = subcommand ? `${command} ${subcommand}` : command;
|
||||
const usageLine = hasSubcommands && !subcommand
|
||||
? `myst ${command} <subcommand> [options]`
|
||||
: `myst ${usageCmd} [options]`;
|
||||
const usageLine =
|
||||
hasSubcommands && !subcommand
|
||||
? `myst ${command} <subcommand> [options]`
|
||||
: `myst ${usageCmd} [options]`;
|
||||
lines.push(c.bold("Usage:"));
|
||||
lines.push(`${INDENT}${usageLine}`);
|
||||
lines.push("");
|
||||
|
|
|
|||
|
|
@ -13,12 +13,12 @@ def fernet_from_encryption_key(key: SecretStr) -> Fernet | None:
|
|||
return Fernet(raw.encode())
|
||||
|
||||
|
||||
def encrypt_oauth_token(fernet: Fernet, plain: str) -> str:
|
||||
return fernet.encrypt(plain.encode()).decode()
|
||||
def encrypt_oauth_token(fernet: Fernet, raw_token: str) -> str:
|
||||
return fernet.encrypt(raw_token.encode()).decode()
|
||||
|
||||
|
||||
def encrypt_optional(fernet: Fernet | None, plain: str | None) -> str | None:
|
||||
if plain is None:
|
||||
def encrypt_optional(fernet: Fernet | None, raw_token: str | None) -> str | None:
|
||||
if raw_token is None:
|
||||
return None
|
||||
if fernet is None:
|
||||
msg = (
|
||||
|
|
@ -26,4 +26,4 @@ def encrypt_optional(fernet: Fernet | None, plain: str | None) -> str | None:
|
|||
"to the output of cryptography.fernet.Fernet.generate_key().decode()"
|
||||
)
|
||||
raise ValueError(msg)
|
||||
return encrypt_oauth_token(fernet, plain)
|
||||
return encrypt_oauth_token(fernet, raw_token)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ from datetime import datetime
|
|||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.auth.crypto import encrypt_optional, fernet_from_encryption_key
|
||||
from app.config import Settings
|
||||
|
|
@ -18,27 +19,34 @@ async def find_or_create_user(
|
|||
provider_user_id: str,
|
||||
provider_username: str,
|
||||
email: str | None,
|
||||
access_token_plain: str | None,
|
||||
access_token_raw: str | None,
|
||||
access_token_expires_at: datetime | None,
|
||||
refresh_token_plain: str | None,
|
||||
refresh_token_raw: str | None,
|
||||
) -> User:
|
||||
"""Find or create a user based on the given provider and identity details."""
|
||||
|
||||
# Create a Fernet instance for encrypting tokens if a key is available
|
||||
fernet = fernet_from_encryption_key(settings.oauth_token_encryption_key)
|
||||
|
||||
# Query the database for an existing identity
|
||||
result = await db.execute(
|
||||
select(LinkedIdentity).where(
|
||||
select(LinkedIdentity)
|
||||
.options(selectinload(LinkedIdentity.user))
|
||||
.where(
|
||||
LinkedIdentity.provider == provider,
|
||||
LinkedIdentity.provider_user_id == provider_user_id,
|
||||
)
|
||||
)
|
||||
identity = result.scalar_one_or_none()
|
||||
|
||||
# Update the identity and user if identity exists
|
||||
if identity:
|
||||
identity.provider_username = provider_username
|
||||
if access_token_plain is not None:
|
||||
identity.access_token_encrypted = encrypt_optional(fernet, access_token_plain)
|
||||
if access_token_raw is not None:
|
||||
identity.access_token_encrypted = encrypt_optional(fernet, access_token_raw)
|
||||
identity.access_token_expires_at = access_token_expires_at
|
||||
if refresh_token_plain is not None:
|
||||
identity.refresh_token_encrypted = encrypt_optional(fernet, refresh_token_plain)
|
||||
if refresh_token_raw is not None:
|
||||
identity.refresh_token_encrypted = encrypt_optional(fernet, refresh_token_raw)
|
||||
user = identity.user
|
||||
if email:
|
||||
user.email = email
|
||||
|
|
@ -57,9 +65,9 @@ async def find_or_create_user(
|
|||
provider=provider,
|
||||
provider_user_id=provider_user_id,
|
||||
provider_username=provider_username,
|
||||
access_token_encrypted=encrypt_optional(fernet, access_token_plain),
|
||||
access_token_encrypted=encrypt_optional(fernet, access_token_raw),
|
||||
access_token_expires_at=access_token_expires_at,
|
||||
refresh_token_encrypted=encrypt_optional(fernet, refresh_token_plain),
|
||||
refresh_token_encrypted=encrypt_optional(fernet, refresh_token_raw),
|
||||
)
|
||||
db.add(linked)
|
||||
await db.commit()
|
||||
|
|
|
|||
|
|
@ -32,7 +32,6 @@ async def create_session(db: AsyncSession, response: Response, user_id: uuid.UUI
|
|||
key=SESSION_COOKIE,
|
||||
value=raw_token,
|
||||
httponly=True,
|
||||
secure=True,
|
||||
samesite="lax",
|
||||
max_age=60 * 60 * 24 * SESSION_DURATION_DAYS,
|
||||
path="/",
|
||||
|
|
@ -72,15 +71,12 @@ async def get_current_session(
|
|||
return sess
|
||||
|
||||
|
||||
async def revoke_session(
|
||||
db: AsyncSession, response: Response, myst_session: str | None
|
||||
) -> None:
|
||||
async def revoke_session(db: AsyncSession, response: Response, myst_session: str | None) -> None:
|
||||
response.delete_cookie(
|
||||
key=SESSION_COOKIE,
|
||||
path="/",
|
||||
samesite="lax",
|
||||
httponly=True,
|
||||
secure=True,
|
||||
)
|
||||
if not myst_session:
|
||||
return
|
||||
|
|
|
|||
|
|
@ -13,12 +13,11 @@ class Settings(BaseSettings):
|
|||
app_name: str = "Myst"
|
||||
database_url: str = "postgresql+asyncpg://myst:myst@db:5432/myst_db" # Default for Docker Compose; override with DATABASE_URL env var in production
|
||||
forgejo_base_url: str = ""
|
||||
forgejo_pat: SecretStr = SecretStr("")
|
||||
forgejo_oauth_client_id: str = ""
|
||||
forgejo_oauth_client_secret: SecretStr = SecretStr("")
|
||||
# Public Myst base URL for OAuth redirect_uri (no trailing slash). If empty, Request.base_url is used.
|
||||
myst_public_base_url: str = ""
|
||||
# URL-safe base64 Fernet key (see `cryptography.fernet.Fernet.generate_key()`). Required to persist OAuth tokens.
|
||||
# URL-safe base64 Fernet key (see `cryptography.fernet.Fernet.generate_key()`). Required to persist OAuth tokens and user PATs.
|
||||
oauth_token_encryption_key: SecretStr = SecretStr("")
|
||||
|
||||
model_config = SettingsConfigDict(env_file=str(env_file))
|
||||
|
|
|
|||
|
|
@ -3,14 +3,13 @@ from contextlib import asynccontextmanager
|
|||
from fastapi import Depends, FastAPI
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
import app.models # noqa: F401 - register ORM tables on metadata
|
||||
from app.auth.session import get_current_session
|
||||
from app.config import get_settings
|
||||
from app.database import Base
|
||||
from app.models.session import Session as UserBrowserSession
|
||||
from app.routers import auth, links
|
||||
|
||||
import app.models # noqa: F401 - register ORM tables on metadata
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
|
|
@ -46,6 +45,7 @@ async def root():
|
|||
@app.get("/dashboard")
|
||||
async def dashboard(sess: UserBrowserSession = Depends(get_current_session)):
|
||||
return {
|
||||
"session": sess,
|
||||
"display_name": sess.user.display_name,
|
||||
"email": sess.user.email,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,13 +2,16 @@ from __future__ import annotations
|
|||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Literal, get_args
|
||||
from typing import TYPE_CHECKING, Literal, get_args
|
||||
|
||||
from sqlalchemy import Enum, ForeignKey, String, Uuid, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .user import User
|
||||
|
||||
GrantType = Literal["public", "private"]
|
||||
|
||||
|
||||
|
|
@ -21,9 +24,7 @@ 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"), 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)
|
||||
|
|
@ -37,4 +38,4 @@ class Grant(Base):
|
|||
)
|
||||
recipient_email: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
|
||||
user: Mapped["User"] = relationship("User", back_populates="grants")
|
||||
user: Mapped[User] = relationship("User", back_populates="grants")
|
||||
|
|
|
|||
|
|
@ -2,12 +2,15 @@ from __future__ import annotations
|
|||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import ForeignKey, String, Uuid, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database import Base
|
||||
from app.models.user import User
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class Session(Base):
|
||||
|
|
@ -25,4 +28,4 @@ class Session(Base):
|
|||
last_seen_at: Mapped[datetime | None] = mapped_column(nullable=True)
|
||||
revoked_at: Mapped[datetime | None] = mapped_column(nullable=True)
|
||||
|
||||
user: Mapped[User] = relationship(back_populates="sessions")
|
||||
user: Mapped[User] = relationship("User", back_populates="sessions")
|
||||
|
|
|
|||
|
|
@ -2,11 +2,16 @@ from __future__ import annotations
|
|||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
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
|
||||
|
||||
|
||||
class User(Base):
|
||||
|
|
@ -17,18 +22,19 @@ class User(Base):
|
|||
)
|
||||
display_name: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
email: Mapped[str | None] = mapped_column(String, nullable=True)
|
||||
pat_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.now())
|
||||
|
||||
identities: Mapped[list[LinkedIdentity]] = relationship(
|
||||
back_populates="user",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
sessions: Mapped[list["Session"]] = relationship(
|
||||
"Session",
|
||||
sessions: Mapped[list[Session]] = relationship(
|
||||
Session,
|
||||
back_populates="user",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
grants: Mapped[list["Grant"]] = relationship(
|
||||
grants: Mapped[list[Grant]] = relationship(
|
||||
"Grant",
|
||||
back_populates="user",
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from urllib.parse import urlencode
|
||||
|
||||
|
|
@ -16,10 +17,106 @@ from app.deps import get_db
|
|||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
# ── Forgejo API client ──
|
||||
|
||||
|
||||
async def _forgejo_post(settings: Settings, path: str, data: dict) -> dict:
|
||||
url = f"{settings.forgejo_base_url.rstrip('/')}{path}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
resp = await client.post(url, data=data, headers={"Accept": "application/json"})
|
||||
except httpx.RequestError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Cannot reach Forgejo: {exc}",
|
||||
) from exc
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=(f"Forgejo API error {resp.status_code} at {path}: {resp.text[:500]}"),
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def _forgejo_get(settings: Settings, path: str, token: str) -> dict:
|
||||
url = f"{settings.forgejo_base_url.rstrip('/')}{path}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
resp = await client.get(url, headers={"Authorization": f"token {token}"})
|
||||
except httpx.RequestError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Cannot reach Forgejo: {exc}",
|
||||
) from exc
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=(f"Forgejo API error {resp.status_code} at {path}: {resp.text[:500]}"),
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
# ── OAuth CSRF helpers ──
|
||||
|
||||
|
||||
def _set_oauth_state_cookie(response: Response, state: str) -> None:
|
||||
response.set_cookie(
|
||||
key="oauth_state",
|
||||
value=state,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
max_age=600,
|
||||
)
|
||||
|
||||
|
||||
def _verify_oauth_state(state: str | None, oauth_state: str | None) -> None:
|
||||
if not state or not oauth_state or not secrets.compare_digest(state, oauth_state):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="OAuth state mismatch. Possible CSRF attack.",
|
||||
)
|
||||
|
||||
|
||||
# ── Forgejo response parsers ──
|
||||
|
||||
|
||||
def _parse_token_response(data: dict) -> tuple[str, str | None, datetime | None]:
|
||||
access_token = data.get("access_token")
|
||||
if not access_token or not isinstance(access_token, str):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="Forgejo OAuth response did not include an access_token.",
|
||||
)
|
||||
refresh_token = data.get("refresh_token")
|
||||
refresh_plain = refresh_token if isinstance(refresh_token, str) else None
|
||||
expires_in = data.get("expires_in")
|
||||
if expires_in is not None:
|
||||
expires_at = datetime.now(UTC) + timedelta(seconds=int(expires_in))
|
||||
else:
|
||||
expires_at = None
|
||||
return access_token, refresh_plain, expires_at
|
||||
|
||||
|
||||
def _parse_user_response(data: dict) -> tuple[str, str, str | None]:
|
||||
provider_user_id = str(data.get("id", "")).strip()
|
||||
provider_username = str(data.get("login", "")).strip()
|
||||
if not provider_user_id or not provider_username:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="Forgejo user response missing id or login.",
|
||||
)
|
||||
email_val = data.get("email")
|
||||
email = email_val if isinstance(email_val, str) and email_val.strip() else None
|
||||
return provider_user_id, provider_username, email
|
||||
|
||||
|
||||
# ── OAuth config helpers ──
|
||||
|
||||
|
||||
def _forgejo_oauth_redirect_uri(request: Request, settings: Settings) -> str:
|
||||
if settings.myst_public_base_url.strip():
|
||||
base = settings.myst_public_base_url.strip().rstrip("/")
|
||||
return f"{base}/auth/callback/forgejo"
|
||||
base_url = settings.myst_public_base_url.strip().rstrip("/")
|
||||
if base_url:
|
||||
return f"{base_url}/auth/callback/forgejo"
|
||||
return str(request.url_for("forgejo_oauth_callback"))
|
||||
|
||||
|
||||
|
|
@ -42,140 +139,76 @@ def _require_forgejo_oauth_config(settings: Settings) -> None:
|
|||
)
|
||||
|
||||
|
||||
# ── Routes ──
|
||||
|
||||
|
||||
@router.get("/login/forgejo")
|
||||
async def login_forgejo(request: Request, settings: Settings = Depends(get_settings)) -> RedirectResponse:
|
||||
async def login_forgejo(
|
||||
request: Request, settings: Settings = Depends(get_settings)
|
||||
) -> RedirectResponse:
|
||||
_require_forgejo_oauth_config(settings)
|
||||
|
||||
redirect_uri = _forgejo_oauth_redirect_uri(request, settings)
|
||||
base = settings.forgejo_base_url.rstrip("/")
|
||||
state = secrets.token_urlsafe(32)
|
||||
query = urlencode(
|
||||
{
|
||||
"client_id": settings.forgejo_oauth_client_id,
|
||||
"response_type": "code",
|
||||
"redirect_uri": redirect_uri,
|
||||
"scope": "read:user",
|
||||
"state": state,
|
||||
}
|
||||
)
|
||||
authorize_url = f"{base}/login/oauth/authorize?{query}"
|
||||
return RedirectResponse(authorize_url, status_code=status.HTTP_302_FOUND)
|
||||
authorization_url = f"{settings.forgejo_base_url.rstrip('/')}/login/oauth/authorize?{query}"
|
||||
response = RedirectResponse(authorization_url, status_code=status.HTTP_302_FOUND)
|
||||
_set_oauth_state_cookie(response, state)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/callback/forgejo", name="forgejo_oauth_callback")
|
||||
async def callback_forgejo(
|
||||
request: Request,
|
||||
response: Response,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
settings: Settings = Depends(get_settings),
|
||||
code: str | None = None,
|
||||
state: str | None = None,
|
||||
oauth_state: str | None = Cookie(default=None),
|
||||
) -> RedirectResponse:
|
||||
_require_forgejo_oauth_config(settings)
|
||||
if not code:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Missing OAuth authorization code from Forgejo.",
|
||||
)
|
||||
_verify_oauth_state(state, oauth_state)
|
||||
|
||||
redirect_uri = _forgejo_oauth_redirect_uri(request, settings)
|
||||
base = settings.forgejo_base_url.rstrip("/")
|
||||
token_url = f"{base}/login/oauth/access_token"
|
||||
redirect = RedirectResponse("/dashboard", status_code=status.HTTP_302_FOUND)
|
||||
redirect.delete_cookie("oauth_state")
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
token_resp = await client.post(
|
||||
token_url,
|
||||
data={
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": settings.forgejo_oauth_client_id,
|
||||
"client_secret": settings.forgejo_oauth_client_secret.get_secret_value(),
|
||||
"code": code,
|
||||
"redirect_uri": redirect_uri,
|
||||
},
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
except httpx.RequestError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Cannot reach Forgejo OAuth token endpoint: {exc}",
|
||||
) from exc
|
||||
token_data = await _forgejo_post(
|
||||
settings,
|
||||
"/login/oauth/access_token",
|
||||
{
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": settings.forgejo_oauth_client_id,
|
||||
"client_secret": settings.forgejo_oauth_client_secret.get_secret_value(),
|
||||
"code": code,
|
||||
"redirect_uri": _forgejo_oauth_redirect_uri(request, settings),
|
||||
},
|
||||
)
|
||||
access_token, refresh_plain, expires_at = _parse_token_response(token_data)
|
||||
|
||||
if token_resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=(
|
||||
f"Forgejo OAuth token exchange failed with HTTP {token_resp.status_code}: "
|
||||
f"{token_resp.text[:500]}"
|
||||
),
|
||||
)
|
||||
user_data = await _forgejo_get(settings, "/api/v1/user", access_token)
|
||||
provider_user_id, provider_username, email = _parse_user_response(user_data)
|
||||
|
||||
token_data = token_resp.json()
|
||||
access_token = token_data.get("access_token")
|
||||
if not access_token or not isinstance(access_token, str):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="Forgejo OAuth response did not include an access_token.",
|
||||
)
|
||||
user = await find_or_create_user(
|
||||
db,
|
||||
settings,
|
||||
provider="forgejo",
|
||||
provider_user_id=provider_user_id,
|
||||
provider_username=provider_username,
|
||||
email=email,
|
||||
access_token_raw=access_token,
|
||||
access_token_expires_at=expires_at,
|
||||
refresh_token_raw=refresh_plain,
|
||||
)
|
||||
|
||||
refresh_token = token_data.get("refresh_token")
|
||||
refresh_plain = refresh_token if isinstance(refresh_token, str) else None
|
||||
|
||||
expires_in = token_data.get("expires_in")
|
||||
access_token_expires_at: datetime | None
|
||||
if expires_in is not None:
|
||||
access_token_expires_at = datetime.now(UTC) + timedelta(seconds=int(expires_in))
|
||||
else:
|
||||
access_token_expires_at = None
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
user_resp = await client.get(
|
||||
f"{base}/api/v1/user",
|
||||
headers={"Authorization": f"token {access_token}"},
|
||||
)
|
||||
except httpx.RequestError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Cannot reach Forgejo user API: {exc}",
|
||||
) from exc
|
||||
|
||||
if user_resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=(
|
||||
f"Forgejo user lookup failed with HTTP {user_resp.status_code}: "
|
||||
f"{user_resp.text[:500]}"
|
||||
),
|
||||
)
|
||||
|
||||
user_json = user_resp.json()
|
||||
provider_user_id = str(user_json.get("id", "")).strip()
|
||||
provider_username = str(user_json.get("login", "")).strip()
|
||||
if not provider_user_id or not provider_username:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="Forgejo user response missing id or login.",
|
||||
)
|
||||
email_val = user_json.get("email")
|
||||
email = email_val if isinstance(email_val, str) and email_val.strip() else None
|
||||
|
||||
try:
|
||||
user = await find_or_create_user(
|
||||
db,
|
||||
settings,
|
||||
provider="forgejo",
|
||||
provider_user_id=provider_user_id,
|
||||
provider_username=provider_username,
|
||||
email=email,
|
||||
access_token_plain=access_token,
|
||||
access_token_expires_at=access_token_expires_at,
|
||||
refresh_token_plain=refresh_plain,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
|
||||
await create_session(db, response, user.id)
|
||||
return RedirectResponse("/dashboard", status_code=status.HTTP_302_FOUND)
|
||||
await create_session(db, redirect, user.id)
|
||||
return redirect
|
||||
|
||||
|
||||
@router.get("/logout")
|
||||
|
|
|
|||
|
|
@ -1,3 +1,7 @@
|
|||
[tool.ruff]
|
||||
target-version = "py313"
|
||||
line-length = 100
|
||||
|
||||
[project]
|
||||
name = "myst-web"
|
||||
version = "0.1.0"
|
||||
|
|
@ -15,5 +19,6 @@ dependencies = [
|
|||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"ruff>=0.11.0",
|
||||
"uvicorn[standard]>=0.44.0",
|
||||
]
|
||||
|
|
|
|||
31
web/uv.lock
generated
31
web/uv.lock
generated
|
|
@ -351,6 +351,7 @@ dependencies = [
|
|||
|
||||
[package.dev-dependencies]
|
||||
dev = [
|
||||
{ name = "ruff" },
|
||||
{ name = "uvicorn", extra = ["standard"] },
|
||||
]
|
||||
|
||||
|
|
@ -366,7 +367,10 @@ requires-dist = [
|
|||
]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [{ name = "uvicorn", extras = ["standard"], specifier = ">=0.44.0" }]
|
||||
dev = [
|
||||
{ name = "ruff", specifier = ">=0.11.0" },
|
||||
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.44.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pycparser"
|
||||
|
|
@ -512,6 +516,31 @@ wheels = [
|
|||
{ url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ruff"
|
||||
version = "0.15.13"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/24/21/a7d5c126d5b557715ef81098f3db2fe20f622a039ff2e626af28d674ab80/ruff-0.15.13.tar.gz", hash = "sha256:f9d89f17f7ba7fb2ed42921f0df75da797a9a5d71bc39049e2c687cf2baf44b7", size = 4678180, upload-time = "2026-05-14T13:44:37.869Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c6/61/11d458dc6ac22504fd8e237b29dfd40504c7fbbcc8930402cfe51a8e63ed/ruff-0.15.13-py3-none-linux_armv6l.whl", hash = "sha256:444b580fc72fd6887e650acd3e575e18cdc79dbcf42fb4030b491057921f61f8", size = 10738279, upload-time = "2026-05-14T13:44:18.7Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/86/ca/caa871ee7be718c45256fada4e16a218ee3e33f0c4a46b729a60a24912e6/ruff-0.15.13-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:6590d009e7cb7ebf36f83dbdd44a3fa48a0994ff6f1cdc1b08006abe58f98dc7", size = 11124798, upload-time = "2026-05-14T13:44:06.427Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d3/19/43f5f2e568dddde567fc41f8471f9432c09563e19d3e617a48cfa52f8f0a/ruff-0.15.13-py3-none-macosx_11_0_arm64.whl", hash = "sha256:1c26d2f66163deeb6e08d8b39fbbe983ce3c71cea06a6d7591cfd1421793c629", size = 10460761, upload-time = "2026-05-14T13:44:04.375Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/99/df/cf938cd6de3003178f03ad7c1ea2a6c099468c03a35037985070b37e76be/ruff-0.15.13-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9dbd6f94b434f896308e4d57fb7bfde0d02b99f7a64b3bdab0fdfa6a864203a5", size = 10804451, upload-time = "2026-05-14T13:44:25.221Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c7/7d/5d0973129b154ded2225729169d7068f26b467760b146493fde138415f23/ruff-0.15.13-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bf3259f3be4d181bda591da5db2571aed6853c6a048157756448020bc6c5cd22", size = 10534285, upload-time = "2026-05-14T13:44:08.888Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/e3/6b999bbc66cd51e5f073842bc2a3995e99c5e0e72e16b15e7261f7abf57a/ruff-0.15.13-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ae9c17e5eb4430c154e76abc25d79a318190f5a997f38fb6b114416c5319ffc9", size = 11312063, upload-time = "2026-05-14T13:44:11.274Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/af/5a/642639e9f5db04f1e97fbd6e091c6fd20725bdf072fb114d00eefb9e6eb8/ruff-0.15.13-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2e2e39bff6c341f4b577a21b801326fab0b11847f48fcaa83f00a113c9b3cb55", size = 12183079, upload-time = "2026-05-14T13:44:01.634Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/19/4c/7585735f6b53b0f12de13618b2f7d250a844f018822efc899df2e7b8295f/ruff-0.15.13-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e8d9a8e08013542e94d3220bc5b62cc3e5ef87c5f74bff367d3fac14fab013e6", size = 11440833, upload-time = "2026-05-14T13:43:59.043Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e8/31/bf1a0803d077e679cfeee5f2f67290a0fa79c7385b5d9a8c17b9db2c48f0/ruff-0.15.13-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc411dfebe5eebe55ce041c6ae080eb7668955e866daa2fbb16692a784f1c4ca", size = 11434486, upload-time = "2026-05-14T13:44:27.761Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e1/4e/62c9b999875d4f14db80f277c030578f5e249c9852d65b7ac7ad0b43c041/ruff-0.15.13-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:768494eb08b9cee54e2fd27969966f74db5a57f6eaa7a90fcb3306af34dfc4bd", size = 11385189, upload-time = "2026-05-14T13:44:13.704Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/89/7e959047a104df3eb12863447c110140191fc5b6c4f379ea2e803fcdb0e4/ruff-0.15.13-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:fb75f9a3a7e42ffe117d734494e6c5e5cb3565d66e12612cb63d0e572a41a5b6", size = 10781380, upload-time = "2026-05-14T13:43:56.734Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ff/52/5fd18f3b88cab63e88aa11516b3b4e1e5f720e5c330f8dbe5c26210f41f8/ruff-0.15.13-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:8cb74dd33bb2f6613faf7fc03b660053b5ac4f80e706d5788c6335e2a8048d51", size = 10540605, upload-time = "2026-05-14T13:44:20.748Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e8/e0/9e35f338990d3e41a82875ff7053ffe97541dae81c9d02143177f381d572/ruff-0.15.13-py3-none-musllinux_1_2_i686.whl", hash = "sha256:7ef823f817fcd191dc934e984be9cf4094f808effa16f2542ad8e821ba02bbf2", size = 11036554, upload-time = "2026-05-14T13:44:16.256Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c2/13/070fb048c24080fba188f66371e2a92785be257ad02242066dc7255ac6e9/ruff-0.15.13-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:f345a13937bd7f09f6f5d19fa0721b0c103e00e7f62bc67089a8e5e037719e0b", size = 11528133, upload-time = "2026-05-14T13:44:22.808Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6b/8c/b1e1666aef7fc6555094d73ae6cd981701781ae85b97ceefc0eebd0b4668/ruff-0.15.13-py3-none-win32.whl", hash = "sha256:4044f94208b3b05ba0fc4a4abd0558cf4d6459bd18325eead7fd8cc66f909b41", size = 10721455, upload-time = "2026-05-14T13:44:35.697Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ab/a6/870a3e8a50590bb92be184ad928c2922f088b00d9dc5c5ec7b924ee08c22/ruff-0.15.13-py3-none-win_amd64.whl", hash = "sha256:7064884d442b7d477b4e7473d12da7f08851d2b1982763c5d3f388a19468a1a4", size = 11900409, upload-time = "2026-05-14T13:44:30.389Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9b/36/9c015cd052fca743dae8cb2aeb16b551444787467db42ceab0fc968865af/ruff-0.15.13-py3-none-win_arm64.whl", hash = "sha256:2471da9bd1068c8c064b5fd9c0c4b6dddffd6369cb1cd68b29993b1709ff1b21", size = 11179336, upload-time = "2026-05-14T13:44:33.026Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlalchemy"
|
||||
version = "2.0.49"
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue