Skip to content

02: backend-setup - #1

Merged
ASHUTOSH-KUMAR-RAO merged 1 commit into
mainfrom
02--Backend-Setup
May 5, 2026
Merged

02: backend-setup#1
ASHUTOSH-KUMAR-RAO merged 1 commit into
mainfrom
02--Backend-Setup

Conversation

@ASHUTOSH-KUMAR-RAO

@ASHUTOSH-KUMAR-RAO ASHUTOSH-KUMAR-RAO commented May 5, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Backend API infrastructure initialized with endpoints for chat, AI models, benchmarks, comparisons, exports, reports, templates, and voice functionality.
  • Chores

    • Added project configuration, dependency management, and environment setup files for backend deployment.

@coderabbitai

coderabbitai Bot commented May 5, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR establishes the initial backend infrastructure for Inferix, a privacy-first offline AI playground. It includes environment configuration, a Pydantic-based settings system, an empty FastAPI application with nine routers, CORS middleware, lifespan handlers, and health check endpoints, plus all required Python dependencies.

Changes

Backend Infrastructure Setup

Layer / File(s) Summary
Project Configuration & Ignore Patterns
.gitignore
Added comprehensive ignore rules for Python bytecode, virtual environments, build artifacts, database files, logs, OS/IDE files, and project-specific paths.
Dependency Manifest
backend/requirements.txt
Specified 32 Python packages covering FastAPI/Uvicorn, LangChain with Ollama support, Prisma/asyncpg, Pydantic configuration, Clerk auth, document export (ReportLab, Markdown), and voice recognition.
Environment Configuration Templates
backend/.env.example
Created template with placeholders for app metadata, NeonDB, Ollama models, Clerk keys, CORS origins, and export directory.
Development Environment File
backend/.env
Populated with concrete development values including PostgreSQL connection, Ollama localhost endpoint with three model identifiers, Clerk dummy credentials, and CORS allowlist.
Configuration System
backend/app/core/config.py
Implemented Settings class extending Pydantic BaseSettings with typed fields for app runtime, database, Ollama endpoints/models, authentication, CORS, and exports; added computed OLLAMA_MODELS property; instantiated module-level settings object.
FastAPI Application Entrypoint
backend/main.py
Created FastAPI app with async lifespan handler for startup/shutdown logging, configured CORS middleware with single-origin and credential support, registered nine API routers under /api/ prefixes, and exposed GET / (metadata) and GET /health (status) endpoints.
Router Definitions
backend/app/routers/ai.py, benchmark.py, chat.py, compare.py, export.py, models.py, report.py, templates.py, voice.py
Created nine minimal router modules, each importing APIRouter and instantiating a module-level router instance; placeholders for future endpoint definitions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A backend springs forth, like clover from the ground—
With routers nine and settings bound!
Ollama whispers, Clerk stands guard,
CORS flows freely (though hardened, not barred),
From .env dreams to lifespan's embrace,
Inferix finds its rightful place! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '02: backend-setup' accurately reflects the main objective of this pull request, which establishes the foundational backend infrastructure.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 02--Backend-Setup

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/.env.example (1)

1-25: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Remove backend/.env from version control immediately.

The AI-generated summary notes that a concrete backend/.env file (with real values for the same keys) was added alongside this .env.example in this PR. Committing a populated .env to git leaks secrets (CLERK_SECRET_KEY, DATABASE_URL, etc.) to everyone with repository access, and the secret is permanently in git history even after deletion.

