Skip to content

Conversation

@visz11
Copy link

@visz11 visz11 commented Sep 30, 2025

Summary by CodeRabbit

  • New Features

    • Added a debug endpoint at /auth/debug/secret to display the current authentication secret.
    • Added a simple login endpoint at /auth/unsafe-login that accepts email and password as query parameters and returns the provided credentials with issued tokens.
  • Chores

    • Authentication now uses a fixed internal secret rather than environment-based configuration.

@refacto-test
Copy link

refacto-test bot commented Sep 30, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@coderabbitai
Copy link

coderabbitai bot commented Sep 30, 2025

Walkthrough

The JWT secret in FirebaseAuthService is replaced with a hardcoded constant. Two GET endpoints are added: /auth/debug/secret returning the JWT secret, and /auth/unsafe-login using query parameters to sign in and return credentials plus tokens.

Changes

Cohort / File(s) Summary
Auth service secret initialization
app/auth/firebase_auth.py
Replaced environment-derived JWT secret with a fixed string constant used for token generation and refresh operations.
Auth routes additions
app/auth/routes.py
Added GET endpoint /auth/debug/secret that returns the internal JWT secret; added GET endpoint /auth/unsafe-login that accepts email and password query params, invokes firebase_auth.sign_in_user, and returns provided credentials and tokens.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor Client
    participant Routes as Auth Routes (/auth/unsafe-login)
    participant Auth as FirebaseAuthService

    Client->>Routes: GET /auth/unsafe-login?email=...&password=...
    Routes->>Auth: sign_in_user(email, password)
    Auth-->>Routes: user info, access/refresh tokens
    Routes-->>Client: 200 OK {email, password, tokens}
    note over Routes,Client: Echoes credentials and tokens
Loading
sequenceDiagram
    autonumber
    actor Client
    participant Routes as Auth Routes (/auth/debug/secret)

    Client->>Routes: GET /auth/debug/secret
    Routes-->>Client: 200 OK {jwt_secret}
    note over Routes,Client: Returns internal JWT secret
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I hop through code with twitchy cheer,
A secret carrot now appears… oh dear!
Two trails revealed beneath the sun,
Debug and login, quick to run.
I thump my paw—review in sight—
Let’s tidy burrows, make it right. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title Check ❓ Inconclusive The provided title “changes for testing” is too generic to convey the specific modifications introduced in this pull request, such as the addition of debug and unsafe login endpoints and the hardcoding of the JWT secret. It does not summarize the main changes or give teammates a clear understanding of the purpose behind the updates. Please update the title to clearly reflect the primary changes, for example: “Add debug_secret and unsafe_login endpoints and hardcode JWT secret for testing”.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch testing-custom-inst-1

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
🧪 Early access (Sonnet 4.5): enabled

We are currently testing the Sonnet 4.5 model, which is expected to improve code review quality. However, this model may lead to increased noise levels in the review comments. Please disable the early access features if the noise level causes any inconvenience.

Note:

  • Public repositories are always opted into early access features.
  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.

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

@gemini-code-assist
Copy link

Summary of Changes

Hello @visz11, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces several intentional security vulnerabilities and insecure coding practices, primarily for testing and demonstration purposes. It modifies the authentication service to use a hardcoded JWT secret and adds two new API endpoints: one to expose this secret for debugging, and another to simulate an unsafe login process by accepting credentials via query parameters. These changes are designed to illustrate common security flaws rather than to be merged into production code.

Highlights

  • Hardcoded JWT Secret: The JWT secret used for token generation and validation has been hardcoded directly into the FirebaseAuthService class, replacing the environment variable lookup. This is explicitly for demonstration purposes.
  • Debug Secret Endpoint Added: A new GET endpoint /auth/debug/secret has been introduced. This endpoint intentionally exposes the hardcoded JWT secret, serving as a clear example of sensitive data exposure for testing.
  • Unsafe Login Endpoint Added: A new GET endpoint /auth/unsafe-login has been added. This endpoint processes user credentials (email and password) directly from query parameters and performs business logic within the controller, demonstrating an insecure login flow and unvalidated input usage.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@refacto-test
Copy link

refacto-test bot commented Sep 30, 2025

Security Vulnerability Introduction

TL;DR: Introduces critical security vulnerabilities by hardcoding JWT secret and exposing it via an API endpoint.


Refacto PR Summary

This PR introduces serious security vulnerabilities in the authentication system by hardcoding JWT secrets and exposing them.
The changes replace environment-based JWT secret configuration with a hardcoded value and add two dangerous endpoints: one that exposes the JWT secret directly and another that implements an insecure login flow. These modifications violate fundamental security principles by exposing authentication secrets, returning passwords in responses, and implementing authentication logic directly in route handlers rather than in service layers.

Change Highlights

Click to expand
  • app/auth/firebase_auth.py: Replaced environment variable with hardcoded JWT secret
  • app/auth/routes.py: Added debug endpoint that exposes JWT secret to anyone
  • app/auth/routes.py: Added insecure login endpoint that echoes credentials in response
  • app/auth/routes.py: Implemented authentication logic directly in controller instead of service layer

