Skip to content

fix: handle missing name fields and GitHub API errors in social auth - #173

Merged
amirasaran merged 2 commits into
mainfrom
seer/fix-social-auth-error-handling
Nov 9, 2025
Merged

amirasaran merged 2 commits into
mainfrom
seer/fix-social-auth-error-handling

Conversation

@seer-by-sentry

@seer-by-sentry seer-by-sentry Bot commented Nov 9, 2025 •

Copy link
Copy Markdown
Contributor

User description

Description

Fixes BACKEND-P. The issue was that: GitHub OAuth response with 200 status and error payload causes KeyError: 'access_token' due to missing key validation.

  • Modified Google and Facebook social auth to use .get() when accessing given_name and family_name from the API response, preventing errors when these fields are missing.
  • Added error handling for GitHub social auth to check for an error key in the response body and to ensure that the access_token is present before proceeding.

This fix was generated by Seer in Sentry, triggered by AmirMohsen Asaran Ghomi. 👁️ Run ID: 43128

Not quite right? Click here to continue debugging with Seer.

Related Issue

Fixes BACKEND-P

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

UI Changes

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published

Auto-created Ticket

#178

PR Type

Bug fix


Description

  • Add error handling for GitHub OAuth response with error payload

  • Use .get() for optional name fields in Google/Facebook auth

  • Prevent KeyError when accessing missing API response fields

  • Validate access_token presence before GitHub API calls


Diagram Walkthrough

flowchart LR
  A["Social Auth Response"] --> B{"Check for errors"}
  B -->|Error present| C["Return None"]
  B -->|No error| D{"Validate required fields"}
  D -->|Missing fields| E["Return None"]
  D -->|Fields present| F["Create/Get User"]
Loading

File Walkthrough

Relevant files
Bug fix
services.py
Add error handling and safe field access in OAuth               

backend/user/services.py

  • Modified Google OAuth authenticator to use .get() for optional
    given_name and family_name fields
  • Modified Google ID token authenticator to use .get() for optional
    given_name and family_name fields
  • Added error checking in GitHub OAuth authenticator to detect error
    responses
  • Added validation to ensure access_token exists before using it in
    GitHub API calls
+11/-3   

@sentry

sentry Bot commented Nov 9, 2025

Copy link
Copy Markdown

🔍 Existing Issues For Review

Your pull request is modifying functions with the following pre-existing issues:

📄 File: backend/user/services.py

Function Unhandled Issue
authenticate KeyError: 'family_name' /api/v1/user/auth/oauth/
Event Count: 4
authenticate KeyError: 'access_token' /api/v1/user/auth/oauth/
Event Count: 2

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Nov 9, 2025
@qodo-code-review

qodo-code-review Bot commented Nov 9, 2025 •

Copy link
Copy Markdown
Contributor

PR Compliance Guide 🔍

(Compliance updated until commit 80e7d32)

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
⚪
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

⚪
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing audit logs: New social auth flows handle errors and user retrieval but add no logging of critical
authentication events, making audit reconstruction uncertain.

Referred Code
    def authenticate(self, token):
        try:
            response = requests.get(
                "https://www.googleapis.com/oauth2/v3/userinfo",
                headers={"Authorization": f"Bearer {token}"},
            )
            response.raise_for_status()
            data = response.json()
            return self.get_or_create_user(
                data["email"], data.get("given_name"), data.get("family_name")
            )
        except requests.RequestException:
            return None


class GoogleSigninButtonService(AbsractOAuth2Service):
    def authenticate(self, token):
        try:
            response = requests.get(
                "https://oauth2.googleapis.com/tokeninfo", params={"id_token": token}
            )


 ... (clipped 34 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Silent None returns: The code returns None on RequestException or missing GitHub access_token without logging
context, which may hinder debugging and misses some edge-case detail.

Referred Code
            )
        except requests.RequestException:
            return None


