google-api-dotnet-client icon indicating copy to clipboard operation
google-api-dotnet-client copied to clipboard

Google.Apis.Clouderrorreporting.v1beta1.ReportRequest does not appear to be recognizing service account credentials

Open mahesh-bennie opened this issue 6 years ago • 4 comments

Environment details

  • OS: Windows 10
  • .NET version: .net core 3.1
  • Package name and version: Google.Apis.Clouderrorreporting.v1beta1 v1.45.0.1952

Problem description

Working on a POC to push unhandled exceptions over to Error Reporting using the Error Reporting API by following this test example ( https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/vs2015/error-reporting/api/ErrorReportingSample.cs ). Code sample is following:

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            report(ex);                
        }
    }

    private static ClouderrorreportingService CreateErrorReportingClient()
    {
        // Get the Application Default Credentials.
        GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;

        // Add the needed scope to the credentials.
        credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);

        // Create the Error Reporting Service.
        ClouderrorreportingService service = new ClouderrorreportingService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
        });
        return service;
    }

    private static ReportRequest CreateReportRequest(Exception e)
    {
        // Create the service.
        ClouderrorreportingService service = CreateErrorReportingClient();

        // Get the project ID from the environement variables.
        string projectId = "<The Project Id>";

        // Format the project id to the format Error Reporting expects. See:
        // https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events/report
        string formattedProjectId = string.Format("projects/{0}", projectId);

        // Add a service context to the report.  For more details see:
        // https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events#ServiceContext
        ServiceContext serviceContext = new ServiceContext()
        {
            Service = "<The service Name>",
            Version = "<The version>",
        };
        ReportedErrorEvent errorEvent = new ReportedErrorEvent()
        {
            Message = e.ToString(),
            ServiceContext = serviceContext,
        };
        return new ReportRequest(service, errorEvent, formattedProjectId);
    }

    private static void report(Exception e)
    {
        // Create the report and execute the request.
        ReportRequest request = CreateReportRequest(e);
        request.Execute();
    }

That code above executes in a middleware. The credentials that get passed are the private key file belonging to one of our service accounts. Consistently getting a 401 with the following error message:

The service clouderrorreporting has thrown an exception: Google.GoogleApiException: Google.Apis.Requests.RequestError Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential

Debugging does show the credentials are flowing over from GOOGLE_APPLICATION_CREDENTIALS env variable properly so I'm not really sure what else I'm supposed to do to get this working. Any guidance would be appreciated.

mahesh-bennie avatar May 14 '20 17:05 mahesh-bennie

(Transferred to google-api-dotnet-client as that's the repository containing this package.)

jskeet avatar May 14 '20 17:05 jskeet

This is the problem, I suspect:

credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);

You're creating scoped credentials, but then ignoring them and using the unscoped credentials.

You probably want:

credential = credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);

(I'd also suggest using GoogleCredential.GetApplicationDefault() instead of using the async method and Result.)

I'd fix this sample - but it's not present in master any more anyway. The newer sample is here: https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/master/error-reporting/api/ErrorReportingSample/ErrorReportingSample.cs That uses the Google.Cloud.ErrorReporting.V1Beta1 gRPC-based package instead of the REST-like API.

jskeet avatar May 14 '20 17:05 jskeet

Awesome that worked! Would you recommend us to use the gRPC based package? Is the former using gRPC 'under the hood'? Not sure how the latter uses credentials either (assume it calls GetApplicationDefault internally?).

mahesh-bennie avatar May 14 '20 19:05 mahesh-bennie

Excellent - I'm glad it worked. But no, the Google.Apis.Clouderrorreporting.v1beta1 package uses the REST API (JSON over HTTP/1.1).

The gRPC libraries use the application default credentials by default - use a builder (ReportErrorsServiceClientBuilder) to specify alternative credentials if you need to.

I'd generally recommend the gRPC libraries as our generated API surface has come along a lot over the years. On the other hand, gRPC has a native part that can be quite large, and it's not quite as portable due to both that native portion and the use of HTTP/2. So yes, if you can use the gRPC API, I'd suggest doing so, but otherwise the REST API should be fine.

jskeet avatar May 14 '20 20:05 jskeet