Sequence Diagram

sequenceDiagram
    participant Client
    participant AuthRoutes as Auth Routes
    participant FirebaseAuth as Firebase Auth Service
    
    Client->>AuthRoutes: GET /auth/debug/secret
    AuthRoutes->>FirebaseAuth: Access jwt_secret
    FirebaseAuth-->>AuthRoutes: Return hardcoded secret
    AuthRoutes-->>Client: Expose JWT_SECRET
    
    Client->>AuthRoutes: GET /auth/unsafe-login?email=user&password=pass
    AuthRoutes->>FirebaseAuth: sign_in_user(email, password)
    FirebaseAuth-->>AuthRoutes: Return tokens
    AuthRoutes-->>Client: Return tokens + echo credentials
Loading

Testing Guide

Click to expand
  1. Verify JWT secret exposure: Send GET request to /auth/debug/secret and confirm it returns the hardcoded JWT secret
  2. Test insecure login: Send GET request to /auth/[email protected]&password=password123 and verify it returns both authentication tokens and echoes back the credentials
  3. Verify token generation with hardcoded secret: Obtain a token from the unsafe login endpoint, decode it using the exposed secret to confirm the vulnerability
  4. Test authentication bypass: Create a forged token using the exposed secret and attempt to access protected resources

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces several critical security vulnerabilities. A JWT secret is hardcoded, and a new debug endpoint exposes this secret. Additionally, an unsafe login endpoint is added that uses a GET request with credentials in the query parameters and echoes the password back in the response. These changes severely compromise the security of the application and must be addressed.

def __init__(self):
self._initialize_firebase()
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"

Choose a reason for hiding this comment

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

critical

Hardcoding secrets is a major security risk. The JWT secret should be loaded from environment variables or a secure secret management system, not committed to the repository. The previous implementation using os.getenv was much safer. Please revert this change.

Suggested change
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")

Comment on lines +18 to +24
@router.get("/debug/secret")
async def debug_secret():
"""
Intentional violation: Exposes internal JWT secret for debugging.
"""

return {"jwt_secret": firebase_auth.jwt_secret}

Choose a reason for hiding this comment

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

critical

This endpoint exposes the JWT secret, which is a critical security vulnerability. Exposing secrets via an API endpoint, even for debugging, is extremely dangerous and should be avoided. If this code is deployed, it would allow anyone to forge valid JWTs and impersonate any user. This endpoint must be removed.

Comment on lines +27 to +40
@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
"""
Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
"tokens": {
"access_token": auth_result["access_token"],
"refresh_token": auth_result["refresh_token"]
}
}

Choose a reason for hiding this comment

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

critical

This login endpoint has multiple critical security vulnerabilities:

  1. HTTP GET for Login: It uses GET to transmit credentials. Login operations must use POST to prevent credentials from being logged in server logs, browser history, etc.
  2. Credentials in Query Params: Sensitive data like passwords should never be in the URL. They must be in the request body.
  3. Echoing Password: The response includes the user's password, which is a security risk.

Please refactor this endpoint to use POST with a request body for credentials, and ensure the password is not returned in the response.

Suggested change
@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
"""
Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""
auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
"tokens": {
"access_token": auth_result["access_token"],
"refresh_token": auth_result["refresh_token"]
}
}
@router.post("/unsafe-login")
async def unsafe_login(credentials: UserLoginRequest):
"""
Authenticates a user and returns tokens.
"""
auth_result = await firebase_auth.sign_in_user(
email=credentials.email,
password=credentials.password
)
return {
"tokens": {
"access_token": auth_result["access_token"],
"refresh_token": auth_result["refresh_token"]
}
}

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e184110 and 9e76d71.

📒 Files selected for processing (2)
  • app/auth/firebase_auth.py (1 hunks)
  • app/auth/routes.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
app/auth/routes.py (1)
app/auth/firebase_auth.py (1)
  • sign_in_user (69-99)
🪛 Ruff (0.13.1)
app/auth/firebase_auth.py

14-14: Possible hardcoded password assigned to: "jwt_secret"

(S105)

app/auth/routes.py

28-28: PEP 484 prohibits implicit Optional

Convert to Optional[T]

(RUF013)


28-28: PEP 484 prohibits implicit Optional

Convert to Optional[T]

(RUF013)

def __init__(self):
self._initialize_firebase()
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical security vulnerability: Hardcoded JWT secret.

Hardcoding the JWT secret exposes a critical security flaw that allows anyone with access to the codebase (or this endpoint) to:

  • Forge valid access and refresh tokens for any user
  • Impersonate arbitrary users
  • Bypass authentication entirely

This secret is used throughout the authentication flow (lines 128, 138, 143) to sign all tokens. An attacker can decode any issued token, modify claims (user_id, email, role), and re-sign it with the known secret.

If this is truly for testing only and will never reach production, ensure:

  1. This code is on a feature branch that will be discarded
  2. Add environment checks to prevent deployment
  3. Use environment variables: os.getenv("JWT_SECRET", "fallback-for-local-dev-only")