class GoogleSigninButtonService(AbsractOAuth2Service):
    def authenticate(self, token):
        try:
            response = requests.get(
                "https://oauth2.googleapis.com/tokeninfo", params={"id_token": token}
            )
            response.raise_for_status()
            data = response.json()
            return self.get_or_create_user(
                data["email"], data.get("given_name"), data.get("family_name")
            )
        except requests.RequestException:
            return None


class GithubOAuthService(AbsractOAuth2Service):


 ... (clipped 19 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Token presence check: GitHub flow now validates access_token presence, but Google flows still assume email
exists and there is no explicit validation or sanitization of external response fields.

Referred Code
            return self.get_or_create_user(
                data["email"], data.get("given_name"), data.get("family_name")
            )
        except requests.RequestException:
            return None


class GoogleSigninButtonService(AbsractOAuth2Service):
    def authenticate(self, token):
        try:
            response = requests.get(
                "https://oauth2.googleapis.com/tokeninfo", params={"id_token": token}
            )
            response.raise_for_status()
            data = response.json()
            return self.get_or_create_user(
                data["email"], data.get("given_name"), data.get("family_name")
            )
        except requests.RequestException:
            return None



 ... (clipped 26 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

Previous compliance checks

Compliance check up to commit 404ef29
Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🟢
🎫 #178
🟢 Use optional access for profile name fields to handle missing given_name and family_name
without errors.
Detect GitHub OAuth responses that contain an error field and treat them as authentication
failures.
Validate that an access_token exists before making GitHub user email lookup calls.
On upstream request or payload issues, return a safe non-authenticated result (e.g., None)
instead of raising.
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

⚪
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing audit logs: New authentication flows return None on errors without adding audit logging of the failed
auth attempts or outcomes, which may hinder reconstructing events.

Referred Code
# Check if GitHub returned an error in the response body
if "error" in data:
    return None

access_token = data.get("access_token")
if not access_token:
    return None

Learn more about managing compliance generic rules or creating your own custom rules

Compliance check up to commit 404ef29
Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
⚪
🎫 No ticket provided
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

⚪
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing audit logs: Newly added authentication flows handle errors and user creation but add no logging of
critical auth actions (success/failure), making audit trails unclear.

Referred Code
# Check if GitHub returned an error in the response body
if "error" in data:
    return None

access_token = data.get("access_token")
if not access_token:
    return None

Learn more about managing compliance generic rules or creating your own custom rules

  • Update

@qodo-code-review

qodo-code-review Bot commented Nov 9, 2025 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
✅ Simplify redundant GitHub API error checks
Suggestion Impact:The commit removed the explicit check for an "error" key and added comments explaining that missing access_token covers error cases, matching the suggested simplification.

code diff:

-            # Check if GitHub returned an error in the response body
-            if "error" in data:
-                return None
-            
             access_token = data.get("access_token")
             if not access_token:
+                # This handles cases where GitHub returns an error in the JSON body
+                # (e.g., for an expired code) or if the token is missing for other reasons.
                 return None

Simplify the GitHub API error handling by removing the redundant check for an
error key, as checking for the absence of access_token is sufficient to cover
error conditions.

backend/user/services.py [327-333]

-# Check if GitHub returned an error in the response body
-if "error" in data:
+access_token = data.get("access_token")
+if not access_token:
+    # This handles cases where GitHub returns an error in the JSON body
+    # (e.g., for an expired code) or if the token is missing for other reasons.
     return None
 
-access_token = data.get("access_token")
-if not access_token:
-    return None
-

[Suggestion processed]

Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies that checking for the presence of an error key is redundant, as the subsequent check for access_token implicitly handles the error case, leading to more concise code.

Low
  • Update

Comment thread backend/user/services.py Outdated
Co-authored-by: qodo-merge-pro[bot] <151058649+qodo-merge-pro[bot]@users.noreply.github.com>
@amirasaran
amirasaran merged commit 2f6be75 into main Nov 9, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 2/5 size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants