gogoogle-cloud-platformgoogle-chat

Unauthenticated desc = transport: per-RPC creds failed due to error: credentials: cannot fetch token: compute: Received 500


I am trying to use the Google Chat API with Go in a GCP Cloud Function. Below is my code using the google.golang.org/api/chat/v1 package:

import (
    "context"
    "fmt"
    "google.golang.org/api/chat/v1"
)

func getMessage() {

    ctx := context.Background()
    c, err := chat.NewService(ctx)

    message, err := c.Spaces.Messages.Get("my id").Do()
    if err != nil {
        fmt.Printf("Error requesting message for %s: %v\n", t.Name, err)
        return
    }
}

However, when I deploy and test this function, I get the following error:

Get "https://chat.googleapis.com/v1/spaces/../messages?alt=json&prettyPrint=false": credentials: cannot fetch token: compute: Received 500 `Could not fetch URI /computeMetadata/v1/instance/service-accounts/default/token?scopes=...

I also tried the newe cloud.google.com/go/chat package, but I encountered a similar issue. Here's the code:

import (
    chat "cloud.google.com/go/chat/apiv1"
    "cloud.google.com/go/chat/apiv1/chatpb"
    "context"
    "fmt"
)

func getMessage() {

    ctx := context.Background()
    c, err := chat.NewClient(ctx)
    request := &chatpb.GetMessageRequest{
        Name: "spaces/123/messages/456",
    }
    message, err := c.GetMessage(ctx, request)
    if err != nil {
        fmt.Printf("Error requesting message for %s: %v\n", t.Name, err)
        return
    }
}

The error is:

Error requesting message for spaces/..: rpc error: code = Unauthenticated desc = transport: per-RPC creds failed due to error: credentials: cannot fetch token: compute: Received 500 `Could not fetch URI /computeMetadata/v1/instance/service-accounts/default/token?scopes=...

A similar implementation using @googleapis/chat in a Node.js Cloud Function works without any issues. I have set up the Go Cloud Function in the same way as the Node.js Cloud Function, including the service account permissions and environment configurations. Despite this, the Go implementation continues to throw the authentication error.

What might be causing the discrepancy, and how can I resolve it in the Go setup?


Solution

  • It seems the issue was caused by not specifying a scope. When no specific scope is provided, the client attempts to use all available scopes, which can potentially overwhelm Google's authentication system and result in a 500 error.

    To resolve this, we should explicitly define the scope required for my use case, as shown below:

    For the google.golang.org/api/chat/v1 package:

    c, err := chat.NewService(ctx, option.WithScopes(chat.ChatBotScope))
    

    For the cloud.google.com/go/chat package

    c, err := chat.NewClient(ctx, option.WithScopes("https://www.googleapis.com/auth/chat.bot"))