Skip to content

Bug: Null pointer error in authenticateAndSaveCredentials when authentication fails #12

@fcakyon

Description

@fcakyon

Bug Description

There's a non-critical bug in the auth.ts file that causes a null pointer error when authentication times out or fails. I spent a bit of time understanding the issue, but now it's all fixed on my local. I appreciate the MCP tool you created!

The Problem

In the authenticateAndSaveCredentials function (around line 62-69), the code attempts to call auth.refreshAccessToken() even when auth might be null:

const auth = await authenticateWithTimeout(keyfilePath, SCOPES);
if (auth) {
  const newAuth = new google.auth.OAuth2();
  newAuth.setCredentials(auth.credentials);
}

try {
  const { credentials } = await auth.refreshAccessToken(); // ❌ Bug: auth might be null here!
  // ... rest of the code

When authenticateWithTimeout returns null (due to timeout or error), the code still tries to call auth.refreshAccessToken() outside the if (auth) block, causing a "Cannot read property 'refreshAccessToken' of null" error.

The Fix

The code should check if auth is null and handle it properly:

async function authenticateAndSaveCredentials() {
  console.error("Launching auth flow…");
  console.error("Using credentials path:", credentialsPath);

  const keyfilePath = path.join(CREDS_DIR, "gcp-oauth.keys.json");
  console.error("Using keyfile path:", keyfilePath);

  const auth = await authenticateWithTimeout(keyfilePath, SCOPES);
  
  if (!auth) {
    console.error("Authentication failed or timed out");
    return null;
  }

  try {
    const { credentials } = await auth.refreshAccessToken();
    console.error("Received new credentials with scopes:", credentials.scope);

    // Ensure directory exists before saving
    ensureCredsDirectory();

    fs.writeFileSync(credentialsPath, JSON.stringify(credentials, null, 2));
    console.error(
      "Credentials saved successfully with refresh token to:",
      credentialsPath,
    );
    auth.setCredentials(credentials);
    return auth;
  } catch (error) {
    console.error("Error refreshing token during initial auth:", error);
    return auth;
  }
}

Additional Issues

  1. The newAuth variable (lines 64-65) is created but never used - this code can be removed.
  2. The function should return early if authentication fails to prevent the null pointer error.

Steps to Reproduce

  1. Set up the mcp-gdrive server with incorrect credentials or let the authentication timeout
  2. The server will crash with a null pointer error when trying to call refreshAccessToken() on a null object

Environment

  • Error occurs when the OAuth key file (gcp-oauth.keys.json) causes authentication to fail or timeout

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions