Skip to content

Commit

Permalink
max size random data
Browse files Browse the repository at this point in the history
  • Loading branch information
mikehelmick committed Feb 16, 2021
1 parent dca4fb5 commit 4569185
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
6 changes: 4 additions & 2 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,12 @@ func (j *JSONResponder) Write(headerSize, bodySize uint64, w http.ResponseWriter
}
}

const headerDiff = contentHeaderSize + uint64(len(Header))

w.WriteHeader(http.StatusOK)
// Generate the response details.
if headerSize > contentHeaderSize {
w.Header().Add(Header, RandomData(headerSize-contentHeaderSize-uint64(len(Header))))
if headerSize > headerDiff {
w.Header().Add(Header, RandomData(headerSize-headerDiff))
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, "%s", bodyData)
Expand Down
9 changes: 9 additions & 0 deletions tracker.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
const (
Header = "X-Chaff"
DefaultCapacity = 100
MaxRandomBytes = 1000000
)

// Tracker represents the status of a latency and request size tracker.
Expand Down Expand Up @@ -158,9 +159,17 @@ func (t *Tracker) CalculateProfile() *request {
}
}

// RandomData generates size bytes of random base64 data.
func RandomData(size uint64) string {
// Account for base64 overhead
size = 3 * size / 4
if size <= 0 {
return ""
}
if size > MaxRandomBytes {
size = MaxRandomBytes
}

buffer := make([]byte, size)
_, err := rand.Read(buffer)
if err != nil {
Expand Down
17 changes: 17 additions & 0 deletions tracker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package chaff

import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
Expand All @@ -27,6 +28,22 @@ import (
"github.com/google/go-cmp/cmp"
)

func TestRandomData(t *testing.T) {
d := RandomData(0)
if d != "" {
t.Fatalf("expected empty string, got: %q", d)
}

d = RandomData(MaxRandomBytes * 2)
b, err := base64.StdEncoding.DecodeString(d)
if err != nil {
t.Fatal(err)
}
if l := len(b); l < int(float32(MaxRandomBytes)*0.99) || l > int(float32(MaxRandomBytes)*1.01) {
t.Fatalf("length is outside of 1pct of expected, want: %d got: %d", MaxRandomBytes, l)
}
}

func checkLength(t *testing.T, expected int, length int) {
t.Helper()
lower := float64(expected) * 0.99
Expand Down

0 comments on commit 4569185

Please sign in to comment.