Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions api/agents.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
79 changes: 79 additions & 0 deletions api/agents_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
11 changes: 10 additions & 1 deletion api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand All @@ -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)
}
}
Expand Down
1 change: 1 addition & 0 deletions api/jobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Expand Down
35 changes: 35 additions & 0 deletions api/jobs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down