Action items:

  1. Add backend/.env to .gitignore before merging.
  2. Remove it from this PR's commits (use git rm --cached backend/.env and amend/force-push, or use git filter-repo / BFG to purge history).
  3. Rotate any real credentials that may have been committed.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/.env.example` around lines 1 - 25, The PR has a committed populated
backend/.env that leaks secrets; add "backend/.env" to .gitignore, remove the
tracked file from the commit history (run git rm --cached backend/.env and
amend/force-push or use git filter-repo/BFG to purge it from history), and
rotate any exposed credentials (DATABASE_URL, CLERK_SECRET_KEY, etc.)
immediately; ensure the repository only contains backend/.env.example (the
variables shown like APP_NAME, DATABASE_URL, CLERK_SECRET_KEY) and not a real
backend/.env before merging.
🧹 Nitpick comments (5)
backend/app/core/config.py (2)

25-25: ⚡ Quick win

ALLOWED_ORIGINS typed as str — locks CORS to a single origin and breaks multi-origin support.

The field is consumed as [settings.ALLOWED_ORIGINS] in main.py, permanently wrapping it in a single-element list. Changing to List[str] allows multiple origins to be provided via a JSON-encoded env var (e.g., ALLOWED_ORIGINS='["http://localhost:3000","https://app.example.com"]'), which pydantic-settings automatically handles by treating the environment variable's value as a JSON-encoded string for complex types like list.

♻️ Proposed refactor
-    ALLOWED_ORIGINS: str = "http://localhost:3000"
+    ALLOWED_ORIGINS: List[str] = ["http://localhost:3000"]

And in backend/.env / backend/.env.example:

-ALLOWED_ORIGINS=http://localhost:3000
+ALLOWED_ORIGINS=["http://localhost:3000"]

Then simplify main.py:

-    allow_origins=[settings.ALLOWED_ORIGINS],
+    allow_origins=settings.ALLOWED_ORIGINS,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/core/config.py` at line 25, ALLOWED_ORIGINS is typed as str which
forces main.py to wrap it as a single-item list; change the config variable
ALLOWED_ORIGINS to a List[str] (import List from typing) and give it a sensible
default (e.g., ["http://localhost:3000"]) so pydantic-settings will parse a
JSON-array environment value like
'["http://localhost:3000","https://app.example.com"]'; then update any usage in
main.py that currently does [settings.ALLOWED_ORIGINS] to use
settings.ALLOWED_ORIGINS directly (no extra list wrapping) and update
.env/.env.example to provide a JSON array string for ALLOWED_ORIGINS.

38-38: 💤 Low value

Prefer SettingsConfigDict over a plain dict for model_config.

The idiomatic pydantic-settings pattern is model_config = SettingsConfigDict(env_file='.env', extra='ignore'), which provides IDE autocompletion, type checking, and catches invalid config keys at development time.

♻️ Proposed refactor
+from pydantic_settings import BaseSettings, SettingsConfigDict
 from typing import List

 class Settings(BaseSettings):
     ...
-    model_config = {"env_file": ".env", "extra": "ignore"}
+    model_config = SettingsConfigDict(env_file=".env", extra="ignore")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/core/config.py` at line 38, Replace the bare dict assigned to
model_config with a typed SettingsConfigDict from pydantic so IDEs/type-checkers
can validate keys: import SettingsConfigDict from pydantic (or pydantic-settings
if using that package) and change model_config = {"env_file": ".env", "extra":
"ignore"} to model_config = SettingsConfigDict(env_file=".env", extra="ignore");
keep the same keys/values and update any imports as needed.
backend/main.py (2)

13-16: 💤 Low value

Use logging instead of print() in the lifespan handler.

print() bypasses log-level control, structured logging, and any log aggregation pipeline that may be configured. Swap to the stdlib logging module so operators can manage verbosity consistently.

♻️ Proposed refactor
+import logging
+
+logger = logging.getLogger(__name__)
+
 `@asynccontextmanager`
 async def lifespan(app: FastAPI):
-    print(f"🚀 Inferix Backend starting on port {settings.APP_PORT}")
-    print(f"🤖 Ollama URL: {settings.OLLAMA_BASE_URL}")
+    logger.info("Inferix Backend starting on port %s", settings.APP_PORT)
+    logger.info("Ollama URL: %s", settings.OLLAMA_BASE_URL)
     yield
-    print("🛑 Inferix Backend shutting down...")
+    logger.info("Inferix Backend shutting down...")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/main.py` around lines 13 - 16, Replace the three print() calls in the
lifespan handler with stdlib logging: import logging, get a module logger via
logging.getLogger(__name__) and call logger.info(...) (or appropriate levels)
for the startup message that includes settings.APP_PORT and
settings.OLLAMA_BASE_URL and for the shutdown message; ensure logging is
configured elsewhere (or add basicConfig if needed) so log-level and aggregation
work correctly. Use the same message text but with logger.info in place of print
in the lifespan/generator where yield is present.