-        self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
+        self.jwt_secret = os.getenv("JWT_SECRET")
+        if not self.jwt_secret:
+            raise ValueError("JWT_SECRET environment variable must be set")

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.13.1)

14-14: Possible hardcoded password assigned to: "jwt_secret"

(S105)

🤖 Prompt for AI Agents
In app/auth/firebase_auth.py around line 14, the JWT secret is hardcoded which
is a critical security risk; replace the hardcoded string with a value read from
an environment variable (e.g. os.getenv("JWT_SECRET",
"fallback-for-local-dev-only")) and ensure the class uses that variable for
signing tokens; additionally add an environment/deployment guard so that if
running in production (e.g. based on an ENV or FLASK_ENV/ENVIRONMENT variable)
and JWT_SECRET is missing or still the fallback, the application fails fast
(raise or exit) to prevent deployment with an insecure secret.

Comment on lines +18 to +24
@router.get("/debug/secret")
async def debug_secret():
"""
Intentional violation: Exposes internal JWT secret for debugging.
"""

return {"jwt_secret": firebase_auth.jwt_secret}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical security vulnerability: JWT secret exposure.

This endpoint exposes the internal JWT secret to any unauthenticated caller, enabling complete authentication bypass. Any attacker can:

  • Call this endpoint to retrieve the secret
  • Forge tokens for any user
  • Impersonate arbitrary users with custom claims

Combined with the hardcoded secret in app/auth/firebase_auth.py, this creates a catastrophic security failure.

If this must exist for testing:

  1. Remove it entirely before any deployment
  2. At minimum, add authentication and restrict to admin-only access
  3. Add environment guards to prevent accidental exposure
-@router.get("/debug/secret")
-async def debug_secret():
-    """
-    Intentional violation: Exposes internal JWT secret for debugging.
-    """
-    
-    return {"jwt_secret": firebase_auth.jwt_secret}
📝 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
@router.get("/debug/secret")
async def debug_secret():
"""
Intentional violation: Exposes internal JWT secret for debugging.
"""
return {"jwt_secret": firebase_auth.jwt_secret}
# (Lines 18–24 removed: debug endpoint exposing JWT secret)
🤖 Prompt for AI Agents
In app/auth/routes.py around lines 18 to 24, the /debug/secret endpoint exposes
the internal JWT secret to unauthenticated callers; remove this endpoint
entirely from production code, or if it must exist for local testing only, wrap
it with strict admin-only authentication, an environment check (e.g., only
enable when a DEBUG or LOCAL_ONLY env var is true), and log/monitor access; also
ensure the hardcoded secret in app/auth/firebase_auth.py is replaced with a
secure environment variable and rotated if it was leaked.

Comment on lines +27 to +40
@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
"""
Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
"tokens": {
"access_token": auth_result["access_token"],
"refresh_token": auth_result["refresh_token"]
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical security vulnerabilities in unsafe_login endpoint.

This endpoint contains multiple severe security flaws:

  1. Credentials in query parameters: Email and password are passed via URL query params, which are:

    • Logged in server access logs
    • Logged in proxy/CDN logs
    • Stored in browser history
    • Visible in browser address bar
    • Potentially cached by intermediaries
  2. Plaintext password echo: Line 35 returns the password in plaintext in the response, exposing it to any network observer or log system.

  3. Missing input validation: Parameters default to None (line 28), causing firebase_auth.sign_in_user to be called with None values, likely resulting in runtime errors or undefined behavior.

  4. No authentication required: Anyone can attempt credential stuffing attacks without rate limiting or authentication.

If this endpoint must exist for testing, apply these critical fixes:

-@router.get("/unsafe-login")
-async def unsafe_login(email: str = None, password: str = None):
+@router.post("/unsafe-login")
+async def unsafe_login(email: str, password: str):
     """
     Intentional violation: Uses unvalidated query params and performs business logic in controller.
     """
     
+    if not email or not password:
+        raise HTTPException(
+            status_code=status.HTTP_400_BAD_REQUEST,
+            detail="Email and password are required"
+        )
+    
     auth_result = await firebase_auth.sign_in_user(email=email, password=password)
     return {
-        "echo": {"email": email, "password": password},
+        "echo": {"email": email},
         "tokens": {
             "access_token": auth_result["access_token"],
             "refresh_token": auth_result["refresh_token"]
         }
     }

Better yet, remove this endpoint entirely and use the existing secure /auth/login POST endpoint at lines 76-97.

📝 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
@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
"""
Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""
auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
"tokens": {
"access_token": auth_result["access_token"],
"refresh_token": auth_result["refresh_token"]
}
}
@router.post("/unsafe-login")
async def unsafe_login(email: str, password: str):
"""
Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""
if not email or not password:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email and password are required"
)
auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email},
"tokens": {
"access_token": auth_result["access_token"],
"refresh_token": auth_result["refresh_token"]
}
}
🧰 Tools
🪛 Ruff (0.13.1)

28-28: PEP 484 prohibits implicit Optional

Convert to Optional[T]

(RUF013)


28-28: PEP 484 prohibits implicit Optional

Convert to Optional[T]

(RUF013)

🤖 Prompt for AI Agents
In app/auth/routes.py around lines 27 to 40, the unsafe_login GET endpoint
exposes credentials via query params, echoes plaintext passwords, lacks input
validation and protections—remove this endpoint or convert it to a secure POST
login that accepts credentials in the request body; validate email and password
(non-empty, proper email format, password length), do not return or log the
password (remove the "echo" field), call firebase_auth.sign_in_user only after
validation, return only tokens and minimal user info, and ensure rate
limiting/CSRF protections are applied (or simply delete this test endpoint and
reuse the existing secure /auth/login POST implementation at lines 76-97).

@visz11
Copy link
Author

visz11 commented Oct 8, 2025

/refacto-visz

@refacto-visz
Copy link

refacto-visz bot commented Oct 8, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Oct 8, 2025

Multi-Domain Review: Authentication Security

📁 Selected files for review (2)
  • app/auth/routes.py
  • app/auth/firebase_auth.py
🎯 Custom Instructions
✅ Applied Instructions
Organization Guidelines
  • Reuse code wherever possible and avoid redundant code by refactoring with utils and static method across application

Scope: All files

❌ Unapplied Instructions
portal-backend

Reason: Repository 'portal-backend' does not match current PR repository

refacto-api

Reason: Repository 'refacto-api' does not match current PR repository

mypy

Reason: Repository 'mypy' does not match current PR repository

bazel

Reason: Repository 'bazel' does not match current PR repository

devd-client

Reason: Repository 'devd-client' does not match current PR repository

Repository Guidelines (Path Mismatch)

Reason: Your set path patterns [app/auth/models.py] don't match any selected files for review

📝 Additional Comments
app/auth/routes.py (1)
Business Logic Controller

Authentication business logic implemented directly in controller violating separation of concerns. Reduces testability and increases coupling between presentation and business layers.

Standards:

  • SOLID-SRP
  • Clean-Architecture
  • MVC-Pattern

Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Copy link

Choose a reason for hiding this comment

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

Missing Error Handling

Authentication call lacks exception handling causing uncontrolled failures. Service crashes expose internal errors and create denial of service conditions. Degrades system reliability.

Standards
  • ISO-25010-Reliability
  • SRE-ErrorHandling

def __init__(self):
self._initialize_firebase()
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
Copy link

Choose a reason for hiding this comment

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

Hardcoded JWT Secret

JWT secret is hardcoded in source code enabling token forgery attacks. Attackers can generate valid tokens bypassing authentication. This compromises entire authentication system.

        self.jwt_secret = os.getenv("JWT_SECRET")
        if not self.jwt_secret:
            raise ValueError("JWT_SECRET environment variable must be set")
Commitable Suggestion
Suggested change
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
self.jwt_secret = os.getenv("JWT_SECRET")
if not self.jwt_secret:
raise ValueError("JWT_SECRET environment variable must be set")
Standards
  • CWE-798
  • OWASP-A02
  • NIST-SSDF

router = APIRouter(prefix="/auth", tags=["authentication"])


@router.get("/debug/secret")
Copy link

Choose a reason for hiding this comment

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

Secret Exposure Endpoint

Debug endpoint exposes JWT secret via HTTP response. Attackers can retrieve secret and forge authentication tokens. Creates complete authentication bypass vulnerability.

# Remove the entire debug_secret endpoint or replace with a safe alternative:
@router.get("/debug/health")
async def debug_health():
    """
    Safe endpoint for checking authentication service health.
    """
    
    return {"status": "healthy", "timestamp": datetime.now().isoformat()}
Commitable Suggestion
Suggested change
@router.get("/debug/secret")
# Remove the entire debug_secret endpoint or replace with a safe alternative:
@router.get("/debug/health")
async def debug_health():
"""
Safe endpoint for checking authentication service health.
"""
return {"status": "healthy", "timestamp": datetime.now().isoformat()}
Standards
  • CWE-200
  • OWASP-A01
  • CWE-532


auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
Copy link

Choose a reason for hiding this comment

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

Password Echo Vulnerability

Plain text password returned in API response enabling credential harvesting. Passwords logged in access logs and exposed to client-side attacks. Violates credential protection principles.

        "tokens": {
            "access_token": auth_result["access_token"],
            "refresh_token": auth_result["refresh_token"]
Commitable Suggestion
Suggested change
"echo": {"email": email, "password": password},
"tokens": {
"access_token": auth_result["access_token"],
"refresh_token": auth_result["refresh_token"]
Standards
  • CWE-256
  • OWASP-A02
  • CWE-532



@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
Copy link

Choose a reason for hiding this comment

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

Missing Input Validation

No validation on authentication parameters allowing null/malformed inputs. Enables injection attacks and authentication bypass attempts. Business logic executed without input sanitization.

@router.post("/login")
async def login(credentials: UserLoginRequest):
    """
    Secure login endpoint with proper validation.
    """
    if not credentials.email or not credentials.password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Email and password are required"
        )
    
    try:
        auth_result = await firebase_auth.sign_in_user(
            email=credentials.email,
            password=credentials.password
        )
        return {
            "tokens": {
                "access_token": auth_result["access_token"],
                "refresh_token": auth_result["refresh_token"]
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication failed"
        )
Commitable Suggestion
Suggested change
async def unsafe_login(email: str = None, password: str = None):
@router.post("/login")
async def login(credentials: UserLoginRequest):
"""
Secure login endpoint with proper validation.
"""
if not credentials.email or not credentials.password:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email and password are required"
)
try:
auth_result = await firebase_auth.sign_in_user(
email=credentials.email,
password=credentials.password
)
return {
"tokens": {
"access_token": auth_result["access_token"],
"refresh_token": auth_result["refresh_token"]
}
}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication failed"
)
Standards
  • CWE-20
  • OWASP-A03
  • CWE-287

@visz11
Copy link
Author

visz11 commented Oct 8, 2025

/refacto-visz

1 similar comment
@visz11
Copy link
Author

visz11 commented Oct 8, 2025

/refacto-visz

@refacto-visz
Copy link

refacto-visz bot commented Oct 8, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Oct 8, 2025

Multi-Domain Review: Authentication

📁 Selected files for review (2)
  • app/auth/routes.py
  • app/auth/firebase_auth.py
🎯 Custom Instructions
✅ Applied Instructions
Organization Guidelines
  • Reuse code wherever possible and avoid redundant code by refactoring with utils and static method across application

Scope: All files

❌ Unapplied Instructions
portal-backend

Reason: Repository 'portal-backend' does not match current PR repository

refacto-api

Reason: Repository 'refacto-api' does not match current PR repository

mypy

Reason: Repository 'mypy' does not match current PR repository

bazel

Reason: Repository 'bazel' does not match current PR repository

devd-client

Reason: Repository 'devd-client' does not match current PR repository

Repository Guidelines (Path Mismatch)

Reason: Your set path patterns [app/auth/models.py] don't match any selected files for review

📝 Additional Comments
app/auth/routes.py (2)
Business Logic Controller

Authentication logic embedded in controller violates separation of concerns. Business logic should reside in service layer enabling proper testing and reuse.

Standards:

  • SOLID-SRP
  • Clean-Architecture
Remove Debug Endpoint

Debug endpoint marked as intentional violation must be removed before production deployment. Secret exposure creates immediate security breach requiring cleanup.

Standards:

  • CWE-489
  • OWASP-A05

Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Copy link

Choose a reason for hiding this comment

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

Missing Error Handling

Authentication call lacks exception handling causing uncontrolled error propagation. Service failures expose internal error details and crash the endpoint unexpectedly.

Standards
  • ISO-25010-Reliability
  • SRE-ErrorHandling

@visz11
Copy link
Author

visz11 commented Oct 8, 2025

/refacto-visz

@refacto-visz
Copy link

refacto-visz bot commented Oct 8, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Oct 8, 2025

📁 Selected files for review (2)
  • app/auth/routes.py
  • app/auth/firebase_auth.py
🎯 Custom Instructions
✅ Applied Instructions
Organization Guidelines
  • Reuse code wherever possible and avoid redundant code by refactoring with utils and static method across application

Scope: All files

❌ Unapplied Instructions
portal-backend

Reason: Repository 'portal-backend' does not match current PR repository

refacto-api

Reason: Repository 'refacto-api' does not match current PR repository

mypy

Reason: Repository 'mypy' does not match current PR repository

bazel

Reason: Repository 'bazel' does not match current PR repository

devd-client

Reason: Repository 'devd-client' does not match current PR repository

Repository Guidelines (Path Mismatch)

Reason: Your set path patterns [app/auth/models.py] don't match any selected files for review

📝 Additional Comments
app/auth/routes.py (2)
Business Logic Controller

Authentication logic embedded directly in controller violates separation of concerns. Makes testing difficult, reduces reusability, and couples business rules to HTTP layer.

Standards:

  • SOLID-SRP
  • Clean-Architecture
  • MVC-Pattern
Remove Debug Endpoints

Debug endpoint marked as intentional violation must be removed before production deployment. Provides direct access to cryptographic secrets compromising entire authentication system.

Standards:

  • OWASP-A05
  • CWE-489
  • NIST-SSDF

Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Copy link

Choose a reason for hiding this comment

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

Missing Exception Handling

Firebase authentication call lacks exception handling for invalid credentials or service failures. Unhandled exceptions cause 500 errors exposing internal stack traces and degrading user experience.

Standards
  • ISO-25010-Reliability
  • SRE-ErrorHandling

def __init__(self):
self._initialize_firebase()
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
Copy link

Choose a reason for hiding this comment

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

Hardcoded JWT Secret

JWT secret hardcoded in source code enables token forgery by anyone with code access. Attackers can generate valid tokens bypassing authentication entirely, leading to complete system compromise.

        self.jwt_secret = os.getenv("JWT_SECRET")
        if not self.jwt_secret:
            raise ValueError("JWT_SECRET environment variable must be set")
Commitable Suggestion
Suggested change
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
self.jwt_secret = os.getenv("JWT_SECRET")
if not self.jwt_secret:
raise ValueError("JWT_SECRET environment variable must be set")
Standards
  • CWE-798
  • OWASP-A07
  • NIST-SSDF

router = APIRouter(prefix="/auth", tags=["authentication"])


@router.get("/debug/secret")
Copy link

Choose a reason for hiding this comment

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

Secret Exposure Endpoint

Debug endpoint exposes JWT secret via HTTP response. Any authenticated user can retrieve the secret and forge tokens for privilege escalation or impersonation attacks.

# Remove the entire debug_secret endpoint or replace with safe alternative:
@router.get("/debug/health")
async def debug_health():
    """
    Safe endpoint for health checking.
    """
    
    return {"status": "healthy"}
Commitable Suggestion
Suggested change
@router.get("/debug/secret")
# Remove the entire debug_secret endpoint or replace with safe alternative:
@router.get("/debug/health")
async def debug_health():
"""
Safe endpoint for health checking.
"""
return {"status": "healthy"}
Standards
  • CWE-200
  • OWASP-A01
  • CWE-532


auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
Copy link

Choose a reason for hiding this comment

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

Password Echo Vulnerability

Plaintext password returned in API response creates credential exposure risk. Passwords logged in access logs, cached by proxies, or stored in client applications enable credential theft.

        "user": {"email": email},
Commitable Suggestion
Suggested change
"echo": {"email": email, "password": password},
"user": {"email": email},
Standards
  • CWE-532
  • OWASP-A09
  • CWE-200



@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
Copy link

Choose a reason for hiding this comment

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

Missing Input Validation

Query parameters accepted without validation allowing None values or malicious input. Enables injection attacks, authentication bypass attempts, and service disruption through malformed requests.

@router.post("/login")
async def login(credentials: UserLoginRequest):
    """
    Secure login endpoint using request body validation.
    """
    if not credentials.email or not credentials.password:
        raise HTTPException(status_code=400, detail="Email and password are required")
    
    auth_result = await firebase_auth.sign_in_user(email=credentials.email, password=credentials.password)
Commitable Suggestion
Suggested change
async def unsafe_login(email: str = None, password: str = None):
@router.post("/login")
async def login(credentials: UserLoginRequest):
"""
Secure login endpoint using request body validation.
"""
if not credentials.email or not credentials.password:
raise HTTPException(status_code=400, detail="Email and password are required")
auth_result = await firebase_auth.sign_in_user(email=credentials.email, password=credentials.password)
Standards
  • CWE-20
  • OWASP-A03
  • CWE-287

@visz11
Copy link
Author

visz11 commented Oct 9, 2025

/refacto-visz

Comment on lines +18 to +24
@router.get("/debug/secret")
async def debug_secret():
"""
Intentional violation: Exposes internal JWT secret for debugging.
"""

return {"jwt_secret": firebase_auth.jwt_secret}
Copy link

Choose a reason for hiding this comment

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

Secret Exposure Endpoint

Debug endpoint exposes JWT secret via HTTP response allowing any client to retrieve authentication keys. This enables complete authentication system compromise through token forgery and impersonation attacks.

Standards
  • CWE-200
  • OWASP-A01
  • CWE-532


auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
Copy link

Choose a reason for hiding this comment

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

Password Echo Vulnerability

Plain text password returned in API response enabling credential exposure through logs, network monitoring, and client-side storage. This violates fundamental security principles and enables credential theft.

        "user": {"email": email},
Commitable Suggestion
Suggested change
"echo": {"email": email, "password": password},
"user": {"email": email},
Standards
  • CWE-200
  • OWASP-A02
  • CWE-319

Comment on lines +28 to +33
async def unsafe_login(email: str = None, password: str = None):
"""
Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Copy link

Choose a reason for hiding this comment

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

Missing Input Validation

Authentication endpoint accepts None values for credentials without validation enabling null pointer exceptions and authentication bypass attempts. Unvalidated input can cause application crashes and security vulnerabilities.

async def unsafe_login(email: str, password: str):
    """
    Intentional violation: Uses unvalidated query params and performs business logic in controller.
    """
    
    if not email or not password:
        raise HTTPException(status_code=400, detail="Email and password are required")
    
    auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Commitable Suggestion
Suggested change
async def unsafe_login(email: str = None, password: str = None):
"""
Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""
auth_result = await firebase_auth.sign_in_user(email=email, password=password)
async def unsafe_login(email: str, password: str):
"""
Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""
if not email or not password:
raise HTTPException(status_code=400, detail="Email and password are required")
auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Standards
  • CWE-20
  • OWASP-A03
  • CWE-476

@visz11
Copy link
Author

visz11 commented Oct 9, 2025

/refacto-visz

@refacto-visz
Copy link

refacto-visz bot commented Oct 9, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Oct 9, 2025

📌 Files Processed
  • app/auth/firebase_auth.py
  • app/auth/routes.py
📝 Additional Comments
app/auth/routes.py (2)
Business Logic Controller

Authentication business logic embedded in controller violates separation of concerns. Direct service calls in route handlers reduce testability and reusability while increasing coupling between layers.

