Skip to content

Conversation

@coodos
Copy link
Contributor

@coodos coodos commented Nov 13, 2025

Description of change

fixes and makes the logic of running firebase more robust

Issue Number

Type of change

  • Chore (refactoring, build scripts or anything else that isn't user-facing)

How the change has been tested

Change checklist

  • I have ensured that the CI Checks pass locally
  • I have removed any unnecessary logic
  • My code is well documented
  • I have signed my commits
  • My code follows the pattern of the application
  • I have self reviewed my code

Summary by CodeRabbit

  • Bug Fixes

    • Improved error reporting and diagnostics for authentication service initialization.
    • Added alerts when webhook and watcher features may be impacted due to configuration issues.
  • Refactor

    • Enhanced credential management and fallback logic during service startup for more robust initialization.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 13, 2025

Walkthrough

The PR refactors Firebase Admin SDK initialization in the auth API to detect existing initialization via getApps(), support loading credentials from a file path with fallback to applicationDefault(), and add explicit error handling with a firebaseInitialized flag for state tracking.

Changes

Cohort / File(s) Summary
Firebase Admin SDK Initialization Refactor
platforms/blabsy-w3ds-auth-api/src/index.ts
Added getApps and fs module imports; introduced firebaseInitialized flag; restructured initialization to detect pre-existing SDK instances, load credentials from a file (with fallback to applicationDefault()), and improve error handling with warnings for initialization failures.

Sequence Diagram

sequenceDiagram
    participant App as Application Start
    participant Init as Initialization Logic
    participant Firebase as Firebase Admin SDK
    participant FileSystem as File System
    participant AppDefault as Application Default
    
    App->>Init: Start initialization
    Init->>Firebase: Check getApps()
    alt Already Initialized
        Firebase-->>Init: Apps exist
        Init->>Init: Set firebaseInitialized = true
    else Not Initialized
        Firebase-->>Init: No apps
        Init->>FileSystem: Load credentials from path
        alt File Exists & Valid
            FileSystem-->>Init: Credentials parsed
            Init->>Firebase: Initialize with credentials
            Firebase-->>Init: ✓ Initialized
            Init->>Init: Set firebaseInitialized = true
        else File Missing or Parse Error
            Init->>AppDefault: Fall back to applicationDefault()
            alt Success
                AppDefault-->>Init: Credentials available
                Init->>Firebase: Initialize
                Firebase-->>Init: ✓ Initialized
                Init->>Init: Set firebaseInitialized = true
            else Failure
                AppDefault-->>Init: ✗ Error
                Init->>Init: Log error & set firebaseInitialized = false
                Init->>Init: Log warning: Firebase disabled
            end
        end
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Verify error handling paths for file I/O and applicationDefault() failures
  • Confirm firebaseInitialized flag is used consistently throughout the codebase
  • Validate that the fallback logic order (file → applicationDefault → disabled) aligns with intended behavior

Poem

🐰 A rabbit hops through Firebase halls,
Where credentials dance and getApps() calls,
File paths tried, then defaults blessed,
Init flags proudly put to test! 🔥

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description follows the template structure but lacks critical details: no issue number provided, testing approach is empty, and all checklist items remain unchecked without verification. Add the issue number, describe how changes were tested (unit tests, integration tests, etc.), and confirm or uncheck the checklist items based on actual completion status.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change: making Firebase initialization more robust with improved error handling and fallback logic.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/fix-blabsy-auth-issue

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.

@coodos coodos merged commit 9d2c182 into main Nov 13, 2025
3 of 4 checks passed
@coodos coodos deleted the chore/fix-blabsy-auth-issue branch November 13, 2025 11:36
Copy link
Contributor

@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: 1

🧹 Nitpick comments (3)
platforms/blabsy-w3ds-auth-api/src/index.ts (3)

41-41: Redundant truthiness check.

Since we're inside the else if block from Line 37 where credentialsPath is guaranteed to be truthy, the first part of this condition is redundant.

Apply this diff to simplify:

-        if (credentialsPath && fs.existsSync(credentialsPath)) {
+        if (fs.existsSync(credentialsPath)) {

42-48: Consider async file I/O for non-blocking startup.

Using fs.readFileSync blocks the event loop during startup. While acceptable for initialization code, using async alternatives (fs.promises.readFile) would align with Node.js best practices for non-blocking I/O.


37-77: Consider extracting initialization logic into a testable function.

The nested branching and try-catch blocks are functional but complex. Extracting this into a separate async function (e.g., initializeFirebase()) would improve testability, readability, and maintainability.

Example structure:

async function initializeFirebase(): Promise<boolean> {
  // Check existing initialization
  if (getApps().length > 0) {
    console.log("✅ Firebase Admin SDK already initialized");
    return true;
  }
  
  // Attempt initialization with credentials
  const credentialsPath = process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.FIREBASE_CREDENTIALS_PATH;
  if (credentialsPath) {
    return await initializeWithCredentials(credentialsPath);
  }
  
  console.warn("⚠️  Firebase credentials not configured...");
  return false;
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3f05abe and cd9dc5e.

⛔ Files ignored due to path filters (1)
  • infrastructure/eid-wallet/src-tauri/gen/android/.idea/kotlinc.xml is excluded by !**/gen/**
📒 Files selected for processing (1)
  • platforms/blabsy-w3ds-auth-api/src/index.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: lint
🔇 Additional comments (5)
platforms/blabsy-w3ds-auth-api/src/index.ts (5)

7-8: LGTM! Appropriate imports for robust initialization.

The addition of getApps and fs supports the enhanced initialization logic with proper checks for existing Firebase instances and file-based credential loading.


31-31: LGTM! Explicit state tracking improves clarity.

The firebaseInitialized flag provides clear state management for Firebase initialization status, which is useful for the final guard check and potential future conditional logic.


34-36: LGTM! Proper check prevents re-initialization.

Using getApps().length > 0 is the standard pattern to detect existing Firebase Admin SDK initialization and avoid re-initialization errors.


78-86: LGTM! Comprehensive error handling and graceful degradation.

The warning messages clearly communicate when Firebase features are disabled, and the error logging includes helpful context (message and stack trace) for debugging initialization failures.


32-90: Request testing details for authentication infrastructure changes.

The PR description lacks information about how these Firebase initialization changes were tested. Given that this affects authentication infrastructure and webhook/watcher features, please provide details on:

  1. How the different initialization paths (existing app, file credentials, applicationDefault, no credentials) were tested
  2. How webhook and watcher features behave when Firebase is not initialized
  3. Whether error scenarios (invalid JSON, missing file, invalid credentials) were validated

Comment on lines +88 to +90
if (!firebaseInitialized) {
console.warn("⚠️ Firebase Admin SDK not initialized. Webhook and watcher features may fail.");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify impact on webhook and watcher features when Firebase is not initialized.

The warning correctly identifies potential failures in webhook and watcher features. Ensure that these features handle the uninitialized state gracefully without crashing or exposing error details to clients.

Run the following script to check how webhook and watcher features handle Firebase dependencies:


🏁 Script executed:

#!/bin/bash
# Description: Check Firebase usage in webhook and watcher features

# Search for Firebase Admin usage in WebhookController and Web3Adapter
echo "=== Checking WebhookController for Firebase usage ==="
rg -nP --type=ts -C5 'firebase|getAuth|getFirestore' platforms/blabsy-w3ds-auth-api/src/controllers/WebhookController.ts

echo -e "\n=== Checking Web3Adapter for Firebase usage ==="
rg -nP --type=ts -C5 'firebase|getAuth|getFirestore' platforms/blabsy-w3ds-auth-api/src/web3adapter.ts

echo -e "\n=== Checking for Firebase initialization guards ==="
rg -nP --type=ts 'firebaseInitialized|getApps\(\)' platforms/blabsy-w3ds-auth-api/src/

Length of output: 1578


🏁 Script executed:

#!/bin/bash
# Check how WebhookController is instantiated and error handling in index.ts

echo "=== Full context around WebhookController instantiation ==="
rg -nP --type=ts -C10 'new WebhookController|WebhookController\(' platforms/blabsy-w3ds-auth-api/src/index.ts

echo -e "\n=== Check for try-catch around initialization ==="
rg -nP --type=ts -C8 'try|catch' platforms/blabsy-w3ds-auth-api/src/index.ts | head -50

echo -e "\n=== Find watcher feature implementations ==="
rg -nP --type=ts 'watcher|watch' platforms/blabsy-w3ds-auth-api/src/ -i

echo -e "\n=== View full index.ts around warning message (lines 85-95) ==="
sed -n '85,95p' platforms/blabsy-w3ds-auth-api/src/index.ts

Length of output: 10982


🏁 Script executed:

#!/bin/bash
# Check WebhookController and FirestoreWatcher Firebase handling

echo "=== WebhookController full constructor ==="
sed -n '80,88p' platforms/blabsy-w3ds-auth-api/src/controllers/WebhookController.ts

echo -e "\n=== FirestoreWatcher getFirestore usage ==="
rg -nP --type=ts -C5 'getFirestore' platforms/blabsy-w3ds-auth-api/src/web3adapter/watchers/firestoreWatcher.ts

echo -e "\n=== Check if getFirestore throws synchronously ==="
rg -nP --type=ts -C3 'getFirestore|new FirestoreWatcher' platforms/blabsy-w3ds-auth-api/src/web3adapter/index.ts | head -30

Length of output: 2372


Add error handling for Firebase dependencies in WebhookController and Web3Adapter instantiation.

The warning at lines 88-90 is correct but incomplete. Both WebhookController (line 102) and Web3Adapter (line 93) will crash during instantiation if Firebase is not initialized, because their constructors call getFirestore() without guards:

  • WebhookController constructor (line 84): this.db = getFirestore()
  • Web3Adapter class property (line 17): private readonly db = getFirestore()
  • FirestoreWatcher constructor (line 49): this.db = getFirestore()

These instantiations lack try-catch wrappers. The app will crash with an unhandled error instead of gracefully degrading. Either wrap instantiations in try-catch blocks or add guards to prevent getFirestore() calls when Firebase is uninitialized.

🤖 Prompt for AI Agents
platforms/blabsy-w3ds-auth-api/src/index.ts lines 88-90: the current warning
about Firebase not being initialized is insufficient because Web3Adapter
(instantiated around line 93), WebhookController (around line 102) and
FirestoreWatcher (constructor at line 49) call getFirestore() during
construction and will throw if Firebase isn't initialized; modify the file to
guard or wrap those instantiations in try-catch blocks (or check
firebaseInitialized before creating those objects) and provide safe fallbacks
(null/no-op implementations) and clear error logs so the app degrades gracefully
instead of crashing.

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.

4 participants