19-22: 💤 Low value

Version string "0.1.0" is duplicated.

Line 21 and line 49 both hard-code "0.1.0". The root() endpoint could derive it from the FastAPI app instance to stay in sync automatically.

♻️ Proposed fix
 `@app.get`("/")
 async def root():
     return {
         "app": "Inferix",
-        "version": "0.1.0",
+        "version": app.version,
         "status": "running",
         "docs": "/docs"
     }

Also applies to: 47-52

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/main.py` around lines 19 - 22, The version string is duplicated; set
the version only on the FastAPI app initialization (the FastAPI(...) call that
includes title/description/version/lifespan) and change the root() endpoint to
return the app's version instead of a hard-coded "0.1.0". Locate the FastAPI app
creation and ensure version="0.1.0" is the single source, then update the root()
function to use app.version (and app.title if used) so the endpoint reflects the
app instance value and remove the other hard-coded literal.
.gitignore (1)

9-10: 💤 Low value

Duplicate dist/ and build/ entries.

dist/ and build/ appear on lines 9–10 and again on lines 42–43.

✂️ Proposed fix
 # Build
-dist/
-build/

(Remove the second occurrence at lines 42–43, keeping the entries in the Python section.)

Also applies to: 42-43

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.gitignore around lines 9 - 10, The .gitignore contains duplicate entries
for "dist/" and "build/" — remove the second occurrence (the duplicates shown on
lines 42–43) so each of "dist/" and "build/" appears only once (keep the entries
in the Python section and delete the repeated ones), ensuring no other duplicate
patterns remain in the file.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.gitignore:
- Line 27: Tracked backend/.env is still in Git despite the .env rule in
.gitignore; stop tracking it by removing it from the index (while keeping the
file locally), commit that removal, and ensure .gitignore contains the .env
pattern so it won’t be re-added; then verify and document required keys using
backend/.env.example instead of committing real secrets.

In `@backend/.env`:
- Around line 1-18: The repository is currently tracking backend/.env
(containing keys like APP_NAME, DATABASE_URL, OLLAMA_BASE_URL, CLERK_SECRET_KEY,
etc.); stop tracking that file, add a safe template, and ensure .env is ignored:
remove backend/.env from the index (git rm --cached), add a .env entry to
.gitignore if missing, create/commit backend/.env.example containing the
placeholder entries (APP_NAME, DATABASE_URL, OLLAMA_MODEL_1/2/3,
CLERK_SECRET_KEY, ALLOWED_ORIGINS, EXPORT_DIR) and instruct developers to
populate their own local untracked backend/.env, then commit the changes.

In `@backend/app/core/config.py`:
- Line 9: The DEBUG flag in config.py is dangerously set to True by default;
change the default of DEBUG to False and load/override it from an
environment/config source so production is not accidentally exposed (update the
DEBUG variable initialization and any Config/Settings loader that sets DEBUG);
ensure the environment variable (e.g., DEBUG or APP_DEBUG) can enable True when
explicitly provided and add a short comment indicating DEBUG must be explicitly
enabled in non-dev environments.

In `@backend/main.py`:
- Around line 26-32: The CORS config uses CORSMiddleware with
allow_credentials=True but allows wildcard methods and headers, which violates
FastAPI rules and is overly permissive; update the CORSMiddleware call (where
app.add_middleware is used with CORSMiddleware and settings.ALLOWED_ORIGINS) to
replace allow_methods=["*"] and allow_headers=["*"] with explicit lists of only
the HTTP methods and headers your API needs (e.g.,
["GET","POST","PUT","PATCH","DELETE","OPTIONS"] for allow_methods and a minimal
set like ["Authorization","Content-Type","Accept"] for allow_headers), and
ensure settings.ALLOWED_ORIGINS is a concrete list of origins rather than a
wildcard when allow_credentials=True.

In `@backend/requirements.txt`:
- Line 18: The requirements entry "python-jose[cryptography]" is vulnerable;
update the requirement to pin version 3.4.0 or later (e.g., change to
"python-jose[cryptography]>=3.4.0") in backend/requirements.txt, then regenerate
any lock/compiled dependency files you use (pip-compile, poetry lock, or pipenv
lock) and reinstall dependencies so the new version is picked up; finally run
the test suite and your dependency vulnerability scan to confirm the CVE fixes
are applied.

---

Outside diff comments:
In `@backend/.env.example`:
- Around line 1-25: The PR has a committed populated backend/.env that leaks
secrets; add "backend/.env" to .gitignore, remove the tracked file from the
commit history (run git rm --cached backend/.env and amend/force-push or use git
filter-repo/BFG to purge it from history), and rotate any exposed credentials
(DATABASE_URL, CLERK_SECRET_KEY, etc.) immediately; ensure the repository only
contains backend/.env.example (the variables shown like APP_NAME, DATABASE_URL,
CLERK_SECRET_KEY) and not a real backend/.env before merging.

---

Nitpick comments:
In @.gitignore:
- Around line 9-10: The .gitignore contains duplicate entries for "dist/" and
"build/" — remove the second occurrence (the duplicates shown on lines 42–43) so
each of "dist/" and "build/" appears only once (keep the entries in the Python
section and delete the repeated ones), ensuring no other duplicate patterns
remain in the file.

In `@backend/app/core/config.py`:
- Line 25: ALLOWED_ORIGINS is typed as str which forces main.py to wrap it as a
single-item list; change the config variable ALLOWED_ORIGINS to a List[str]
(import List from typing) and give it a sensible default (e.g.,
["http://localhost:3000"]) so pydantic-settings will parse a JSON-array
environment value like '["http://localhost:3000","https://app.example.com"]';
then update any usage in main.py that currently does [settings.ALLOWED_ORIGINS]
to use settings.ALLOWED_ORIGINS directly (no extra list wrapping) and update
.env/.env.example to provide a JSON array string for ALLOWED_ORIGINS.
- Line 38: Replace the bare dict assigned to model_config with a typed
SettingsConfigDict from pydantic so IDEs/type-checkers can validate keys: import
SettingsConfigDict from pydantic (or pydantic-settings if using that package)
and change model_config = {"env_file": ".env", "extra": "ignore"} to
model_config = SettingsConfigDict(env_file=".env", extra="ignore"); keep the
same keys/values and update any imports as needed.

In `@backend/main.py`:
- Around line 13-16: Replace the three print() calls in the lifespan handler
with stdlib logging: import logging, get a module logger via
logging.getLogger(__name__) and call logger.info(...) (or appropriate levels)
for the startup message that includes settings.APP_PORT and
settings.OLLAMA_BASE_URL and for the shutdown message; ensure logging is
configured elsewhere (or add basicConfig if needed) so log-level and aggregation
work correctly. Use the same message text but with logger.info in place of print
in the lifespan/generator where yield is present.
- Around line 19-22: The version string is duplicated; set the version only on
the FastAPI app initialization (the FastAPI(...) call that includes
title/description/version/lifespan) and change the root() endpoint to return the
app's version instead of a hard-coded "0.1.0". Locate the FastAPI app creation
and ensure version="0.1.0" is the single source, then update the root() function
to use app.version (and app.title if used) so the endpoint reflects the app
instance value and remove the other hard-coded literal.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2be9481f-6821-4797-8dad-35803e95d11c

📥 Commits

Reviewing files that changed from the base of the PR and between 721e948 and 659f412.

⛔ Files ignored due to path filters (1)
  • backend/app/robo.png is excluded by !**/*.png
📒 Files selected for processing (15)
  • .gitignore
  • backend/.env
  • backend/.env.example
  • backend/app/core/config.py
  • backend/app/routers/ai.py
  • backend/app/routers/benchmark.py
  • backend/app/routers/chat.py
  • backend/app/routers/compare.py
  • backend/app/routers/export.py
  • backend/app/routers/models.py
  • backend/app/routers/report.py
  • backend/app/routers/templates.py
  • backend/app/routers/voice.py
  • backend/main.py
  • backend/requirements.txt

Comment thread .gitignore
ENV/

# Environment Variables
.env

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

backend/.env is tracked despite the .env gitignore rule.

The pattern .env on line 27 should match backend/.env in any subdirectory, yet backend/.env is committed in this PR. This typically means the file was staged with git add -f or was tracked before the .gitignore was applied. Once a file is tracked by Git, .gitignore no longer prevents changes from being staged — meaning if a developer later writes real Clerk keys or database credentials into backend/.env, those secrets will be committed automatically.

Remove the file from tracking immediately:

git rm --cached backend/.env

Use backend/.env.example (already in the repo per the AI summary) for documentation of required keys, and keep real .env files untracked.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.gitignore at line 27, Tracked backend/.env is still in Git despite the .env
rule in .gitignore; stop tracking it by removing it from the index (while
keeping the file locally), commit that removal, and ensure .gitignore contains
the .env pattern so it won’t be re-added; then verify and document required keys
using backend/.env.example instead of committing real secrets.

Comment thread backend/.env
Comment on lines +1 to +18
APP_NAME=Inferix
APP_ENV=development
APP_PORT=8000
DEBUG=True

DATABASE_URL=postgresql://dummy:dummy@localhost/inferix

OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL_1=gemma:2b
OLLAMA_MODEL_2=phi3:mini
OLLAMA_MODEL_3=llama3.2:3b

CLERK_SECRET_KEY=dummy_secret_key
CLERK_PUBLISHABLE_KEY=dummy_publishable_key

ALLOWED_ORIGINS=http://localhost:3000

EXPORT_DIR=./exports

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not commit backend/.env — tracked .env files invite credential leaks.

This file is the downstream consequence of the git tracking issue flagged in .gitignore. Even with placeholder values now, the file being tracked means any future replacement of dummy_secret_key or dummy:dummy@localhost/inferix with real credentials will be silently committed and pushed. The canonical practice is to commit only .env.example and let each developer create their own untracked .env.

See the .gitignore comment above for the git rm --cached remediation.

🧰 Tools
🪛 dotenv-linter (4.0.0)

[warning] 2-2: [UnorderedKey] The APP_ENV key should go before the APP_NAME key

(UnorderedKey)


[warning] 14-14: [UnorderedKey] The CLERK_PUBLISHABLE_KEY key should go before the CLERK_SECRET_KEY key

(UnorderedKey)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/.env` around lines 1 - 18, The repository is currently tracking
backend/.env (containing keys like APP_NAME, DATABASE_URL, OLLAMA_BASE_URL,
CLERK_SECRET_KEY, etc.); stop tracking that file, add a safe template, and
ensure .env is ignored: remove backend/.env from the index (git rm --cached),
add a .env entry to .gitignore if missing, create/commit backend/.env.example
containing the placeholder entries (APP_NAME, DATABASE_URL, OLLAMA_MODEL_1/2/3,
CLERK_SECRET_KEY, ALLOWED_ORIGINS, EXPORT_DIR) and instruct developers to
populate their own local untracked backend/.env, then commit the changes.