Standards:

  • SOLID-SRP
  • Clean-Architecture
  • MVC-Pattern
Remove Debug Endpoints

Debug and unsafe endpoints must be removed before production deployment. These endpoints create significant security vulnerabilities and should never be exposed in production environments.

Standards:

  • OWASP-A05
  • CWE-489
  • Security-DevOps

Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Copy link

Choose a reason for hiding this comment

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

Unhandled Authentication Exceptions

Authentication service call lacks exception handling causing uncontrolled error propagation. Failed authentication attempts result in 500 errors instead of proper 401 responses, breaking client error handling.

Standards
  • ISO-25010-Reliability
  • SRE-ErrorHandling

def __init__(self):
self._initialize_firebase()
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
Copy link

Choose a reason for hiding this comment

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

Hardcoded JWT Secret

JWT secret hardcoded in source code enables token forgery by anyone with code access. Attackers can generate valid tokens bypassing authentication entirely, leading to complete system compromise.

        self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
Commitable Suggestion
Suggested change
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
Standards
  • CWE-798
  • OWASP-A02
  • CWE-321

Comment on lines +18 to +24
@router.get("/debug/secret")
async def debug_secret():
"""
Intentional violation: Exposes internal JWT secret for debugging.
"""

return {"jwt_secret": firebase_auth.jwt_secret}
Copy link

