|
| 1 | +package telemetry |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "compress/gzip" |
| 6 | + "context" |
| 7 | + "encoding/json" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "net/http/httptest" |
| 11 | + "strings" |
| 12 | + "sync" |
| 13 | + "testing" |
| 14 | + |
| 15 | + "github.com/step-security/dev-machine-guard/internal/config" |
| 16 | + "github.com/step-security/dev-machine-guard/internal/progress" |
| 17 | +) |
| 18 | + |
| 19 | +func TestGzipBytes_RoundTrip(t *testing.T) { |
| 20 | + original := []byte(`{"customer_id":"acme","node_projects":[{"project_path":"/x"}]}`) |
| 21 | + compressed, err := gzipBytes(original) |
| 22 | + if err != nil { |
| 23 | + t.Fatalf("gzipBytes failed: %v", err) |
| 24 | + } |
| 25 | + if len(compressed) < 2 || compressed[0] != 0x1f || compressed[1] != 0x8b { |
| 26 | + t.Fatal("expected gzip magic bytes") |
| 27 | + } |
| 28 | + |
| 29 | + gz, err := gzip.NewReader(bytes.NewReader(compressed)) |
| 30 | + if err != nil { |
| 31 | + t.Fatalf("gzip.NewReader failed: %v", err) |
| 32 | + } |
| 33 | + defer gz.Close() |
| 34 | + got, err := io.ReadAll(gz) |
| 35 | + if err != nil { |
| 36 | + t.Fatalf("decompression failed: %v", err) |
| 37 | + } |
| 38 | + if !bytes.Equal(got, original) { |
| 39 | + t.Errorf("round-trip mismatch: got %q, want %q", got, original) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func TestUploadToS3_SendsCompressedBodyAndIsCompressedFlag(t *testing.T) { |
| 44 | + var ( |
| 45 | + mu sync.Mutex |
| 46 | + uploadURLBody []byte |
| 47 | + putBody []byte |
| 48 | + putContentType string |
| 49 | + notifyBody []byte |
| 50 | + ) |
| 51 | + |
| 52 | + // Mock S3 PUT endpoint — captures the body the agent uploads. |
| 53 | + s3Server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 54 | + body, _ := io.ReadAll(r.Body) |
| 55 | + mu.Lock() |
| 56 | + putBody = body |
| 57 | + putContentType = r.Header.Get("Content-Type") |
| 58 | + mu.Unlock() |
| 59 | + w.WriteHeader(http.StatusOK) |
| 60 | + })) |
| 61 | + defer s3Server.Close() |
| 62 | + |
| 63 | + // Mock backend — handles upload-URL and process-uploaded calls. |
| 64 | + backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 65 | + switch { |
| 66 | + case strings.HasSuffix(r.URL.Path, "/telemetry/upload-url"): |
| 67 | + body, _ := io.ReadAll(r.Body) |
| 68 | + mu.Lock() |
| 69 | + uploadURLBody = body |
| 70 | + mu.Unlock() |
| 71 | + _ = json.NewEncoder(w).Encode(map[string]string{ |
| 72 | + "upload_url": s3Server.URL + "/put", |
| 73 | + "s3_key": "developer-mdm/test-customer/dev-1/123.json.gz", |
| 74 | + }) |
| 75 | + case strings.HasSuffix(r.URL.Path, "/telemetry/process-uploaded"): |
| 76 | + body, _ := io.ReadAll(r.Body) |
| 77 | + mu.Lock() |
| 78 | + notifyBody = body |
| 79 | + mu.Unlock() |
| 80 | + w.WriteHeader(http.StatusOK) |
| 81 | + default: |
| 82 | + http.NotFound(w, r) |
| 83 | + } |
| 84 | + })) |
| 85 | + defer backendServer.Close() |
| 86 | + |
| 87 | + // Override config globals for the duration of the test. |
| 88 | + origEndpoint, origCustomer, origKey := config.APIEndpoint, config.CustomerID, config.APIKey |
| 89 | + config.APIEndpoint = backendServer.URL |
| 90 | + config.CustomerID = "test-customer" |
| 91 | + config.APIKey = "test-key" |
| 92 | + defer func() { |
| 93 | + config.APIEndpoint, config.CustomerID, config.APIKey = origEndpoint, origCustomer, origKey |
| 94 | + }() |
| 95 | + |
| 96 | + payload := &Payload{ |
| 97 | + CustomerID: "test-customer", |
| 98 | + DeviceID: "dev-1", |
| 99 | + } |
| 100 | + |
| 101 | + if err := uploadToS3(context.Background(), progress.NewLogger(progress.LevelInfo), payload); err != nil { |
| 102 | + t.Fatalf("uploadToS3 failed: %v", err) |
| 103 | + } |
| 104 | + |
| 105 | + mu.Lock() |
| 106 | + defer mu.Unlock() |
| 107 | + |
| 108 | + // Upload-URL request body must include is_compressed: true. |
| 109 | + var uploadReq map[string]any |
| 110 | + if err := json.Unmarshal(uploadURLBody, &uploadReq); err != nil { |
| 111 | + t.Fatalf("failed to parse upload-URL request body: %v", err) |
| 112 | + } |
| 113 | + if uploadReq["device_id"] != "dev-1" { |
| 114 | + t.Errorf("expected device_id=dev-1, got %v", uploadReq["device_id"]) |
| 115 | + } |
| 116 | + if uploadReq["is_compressed"] != true { |
| 117 | + t.Errorf("expected is_compressed=true, got %v", uploadReq["is_compressed"]) |
| 118 | + } |
| 119 | + |
| 120 | + // PUT body must be gzip-compressed. |
| 121 | + if len(putBody) < 2 || putBody[0] != 0x1f || putBody[1] != 0x8b { |
| 122 | + t.Fatalf("expected gzip-compressed PUT body (got %d bytes)", len(putBody)) |
| 123 | + } |
| 124 | + if putContentType != "application/json" { |
| 125 | + t.Errorf("expected Content-Type application/json (matches presigned URL), got %q", putContentType) |
| 126 | + } |
| 127 | + |
| 128 | + // Decompressing the PUT body should yield the original JSON payload. |
| 129 | + gz, err := gzip.NewReader(bytes.NewReader(putBody)) |
| 130 | + if err != nil { |
| 131 | + t.Fatalf("PUT body is not valid gzip: %v", err) |
| 132 | + } |
| 133 | + defer gz.Close() |
| 134 | + decompressed, err := io.ReadAll(gz) |
| 135 | + if err != nil { |
| 136 | + t.Fatalf("failed to decompress PUT body: %v", err) |
| 137 | + } |
| 138 | + var roundTrip Payload |
| 139 | + if err := json.Unmarshal(decompressed, &roundTrip); err != nil { |
| 140 | + t.Fatalf("decompressed body is not valid JSON: %v", err) |
| 141 | + } |
| 142 | + if roundTrip.DeviceID != "dev-1" { |
| 143 | + t.Errorf("decompressed payload device_id mismatch: got %q", roundTrip.DeviceID) |
| 144 | + } |
| 145 | + |
| 146 | + // Notify-backend was called with the s3_key returned from the upload-URL endpoint. |
| 147 | + var notify map[string]string |
| 148 | + if err := json.Unmarshal(notifyBody, ¬ify); err != nil { |
| 149 | + t.Fatalf("failed to parse notify body: %v", err) |
| 150 | + } |
| 151 | + if !strings.HasSuffix(notify["s3_key"], ".json.gz") { |
| 152 | + t.Errorf("expected s3_key with .json.gz suffix, got %q", notify["s3_key"]) |
| 153 | + } |
| 154 | +} |
0 commit comments