APP_NAME: str = "Inferix"
APP_ENV: str = "development"
APP_PORT: int = 8000
DEBUG: bool = True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

DEBUG defaults to True — unsafe for production deployments.

If this service is ever deployed without an explicit DEBUG=False in the environment, debug mode will be active, potentially exposing stack traces and internal details to end users.

🔒 Proposed fix
-    DEBUG: bool = True
+    DEBUG: bool = False
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
DEBUG: bool = True
DEBUG: bool = False
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/core/config.py` at line 9, The DEBUG flag in config.py is
dangerously set to True by default; change the default of DEBUG to False and
load/override it from an environment/config source so production is not
accidentally exposed (update the DEBUG variable initialization and any
Config/Settings loader that sets DEBUG); ensure the environment variable (e.g.,
DEBUG or APP_DEBUG) can enable True when explicitly provided and add a short
comment indicating DEBUG must be explicitly enabled in non-dev environments.

Comment thread backend/main.py
Comment on lines +26 to +32
app.add_middleware(
CORSMiddleware,
allow_origins=[settings.ALLOWED_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

CORS is overly permissive: wildcard methods and headers combined with allow_credentials=True.

The FastAPI documentation explicitly states that none of allow_origins, allow_methods, and allow_headers can be set to ['*'] when allow_credentials is set to True — all of them must be explicitly specified. Using ["*"] for both methods and headers while allow_credentials=True is a broad attack surface: any HTTP method and any custom header (including auth-bearing headers) will be accepted cross-origin from the configured domain.

Restrict to the specific methods and headers this API actually needs:

🔒 Proposed fix
 app.add_middleware(
     CORSMiddleware,
     allow_origins=[settings.ALLOWED_ORIGINS],
     allow_credentials=True,
-    allow_methods=["*"],
-    allow_headers=["*"],
+    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
+    allow_headers=["Authorization", "Content-Type"],
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
app.add_middleware(
CORSMiddleware,
allow_origins=[settings.ALLOWED_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(
CORSMiddleware,
allow_origins=[settings.ALLOWED_ORIGINS],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type"],
)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/main.py` around lines 26 - 32, The CORS config uses CORSMiddleware
with allow_credentials=True but allows wildcard methods and headers, which
violates FastAPI rules and is overly permissive; update the CORSMiddleware call
(where app.add_middleware is used with CORSMiddleware and
settings.ALLOWED_ORIGINS) to replace allow_methods=["*"] and allow_headers=["*"]
with explicit lists of only the HTTP methods and headers your API needs (e.g.,
["GET","POST","PUT","PATCH","DELETE","OPTIONS"] for allow_methods and a minimal
set like ["Authorization","Content-Type","Accept"] for allow_headers), and
ensure settings.ALLOWED_ORIGINS is a concrete list of origins rather than a
wildcard when allow_credentials=True.