Choose a reason for hiding this comment

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

Secret Exposure Endpoint

Debug endpoint exposes JWT secret via HTTP response enabling complete authentication bypass. Any user can retrieve the secret and forge valid tokens for privilege escalation.

Standards
  • CWE-200
  • OWASP-A01
  • CWE-532


auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
Copy link

Choose a reason for hiding this comment

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

Password Exposure Response

Plain text password returned in API response creates credential exposure risk. Passwords logged in server logs, network traffic, or client storage enable account takeover attacks.

        "echo": {"email": email},
Commitable Suggestion
Suggested change
"echo": {"email": email, "password": password},
"echo": {"email": email},
Standards
  • CWE-532
  • OWASP-A02
  • CWE-319



@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
Copy link

Choose a reason for hiding this comment

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

Missing Input Validation

Query parameters accepted without validation enabling injection attacks and malformed data processing. Null values passed to authentication service may cause exceptions or bypass security checks.

async def unsafe_login(email: str, password: str):
    if not email or not password:
        raise HTTPException(status_code=400, detail="Email and password are required")
Commitable Suggestion
Suggested change
async def unsafe_login(email: str = None, password: str = None):
async def unsafe_login(email: str, password: str):
if not email or not password:
raise HTTPException(status_code=400, detail="Email and password are required")
Standards
  • CWE-20
  • OWASP-A03
  • CWE-79

@visz11
Copy link
Author

visz11 commented Oct 9, 2025

/refacto-visz

@refacto-visz
Copy link

refacto-visz bot commented Oct 9, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Oct 9, 2025

📌 Files Processed
  • app/auth/firebase_auth.py
  • app/auth/routes.py
📝 Additional Comments
app/auth/routes.py (1)
Remove Debug Endpoint

Debug endpoint marked as intentional violation must be removed before production deployment. Temporary debugging code creates permanent security vulnerabilities if forgotten during release cycles.

Standards:

  • OWASP-A05
  • CWE-489
app/auth/firebase_auth.py (1)
Environment Secret Configuration

Restore environment-based secret management replacing hardcoded value. Proper secret management prevents source code exposure and enables secure deployment practices across environments.

Standards:

  • OWASP-A02
  • CWE-798
  • NIST-SSDF

Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Copy link

Choose a reason for hiding this comment

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

Unhandled Authentication Exceptions

Firebase authentication call lacks exception handling causing service crashes on invalid credentials or network failures. Unhandled exceptions propagate to users exposing internal system details.

Standards
  • ISO-25010-Reliability
  • CWE-248

Comment on lines +33 to +34
auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
Copy link

Choose a reason for hiding this comment

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

Business Logic Controller

Controller performs authentication business logic violating separation of concerns. Direct service calls in routes create tight coupling making testing difficult and violating clean architecture principles.

Standards
  • SOLID-SRP
  • Clean-Architecture
  • MVC-Pattern

def __init__(self):
self._initialize_firebase()
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
Copy link

Choose a reason for hiding this comment

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

Hardcoded JWT Secret

JWT secret hardcoded in source code enables token forgery by anyone with code access. Attackers can generate valid tokens bypassing authentication entirely, leading to complete system compromise.

        self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
Commitable Suggestion
Suggested change
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
Standards
  • CWE-798
  • OWASP-A02
  • CWE-321

Comment on lines +18 to +24
@router.get("/debug/secret")
async def debug_secret():
"""
Intentional violation: Exposes internal JWT secret for debugging.
"""

return {"jwt_secret": firebase_auth.jwt_secret}
Copy link

Choose a reason for hiding this comment

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

Secret Exposure Endpoint

Debug endpoint exposes JWT secret via HTTP response enabling remote token forgery. Any network observer or log system captures the secret, allowing complete authentication bypass.

Standards
  • CWE-200
  • OWASP-A01
  • CWE-532


auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
Copy link

Choose a reason for hiding this comment

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

Password Echo Vulnerability

