diff --git a/pkg/auth/authenticator.go b/pkg/auth/authenticator.go index 5d74cf6..e6ad74d 100644 --- a/pkg/auth/authenticator.go +++ b/pkg/auth/authenticator.go @@ -336,10 +336,21 @@ func (a *Authenticator) checkServiceUpstreamAuth(service WebservicesCacheEntry, attribute.String("upstream-http-request-start", reqStart.Format(tracing.TimeFormat)), attribute.String("upstream-http-request-end", time.Now().Format(tracing.TimeFormat)), attribute.Float64("upstream-http-request-rtt-seconds", time.Since(reqStart).Seconds()), - attribute.Int("upstream-auth-status-code", resp.StatusCode), ) - labels := AddWithDownstreamDeadlineLabel(AddStatusLabel(nil, resp.StatusCode), hasDownstreamDeadline) - upstreamAuthRequestDuration.With(labels).Observe(reqDuration.Seconds()) + + if err != nil { + span.RecordError(err) + span.SetStatus(otelcodes.Error, err.Error()) + return CerberusReasonUpstreamAuthFailed + } + + if resp != nil { + span.SetAttributes(attribute.Int("upstream-auth-status-code", resp.StatusCode)) + labels := AddWithDownstreamDeadlineLabel(AddStatusLabel(nil, resp.StatusCode), hasDownstreamDeadline) + upstreamAuthRequestDuration.With(labels).Observe(reqDuration.Seconds()) + } else { + span.SetStatus(otelcodes.Error, "Unexpected nil response") + } if reason := processResponseError(err); reason != "" { span.RecordError(err) diff --git a/pkg/auth/authenticator_test.go b/pkg/auth/authenticator_test.go index 311e587..34c9eeb 100644 --- a/pkg/auth/authenticator_test.go +++ b/pkg/auth/authenticator_test.go @@ -1230,8 +1230,11 @@ func TestCheck_UpstreamAuthTimeout(t *testing.T) { mockHTTPClient := &http.Client{ Transport: &MockTransport{ DoFunc: func(req *http.Request) (*http.Response, error) { - // Return a simulated timeout error - return nil, &url.Error{ + return &http.Response{ + StatusCode: http.StatusInternalServerError, + Body: io.NopCloser(strings.NewReader("Internal Server Error")), + Header: make(http.Header), + }, &url.Error{ Op: "Get", URL: "http://fake-upstream-service/authenticate", Err: errors.New("timeout"), @@ -1277,6 +1280,6 @@ func TestCheck_UpstreamAuthTimeout(t *testing.T) { assert.NoError(t, err, "Expected no error from Check function itself") assert.NotNil(t, finalResponse, "Expected a non-nil response") - assert.False(t, finalResponse.Allow, "Expected the request to be denied due to upstream authentication timeout") - assert.Equal(t, CerberusReasonUpstreamAuthTimeout, finalResponse.Response.Header.Get("X-Cerberus-Reason"), "Expected reason to indicate upstream authentication timeout") + assert.False(t, finalResponse.Allow, "Expected the request to be denied due to upstream authentication failed") + assert.Equal(t, "upstream-auth-failed", finalResponse.Response.Header.Get("X-Cerberus-Reason"), "Expected reason to indicate upstream authentication failed") } \ No newline at end of file