Comment thread backend/requirements.txt
psutil

# Auth
python-jose[cryptography]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

CVE-2024-33663 python-jose algorithm confusion vulnerability

💡 Result:

CVE-2024-33663 is an algorithm-confusion vulnerability in the Python library python-jose that affects versions up to and including 3.3.0, where handling of OpenSSH ECDSA keys (and other key formats) can allow an attacker to confuse the algorithm expected during JWT verification [1]. Impact (what can go wrong) If an attacker can influence what key material and algorithm are used during JWT verification, the algorithm confusion can undermine signature validation and lead to authentication bypass / forged JWT acceptance; multiple vulnerability databases describe it as enabling bypass of authentication/signature verification under the affected conditions [1][2][3]. Affected versions python-jose through 3.3.0 is listed as affected [1][4]. Fix / remediation The package advisory data indicates the issue is fixed in python-jose 3.4.0 (and later), with affected versions introduced through 3.3.0 and fixed at 3.4.0 [4]. The upstream release notes for 3.4.0 explicitly state “Fix for CVE-2024-33663 - signing JWT with public key is now forbidden” [5]. Practical guidance 1) Upgrade python-jose to at least 3.4.0 (prefer the latest available) [4][6]. 2) If you cannot upgrade immediately, ensure your JWT verification logic strictly uses the intended algorithm(s) and key type for verification, and do not accept attacker-controlled algorithm/key-type combinations (the issue is fundamentally about algorithm enforcement during verification) [1][2]. References (evidence) - NVD entry summarizing the issue and affected scope (python-jose through 3.3.0; algorithm confusion with OpenSSH ECDSA and other formats) [1]. - pypa advisory database record for PYSEC-2024-232 (CVE-2024-33663), including the fixed version boundary at 3.4.0 [4]. - Upstream python-jose 3.4.0 release notes mentioning the specific fix for CVE-2024-33663 [5].

