Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
609 changes: 609 additions & 0 deletions F02_GITHUB_AUTH_DESIGN.md

Large diffs are not rendered by default.

464 changes: 464 additions & 0 deletions SECURITY_AUDIT_PHASE6.md

Large diffs are not rendered by default.

14 changes: 3 additions & 11 deletions apps/api/app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from app.core.config import settings
from app.db.database import get_db
from app.models.user import User
from app.core.security import decode_session_user_id

def get_token_from_cookie(request: Request) -> str | None:
return request.cookies.get(settings.auth_cookie_name)
Expand All @@ -22,17 +23,8 @@ def get_current_user(
)

try:
payload = jwt.decode(
token, settings.auth_secret_key, algorithms=["HS256"]
)
user_id_str: str = payload.get("sub")
if user_id_str is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
)
user_id = int(user_id_str)
except (jwt.InvalidTokenError, ValueError):
user_id = decode_session_user_id(token)
except (jwt.InvalidTokenError, ValueError, TypeError):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
Expand Down
8 changes: 5 additions & 3 deletions apps/api/app/api/routes/ask.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,11 @@ def ask_repository(
response.answer = "I couldn't find enough relevant code in this repository to answer that confidently."

return response
except (AIUnavailableError, AIQuotaExceededError) as e:
logger.error(f"AI error in ask: {e}")
except AIQuotaExceededError:
raise
except AIUnavailableError as e:
logger.error("AI service unavailable during Ask")
raise HTTPException(status_code=503, detail=sanitize_ai_error(e))
except Exception as e:
logger.error(f"Unexpected error in ask: {e}")
logger.error("Unexpected generation failure during Ask")
raise HTTPException(status_code=500, detail="An internal error occurred during generation.")
19 changes: 14 additions & 5 deletions apps/api/app/api/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from fastapi.responses import RedirectResponse
from sqlalchemy.orm import Session
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from pydantic import ValidationError

from app.api.deps import get_current_user
Expand Down Expand Up @@ -220,17 +221,21 @@ async def google_callback(
# --- 4. Extract and validate required claims ---
google_sub: str | None = claims.get("sub")
email: str | None = claims.get("email")
email_verified: bool = bool(claims.get("email_verified", False))
email_verified: bool = claims.get("email_verified") is True
name: str | None = claims.get("name")

if not google_sub:
if not isinstance(google_sub, str) or not google_sub or len(google_sub) > 255:
return _fail_redirect(reason="missing_sub")

if not email or not email_verified:
if not isinstance(email, str) or not email or not email_verified:
return _fail_redirect(reason="unverified_email")

# --- 5. User resolution (Cases A/B/C/D) ---
user = _resolve_user(db, google_sub=google_sub, email=email, name=name)
try:
user = _resolve_user(db, google_sub=google_sub, email=email, name=name)
except IntegrityError:
db.rollback()
return _fail_redirect(reason="identity_conflict")
if user is None:
# Conflict: google_sub belongs to one user, email to another — refuse silently
return _fail_redirect(reason="identity_conflict")
Expand Down Expand Up @@ -277,6 +282,8 @@ def _resolve_user(

if user_by_email is not None:
# CASE B: existing CodeLens account — link Google identity.
if user_by_email.google_sub is not None:
return None # Never replace an already linked different identity.
user_by_email.google_sub = google_sub
if not user_by_email.name and name:
user_by_email.name = name
Expand All @@ -302,10 +309,12 @@ def _fail_redirect(reason: str) -> RedirectResponse:
Redirect to the frontend login page with a provider-neutral error code.
Never exposes tokens, secrets, or internal details.
"""
return RedirectResponse(
response = RedirectResponse(
url=f"{settings.frontend_url}/login?error={reason}",
status_code=status.HTTP_302_FOUND,
)
_clear_oauth_state_cookies(response)
return response


def _constant_time_compare(val1: str, val2: str) -> bool:
Expand Down
4 changes: 2 additions & 2 deletions apps/api/app/api/routes/pr_reviews.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.orm import Session

Expand All @@ -16,7 +16,7 @@
def get_pr_review_history(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
limit: int = 50,
limit: int = Query(default=50, ge=1, le=100),
):
"""Get the current user's PR review history."""
reviews = (
Expand Down
58 changes: 22 additions & 36 deletions apps/api/app/api/routes/repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
from app.services.analyzer import analyze_repository
from app.services.scan_progress import (
get_scan_progress,
is_scan_active,
claim_scan,
set_scan_progress,
update_scan_progress,
)
Expand Down Expand Up @@ -230,26 +230,19 @@ def create_repository(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
# If explicit details are missing, attempt to parse them from the provided URL
if not (repository_in.name and repository_in.owner and repository_in.full_name):
try:
parsed = parse_github_url(repository_in.url)
name = repository_in.name or parsed.name
owner = repository_in.owner or parsed.owner
full_name = repository_in.full_name or parsed.full_name
canonical_url = parsed.url
github_id = repository_in.github_id or full_name
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
)
else:
name = repository_in.name
owner = repository_in.owner
full_name = repository_in.full_name
canonical_url = repository_in.url
github_id = repository_in.github_id or full_name
# Explicit metadata must not bypass the URL trust boundary.
try:
parsed = parse_github_url(repository_in.url)
for supplied, expected in ((repository_in.name, parsed.name),
(repository_in.owner, parsed.owner),
(repository_in.full_name, parsed.full_name)):
if supplied is not None and supplied != expected:
raise ValueError("Repository metadata must match the GitHub URL")
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
name, owner, full_name = parsed.name, parsed.owner, parsed.full_name
canonical_url = parsed.url
github_id = repository_in.github_id or full_name

existing = db.execute(
select(Repository).where(
Expand Down Expand Up @@ -404,7 +397,7 @@ def analyze_cb(processed: int, total: int, msg: str) -> None:
)

except Exception as exc:
clean_error = sanitize_ai_error(exc) if hasattr(exc, "__str__") else "Scan failed unexpectedly"
clean_error = "Scan failed. Please try again later."
set_scan_progress(
repository_id=repository_id,
status="failed",
Expand Down Expand Up @@ -454,20 +447,9 @@ def start_repository_scan(
detail=f"Repository with id {repository_id} not found",
)

if is_scan_active(repository_id):
# Scan is already running: return existing status without starting duplicate
return get_scan_progress(repository_id)

# Initialize queued state
initial_state = set_scan_progress(
repository_id=repository_id,
status="queued",
stage="preparing",
progress=0,
files_processed=0,
files_total=0,
message="Scan queued...",
)
claimed, initial_state = claim_scan(repository_id)
if not claimed:
return initial_state

background_tasks.add_task(run_background_scan, repository_id)
return initial_state
Expand All @@ -491,6 +473,8 @@ def ingest_repository_endpoint(
detail=f"Repository with id {repository_id} not found",
)

if not claim_scan(repository_id)[0]:
raise HTTPException(status_code=409, detail="A repository scan is already active")
set_scan_progress(
repository_id=repository_id,
status="running",
Expand Down Expand Up @@ -627,6 +611,8 @@ def analyze_repository_endpoint(
detail=f"Repository with id {repository_id} not found",
)

if not claim_scan(repository_id)[0]:
raise HTTPException(status_code=409, detail="A repository scan is already active")
set_scan_progress(
repository_id=repository_id,
status="running",
Expand Down
7 changes: 4 additions & 3 deletions apps/api/app/core/ai_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,13 @@ def is_transient_cloud_error(exc: Exception | str) -> bool:
def sanitize_ai_error(exc: Exception | str) -> str:
"""Sanitize any AI provider error to avoid leaking provider details or internal metrics.

If the error message contains provider-specific details (Gemini, Google, Ollama, quotaId, URLs),
returns a friendly generic AI unavailable message. Otherwise preserves clean messages.
Unknown exception strings are never safe merely because a pattern did not
match: they may include credentials or source code. Always return the stable
provider-neutral unavailable message; quota errors have a separate handler.
"""
raw = str(exc).strip()
for pattern in _PROVIDER_PATTERNS:
if pattern.search(raw):
return AI_UNAVAILABLE_MESSAGE
return raw or AI_UNAVAILABLE_MESSAGE
return AI_UNAVAILABLE_MESSAGE

31 changes: 25 additions & 6 deletions apps/api/app/core/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from pathlib import Path
from urllib.parse import urlparse
from pydantic import Field, model_validator

from pydantic_settings import BaseSettings, SettingsConfigDict

Expand All @@ -8,16 +10,16 @@


class Settings(BaseSettings):
database_url: str
gemini_api_key: str | None = None
database_url: str = Field(repr=False)
gemini_api_key: str | None = Field(default=None, repr=False)
gemini_model: str = "gemini-3.6-flash"
github_token: str | None = None
github_token: str | None = Field(default=None, repr=False)
ai_provider_mode: str = "hybrid" # hybrid | cloud_only | ollama_only
ollama_base_url: str = "http://localhost:11434"
ollama_model: str = "qwen2.5-coder:7b"
ollama_timeout: int = 60

auth_secret_key: str = "dev_secret_key_change_in_production"
auth_secret_key: str = Field(min_length=32, repr=False)
auth_cookie_name: str = "codelens_session"
auth_cookie_secure: bool = False
auth_cookie_samesite: str = "lax"
Expand All @@ -26,7 +28,7 @@ class Settings(BaseSettings):
# Google OAuth 2.0 / OpenID Connect
# Set these via environment variables: GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI
google_client_id: str | None = None
google_client_secret: str | None = None
google_client_secret: str | None = Field(default=None, repr=False)
google_redirect_uri: str | None = None

# Frontend origin – used for post-OAuth redirects.
Expand All @@ -36,8 +38,25 @@ class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=str(_ENV_FILE),
extra="ignore",
hide_input_in_errors=True,
)

@model_validator(mode="after")
def validate_browser_security(self):
origin = urlparse(self.frontend_url)
if (origin.scheme not in ("http", "https") or not origin.hostname
or origin.username or origin.password or origin.query or origin.fragment
or origin.path or "*" in self.frontend_url):
raise ValueError("FRONTEND_URL must be an exact HTTP(S) origin without a path")
if self.auth_cookie_samesite not in ("lax", "strict", "none"):
raise ValueError("AUTH_COOKIE_SAMESITE must be lax, strict or none")
if self.auth_cookie_samesite == "none" and not self.auth_cookie_secure:
raise ValueError("SameSite=None requires AUTH_COOKIE_SECURE")
if origin.hostname not in ("localhost", "127.0.0.1", "::1"):
if origin.scheme != "https" or not self.auth_cookie_secure:
raise ValueError("Non-local browser deployments require HTTPS and secure cookies")
return self

@property
def google_oauth_configured(self) -> bool:
"""True only when all three Google OAuth values are present."""
Expand All @@ -48,4 +67,4 @@ def google_oauth_configured(self) -> bool:
)


settings = Settings()
settings = Settings()
Loading
Loading