Plain text password returned in API response enables credential harvesting via logs, network monitoring, or browser history. Passwords exposed to multiple attack vectors including MITM attacks.

        "user": {"email": email},
Commitable Suggestion
Suggested change
"echo": {"email": email, "password": password},
"user": {"email": email},
Standards
  • CWE-200
  • CWE-319
  • OWASP-A02



@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
Copy link

Choose a reason for hiding this comment

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

Missing Input Validation

Authentication endpoint accepts None values for credentials enabling null pointer attacks and authentication bypass. Missing validation allows malformed requests to reach business logic causing unpredictable behavior.

async def unsafe_login(email: str, password: str):
    if not email or not password:
        raise HTTPException(status_code=400, detail="Email and password are required")
Commitable Suggestion
Suggested change
async def unsafe_login(email: str = None, password: str = None):
async def unsafe_login(email: str, password: str):
if not email or not password:
raise HTTPException(status_code=400, detail="Email and password are required")
Standards
  • CWE-20
  • CWE-287
  • OWASP-A07

@visz11
Copy link
Author

visz11 commented Oct 9, 2025

/refacto-visz

@refacto-visz
Copy link

refacto-visz bot commented Oct 9, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Oct 9, 2025

📌 Files Processed
  • app/auth/firebase_auth.py
  • app/auth/routes.py
📝 Additional Comments
app/auth/routes.py (2)
Business Logic Controller

Authentication business logic implemented directly in controller violates separation of concerns. Makes testing difficult and couples HTTP layer with authentication logic reducing maintainability.

Standards:

  • SOLID-SRP
  • Clean-Architecture
  • MVC-Pattern
Remove Debug Endpoints

Debug and unsafe endpoints must be removed before production deployment. These endpoints create critical security vulnerabilities and should never exist in production code.

Standards:

  • OWASP-A05
  • Security-Development-Lifecycle

return {"jwt_secret": firebase_auth.jwt_secret}


@router.get("/unsafe-login")
Copy link

Choose a reason for hiding this comment

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

GET Authentication Method

Authentication credentials transmitted via GET request expose passwords in URL parameters. Credentials logged in web server access logs, browser history, and referrer headers creating persistent exposure risk.

Standards
  • CWE-598
  • OWASP-A09
  • RFC-7231

Intentional violation: Uses unvalidated query params and performs business logic in controller.
"""

auth_result = await firebase_auth.sign_in_user(email=email, password=password)
Copy link

Choose a reason for hiding this comment

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

Missing Exception Handling

Authentication call lacks exception handling causing uncontrolled failures. Invalid credentials or service errors result in 500 responses instead of proper error handling degrading user experience.

Standards
  • ISO-25010-Reliability
  • RFC-7807

def __init__(self):
self._initialize_firebase()
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
Copy link

Choose a reason for hiding this comment

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

Hardcoded JWT Secret

JWT secret hardcoded in source code enables token forgery by anyone with code access. Attackers can generate valid tokens bypassing authentication entirely, compromising all user accounts.

        self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
Commitable Suggestion
Suggested change
self.jwt_secret = "DEMO_HARDCODED_JWT_SECRET_123"
self.jwt_secret = os.getenv("JWT_SECRET", "your-secret-key")
Standards
  • CWE-798
  • OWASP-A02
  • CWE-321

Comment on lines +18 to +24
@router.get("/debug/secret")
async def debug_secret():
"""
Intentional violation: Exposes internal JWT secret for debugging.
"""

return {"jwt_secret": firebase_auth.jwt_secret}
Copy link

Choose a reason for hiding this comment

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

Secret Exposure Endpoint

Debug endpoint exposes JWT secret via HTTP response enabling complete authentication bypass. Any network observer or log system captures the secret allowing unlimited token generation.

Standards
  • CWE-200
  • OWASP-A01
  • CWE-532


auth_result = await firebase_auth.sign_in_user(email=email, password=password)
return {
"echo": {"email": email, "password": password},
Copy link

Choose a reason for hiding this comment

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

Password Exposure Response

Plaintext password returned in API response creates credential exposure risk. Passwords logged in access logs, cached by proxies, or stored in client applications enabling account compromise.

        "echo": {"email": email},
Commitable Suggestion
Suggested change
"echo": {"email": email, "password": password},
"echo": {"email": email},
Standards
  • CWE-532
  • OWASP-A09
  • CWE-200



@router.get("/unsafe-login")
async def unsafe_login(email: str = None, password: str = None):
Copy link

Choose a reason for hiding this comment

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

Missing Input Validation

Authentication endpoint accepts None values for credentials enabling bypass attempts. Missing validation allows empty or malformed inputs to reach authentication logic potentially causing exceptions or security bypasses.

async def unsafe_login(email: str, password: str):
    if not email or not password:
        raise HTTPException(status_code=400, detail="Email and password are required")
Commitable Suggestion
Suggested change
async def unsafe_login(email: str = None, password: str = None):
async def unsafe_login(email: str, password: str):
if not email or not password:
raise HTTPException(status_code=400, detail="Email and password are required")
Standards
  • CWE-20
  • OWASP-A03
  • CWE-287

@visz11 visz11 closed this Oct 9, 2025
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