Citations:


🌐 Web query:

CVE-2024-33664 python-jose JWT bomb DoS vulnerability

💡 Result:

CVE-2024-33664 is a denial-of-service (DoS) vulnerability in the python-jose library, nicknamed a "JWT bomb." It affects versions up to and including 3.3.0. Attackers can cause resource consumption by crafting a JSON Web Encryption (JWE) token with a high compression ratio, leading to excessive memory and processing time during decoding.[1][2][3] CVSS v3.1 base score: 5.3 (Medium), with vector AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L.[1][4] The vulnerability was reported in GitHub issue #344, which includes a PoC demonstrating significantly longer processing times for compressed tokens.[2] It is similar to CVE-2024-21319.[1] Fix: Upgrade to python-jose version 3.4.0 or later, released on 2025-02-14. The fix limits incoming JWE tokens and decompressed data to 250 KiB, implemented in pull request #352 (merged Feb 6, 2025).[3][5][6] Workaround: If not using JWE (jose.jwe), the vulnerability does not affect the application. Otherwise, monkey-patch by removing 'DEF' compression support: import jose.constants; jose.constants.ZIPS.SUPPORTED.discard('DEF')[2]. Limit maximum token length to 250K.[2]

Citations:


🏁 Script executed:

cat -n backend/requirements.txt | head -30

