|
| 1 | +package telemetry |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
| 9 | + "sync/atomic" |
| 10 | + "testing" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/step-security/dev-machine-guard/internal/config" |
| 14 | + "github.com/step-security/dev-machine-guard/internal/progress" |
| 15 | +) |
| 16 | + |
| 17 | +// withEnterpriseConfig temporarily patches config to look enterprise-enabled |
| 18 | +// and points APIEndpoint at the given test server. Restores on return. |
| 19 | +func withEnterpriseConfig(t *testing.T, endpoint string) func() { |
| 20 | + t.Helper() |
| 21 | + savedKey, savedCustomer, savedEndpoint := config.APIKey, config.CustomerID, config.APIEndpoint |
| 22 | + config.APIKey = "sk-test-123" |
| 23 | + config.CustomerID = "test-customer" |
| 24 | + config.APIEndpoint = endpoint |
| 25 | + return func() { |
| 26 | + config.APIKey, config.CustomerID, config.APIEndpoint = savedKey, savedCustomer, savedEndpoint |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func TestReportRunStatus_StartedRetriesOn5xx(t *testing.T) { |
| 31 | + var calls int32 |
| 32 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 33 | + atomic.AddInt32(&calls, 1) |
| 34 | + w.WriteHeader(http.StatusInternalServerError) |
| 35 | + })) |
| 36 | + defer srv.Close() |
| 37 | + defer withEnterpriseConfig(t, srv.URL)() |
| 38 | + |
| 39 | + log := progress.NewLogger(progress.LevelInfo) |
| 40 | + reportRunStatus(context.Background(), log, "11111111-2222-4333-8444-555555555555", "dev-1", runStatusStarted, "") |
| 41 | + |
| 42 | + if got := atomic.LoadInt32(&calls); got != int32(runStatusStartedAttempts) { |
| 43 | + t.Fatalf("expected %d retries on 5xx, got %d", runStatusStartedAttempts, got) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func TestReportRunStatus_StartedStopsAfter2xx(t *testing.T) { |
| 48 | + var calls int32 |
| 49 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 50 | + atomic.AddInt32(&calls, 1) |
| 51 | + w.WriteHeader(http.StatusOK) |
| 52 | + })) |
| 53 | + defer srv.Close() |
| 54 | + defer withEnterpriseConfig(t, srv.URL)() |
| 55 | + |
| 56 | + log := progress.NewLogger(progress.LevelInfo) |
| 57 | + reportRunStatus(context.Background(), log, "11111111-2222-4333-8444-555555555555", "dev-1", runStatusStarted, "") |
| 58 | + |
| 59 | + if got := atomic.LoadInt32(&calls); got != 1 { |
| 60 | + t.Fatalf("expected exactly 1 call on 2xx, got %d", got) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +func TestReportRunStatus_DoesNotRetryOn4xx(t *testing.T) { |
| 65 | + // 4xx is terminal: validation or auth rejection; retrying cannot help. |
| 66 | + var calls int32 |
| 67 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 68 | + atomic.AddInt32(&calls, 1) |
| 69 | + w.WriteHeader(http.StatusBadRequest) |
| 70 | + })) |
| 71 | + defer srv.Close() |
| 72 | + defer withEnterpriseConfig(t, srv.URL)() |
| 73 | + |
| 74 | + log := progress.NewLogger(progress.LevelInfo) |
| 75 | + reportRunStatus(context.Background(), log, "11111111-2222-4333-8444-555555555555", "dev-1", runStatusStarted, "") |
| 76 | + |
| 77 | + if got := atomic.LoadInt32(&calls); got != 1 { |
| 78 | + t.Fatalf("expected 1 call for 4xx (no retry), got %d", got) |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +func TestReportRunStatus_FailedRetriesOn5xx(t *testing.T) { |
| 83 | + var calls int32 |
| 84 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 85 | + atomic.AddInt32(&calls, 1) |
| 86 | + w.WriteHeader(http.StatusInternalServerError) |
| 87 | + })) |
| 88 | + defer srv.Close() |
| 89 | + defer withEnterpriseConfig(t, srv.URL)() |
| 90 | + |
| 91 | + log := progress.NewLogger(progress.LevelInfo) |
| 92 | + reportRunStatus(context.Background(), log, "11111111-2222-4333-8444-555555555555", "dev-1", runStatusFailed, "boom") |
| 93 | + |
| 94 | + if got := atomic.LoadInt32(&calls); got != int32(runStatusFailedAttempts) { |
| 95 | + t.Fatalf("expected %d retries on 5xx for failed, got %d", runStatusFailedAttempts, got) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +func TestReportRunStatus_FailedIncludesErrorMessage(t *testing.T) { |
| 100 | + var gotBody map[string]string |
| 101 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 102 | + body, _ := io.ReadAll(r.Body) |
| 103 | + _ = json.Unmarshal(body, &gotBody) |
| 104 | + w.WriteHeader(http.StatusOK) |
| 105 | + })) |
| 106 | + defer srv.Close() |
| 107 | + defer withEnterpriseConfig(t, srv.URL)() |
| 108 | + |
| 109 | + log := progress.NewLogger(progress.LevelInfo) |
| 110 | + reportRunStatus(context.Background(), log, "11111111-2222-4333-8444-555555555555", "dev-1", runStatusFailed, "context deadline exceeded") |
| 111 | + |
| 112 | + if gotBody["status"] != runStatusFailed { |
| 113 | + t.Errorf("status = %q, want %q", gotBody["status"], runStatusFailed) |
| 114 | + } |
| 115 | + if gotBody["error_message"] != "context deadline exceeded" { |
| 116 | + t.Errorf("error_message = %q, want %q", gotBody["error_message"], "context deadline exceeded") |
| 117 | + } |
| 118 | + if gotBody["execution_id"] == "" { |
| 119 | + t.Errorf("execution_id missing from body: %+v", gotBody) |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +func TestReportRunStatus_SkipsSucceededAndUnknownStatus(t *testing.T) { |
| 124 | + var calls int32 |
| 125 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 126 | + atomic.AddInt32(&calls, 1) |
| 127 | + })) |
| 128 | + defer srv.Close() |
| 129 | + defer withEnterpriseConfig(t, srv.URL)() |
| 130 | + |
| 131 | + log := progress.NewLogger(progress.LevelInfo) |
| 132 | + reportRunStatus(context.Background(), log, "11111111-2222-4333-8444-555555555555", "dev-1", "succeeded", "") |
| 133 | + reportRunStatus(context.Background(), log, "11111111-2222-4333-8444-555555555555", "dev-1", "cancelled", "") |
| 134 | + |
| 135 | + if got := atomic.LoadInt32(&calls); got != 0 { |
| 136 | + t.Fatalf("expected zero HTTP calls for non-agent statuses, got %d", got) |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +func TestReportRunStatus_SkipsWhenNotEnterprise(t *testing.T) { |
| 141 | + var calls int32 |
| 142 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 143 | + atomic.AddInt32(&calls, 1) |
| 144 | + })) |
| 145 | + defer srv.Close() |
| 146 | + |
| 147 | + // Restore config after test. Default config.APIKey is the placeholder, which |
| 148 | + // makes IsEnterpriseMode return false. |
| 149 | + savedKey := config.APIKey |
| 150 | + config.APIKey = "{{API_KEY}}" |
| 151 | + defer func() { config.APIKey = savedKey }() |
| 152 | + |
| 153 | + log := progress.NewLogger(progress.LevelInfo) |
| 154 | + reportRunStatus(context.Background(), log, "11111111-2222-4333-8444-555555555555", "dev-1", runStatusStarted, "") |
| 155 | + |
| 156 | + if got := atomic.LoadInt32(&calls); got != 0 { |
| 157 | + t.Fatalf("expected zero calls when not in enterprise mode, got %d", got) |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +func TestReportRunStatus_SkipsEmptyExecutionID(t *testing.T) { |
| 162 | + var calls int32 |
| 163 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 164 | + atomic.AddInt32(&calls, 1) |
| 165 | + })) |
| 166 | + defer srv.Close() |
| 167 | + defer withEnterpriseConfig(t, srv.URL)() |
| 168 | + |
| 169 | + log := progress.NewLogger(progress.LevelInfo) |
| 170 | + reportRunStatus(context.Background(), log, "", "dev-1", runStatusStarted, "") |
| 171 | + |
| 172 | + if got := atomic.LoadInt32(&calls); got != 0 { |
| 173 | + t.Fatalf("expected zero calls when execution_id is empty, got %d", got) |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +func TestReportRunStatus_AbortsRetriesOnCtxCancel(t *testing.T) { |
| 178 | + // Server hangs — every attempt will hit the per-attempt timeout, but we |
| 179 | + // cancel the parent context mid-run to confirm retries stop. |
| 180 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 181 | + time.Sleep(runStatusHTTPTimeout + 2*time.Second) |
| 182 | + })) |
| 183 | + defer srv.Close() |
| 184 | + defer withEnterpriseConfig(t, srv.URL)() |
| 185 | + |
| 186 | + ctx, cancel := context.WithCancel(context.Background()) |
| 187 | + // Cancel after the first attempt completes (~runStatusHTTPTimeout) so we |
| 188 | + // land in the backoff select where ctx.Done wins. |
| 189 | + time.AfterFunc(runStatusHTTPTimeout+100*time.Millisecond, cancel) |
| 190 | + |
| 191 | + log := progress.NewLogger(progress.LevelInfo) |
| 192 | + done := make(chan struct{}) |
| 193 | + start := time.Now() |
| 194 | + go func() { |
| 195 | + reportRunStatus(ctx, log, "11111111-2222-4333-8444-555555555555", "dev-1", runStatusStarted, "") |
| 196 | + close(done) |
| 197 | + }() |
| 198 | + |
| 199 | + select { |
| 200 | + case <-done: |
| 201 | + elapsed := time.Since(start) |
| 202 | + // Should be close to the first-attempt timeout, well under the full |
| 203 | + // retry budget (~runStatusHTTPTimeout * runStatusStartedAttempts). |
| 204 | + budget := runStatusHTTPTimeout*2 + 500*time.Millisecond |
| 205 | + if elapsed > budget { |
| 206 | + t.Fatalf("reportRunStatus took %s, expected ≤ %s once ctx is cancelled", elapsed, budget) |
| 207 | + } |
| 208 | + case <-time.After(runStatusHTTPTimeout*int64Attempts() + 5*time.Second): |
| 209 | + t.Fatal("reportRunStatus did not return") |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +func int64Attempts() time.Duration { |
| 214 | + return time.Duration(runStatusStartedAttempts) |
| 215 | +} |
0 commit comments