diff --git a/api/agents.go b/api/agents.go index f721fb289c..e66e2553c6 100644 --- a/api/agents.go +++ b/api/agents.go @@ -21,17 +21,18 @@ type AgentRegisterRequest struct { // AgentRegisterResponse is the response from the Buildkite Agent API type AgentRegisterResponse struct { - UUID string `json:"id"` - Name string `json:"name"` - AccessToken string `json:"access_token"` - Endpoint string `json:"endpoint"` - RequestHeaders map[string]string `json:"request_headers"` - PingInterval int `json:"ping_interval"` - JobStatusInterval int `json:"job_status_interval"` - HeartbeatInterval int `json:"heartbeat_interval"` - Tags []string `json:"meta_data"` - Tracing *AgentTracing `json:"tracing,omitempty"` - Warnings []Warning `json:"warnings,omitempty"` + UUID string `json:"id"` + Name string `json:"name"` + AccessToken string `json:"access_token"` + Endpoint string `json:"endpoint"` + RequestHeaders map[string]string `json:"request_headers"` + PingInterval int `json:"ping_interval"` + JobStatusInterval int `json:"job_status_interval"` + HeartbeatInterval int `json:"heartbeat_interval"` + Tags []string `json:"meta_data"` + Tracing *AgentTracing `json:"tracing,omitempty"` + InternalTracingExporter *TracingExporter `json:"internal_tracing_exporter,omitempty"` + Warnings []Warning `json:"warnings,omitempty"` } // Warning is a message from Buildkite for the agent to show to its operator, diff --git a/api/agents_test.go b/api/agents_test.go new file mode 100644 index 0000000000..9825e5a828 --- /dev/null +++ b/api/agents_test.go @@ -0,0 +1,79 @@ +package api_test + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/buildkite/agent/v4/api" + "github.com/buildkite/agent/v4/logger" +) + +func TestRegisterIndependentInternalTracingExporter(t *testing.T) { + t.Parallel() + for _, customer := range []bool{false, true} { + t.Run(fmt.Sprint(customer), func(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + response := map[string]any{ + "id": "agent-1", + "internal_tracing_exporter": api.TracingExporter{ + Endpoint: "https://internal.example/v1/traces", Protocol: "http/protobuf", + Headers: map[string]string{"Authorization": "Bearer internal-secret"}, + }, + } + if customer { + response["tracing"] = api.AgentTracing{Backend: "opentelemetry", Exporter: &api.TracingExporter{Endpoint: "https://customer.example/v1/traces"}} + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(response); err != nil { + t.Error(err) + } + })) + defer server.Close() + logs := logger.NewBuffer() + client := api.NewClient(logs, api.Config{Endpoint: server.URL, Token: "llamas", DebugHTTP: true}) + reg, _, err := client.Register(t.Context(), &api.AgentRegisterRequest{Features: []string{"internal-otlp-tracing"}}) + if err != nil { + t.Fatal(err) + } + if exp := reg.InternalTracingExporter; exp == nil || exp.Endpoint != "https://internal.example/v1/traces" || exp.Protocol != "http/protobuf" || exp.Headers["Authorization"] != "Bearer internal-secret" { + t.Errorf("registration lost internal exporter: %+v", exp) + } + if (reg.Tracing != nil) != customer { + t.Errorf("customer tracing present = %t, want %t", reg.Tracing != nil, customer) + } + for _, message := range logs.Messages { + if strings.Contains(message, "internal-secret") || strings.Contains(message, "internal.example") { + t.Errorf("registration logged internal collector configuration: %s", message) + } + } + }) + } +} + +func TestRegisterMalformedResponseDoesNotExposeInternalExporter(t *testing.T) { + t.Parallel() + for _, status := range []int{http.StatusOK, http.StatusInternalServerError} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + w.WriteHeader(status) + _, _ = fmt.Fprint(w, `{"internal_tracing_exporter":{"endpoint":"https://internal.example/v1/traces","headers":{"Authorization":"Bearer internal-secret"}}`) + })) + defer server.Close() + client := api.NewClient(logger.Discard, api.Config{Endpoint: server.URL, Token: "llamas"}) + _, _, err := client.Register(t.Context(), &api.AgentRegisterRequest{}) + if err == nil { + t.Fatal("Register accepted malformed JSON") + } + if message := err.Error(); strings.Contains(message, "internal-secret") || strings.Contains(message, "internal.example") { + t.Errorf("registration error exposes internal configuration: %s", message) + } + }) + } +} diff --git a/api/client.go b/api/client.go index b48fd661ec..7c19f66a28 100644 --- a/api/client.go +++ b/api/client.go @@ -346,8 +346,11 @@ func newResponse(r *http.Response) *Response { // interface, the raw response body will be written to v, without attempting to // first decode it. func (c *Client) doRequest(req *http.Request, v any) (*Response, error) { + // Registration carries internal collector credentials, which must not + // appear in HTTP debug dumps, including when customer tracing is disabled. + _, registration := v.(*AgentRegisterResponse) resp, err := agenthttp.Do(c.logger, c.client, req, - agenthttp.WithDebugHTTP(c.conf.DebugHTTP), + agenthttp.WithDebugHTTP(c.conf.DebugHTTP && !registration), agenthttp.WithTraceHTTP(c.conf.TraceHTTP), ) if err != nil { @@ -359,6 +362,9 @@ func (c *Client) doRequest(req *http.Request, v any) (*Response, error) { response := newResponse(resp) if err := checkResponse(resp); err != nil { + if apiError, ok := err.(*ErrorResponse); registration && ok { + apiError.Snippet = "" + } // even though there was an error, we still return the response // in case the caller wants to inspect it further return response, err @@ -378,6 +384,9 @@ func (c *Client) doRequest(req *http.Request, v any) (*Response, error) { // failure can report what the response actually contained. head := &headWriter{limit: maxErrorBodySnippet} if err = json.NewDecoder(io.TeeReader(resp.Body, head)).Decode(v); err != nil { + if registration { + return response, newUndecodableResponseError(resp, "", err) + } return response, newUndecodableResponseError(resp, head.String(), err) } } diff --git a/api/jobs.go b/api/jobs.go index 5576fec2c4..a1a611e99d 100644 --- a/api/jobs.go +++ b/api/jobs.go @@ -31,6 +31,7 @@ type Job struct { ChunksFailedCount int `json:"chunks_failed_count"` TraceParent string `json:"traceparent"` TraceState string `json:"tracestate"` + InternalTracing bool `json:"internal_tracing"` Priority int `json:"priority"` Warnings []Warning `json:"warnings,omitempty"` } diff --git a/api/jobs_test.go b/api/jobs_test.go index be1b2d8a05..d0576e3936 100644 --- a/api/jobs_test.go +++ b/api/jobs_test.go @@ -13,6 +13,41 @@ import ( "github.com/buildkite/agent/v4/logger" ) +func TestAcceptAndAcquireInternalTracing(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + payload string + want bool + }{ + {`{"id":"job-1","internal_tracing":true}`, true}, + {`{"id":"job-1","internal_tracing":false}`, false}, + {`{"id":"job-1"}`, false}, + } { + t.Run(tc.payload, func(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, tc.payload) + })) + defer server.Close() + client := api.NewClient(logger.Discard, api.Config{Endpoint: server.URL, Token: "llamas"}) + accepted, _, err := client.AcceptJob(t.Context(), "job-1") + if err != nil { + t.Fatal(err) + } + acquired, _, err := client.AcquireJob(t.Context(), "job-1") + if err != nil { + t.Fatal(err) + } + for _, job := range []*api.Job{accepted, acquired} { + if job.InternalTracing != tc.want { + t.Errorf("job internal tracing = %t, want %t", job.InternalTracing, tc.want) + } + } + }) + } +} + func TestJobURL(t *testing.T) { const buildURL = "https://buildkite.com/my-org/my-pipeline/builds/42" const jobID = "b078e2d2-86e9-4c12-bf3b-612a8058d0a4"