Repository: ASHUTOSH-KUMAR-RAO/Inferix

Length of output: 567


Upgrade python-jose[cryptography] to version 3.4.0 or higher to address two critical security vulnerabilities.

CVE-2024-33663 is an algorithm confusion vulnerability in python-jose ≤ 3.3.0 that affects JWT signature verification, particularly with OpenSSH ECDSA keys. An attacker with access to the public key can forge JWT signatures and bypass authentication.

CVE-2024-33664 is a denial-of-service vulnerability ("JWT bomb") in python-jose ≤ 3.3.0 where crafted JWE tokens with high compression ratios cause excessive memory and CPU consumption.

Both vulnerabilities are fixed in python-jose 3.4.0 (released February 14, 2025).

📌 Proposed fix
-python-jose[cryptography]
+python-jose[cryptography]>=3.4.0
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
python-jose[cryptography]
python-jose[cryptography]>=3.4.0
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/requirements.txt` at line 18, The requirements entry
"python-jose[cryptography]" is vulnerable; update the requirement to pin version
3.4.0 or later (e.g., change to "python-jose[cryptography]>=3.4.0") in
backend/requirements.txt, then regenerate any lock/compiled dependency files you
use (pip-compile, poetry lock, or pipenv lock) and reinstall dependencies so the
new version is picked up; finally run the test suite and your dependency
vulnerability scan to confirm the CVE fixes are applied.

@ASHUTOSH-KUMAR-RAO
ASHUTOSH-KUMAR-RAO merged commit b553244 into main May 5, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant