Bladeren bron

feat: limit config request body size

tags/v0.9.0
Jan Svabenik 1 maand geleden
bovenliggende
commit
6df385bd37
2 gewijzigde bestanden met toevoegingen van 22 en 1 verwijderingen
  1. +9
    -1
      internal/control/control.go
  2. +13
    -0
      internal/control/control_test.go

+ 9
- 1
internal/control/control.go Bestand weergeven

@@ -5,6 +5,7 @@ import (
"encoding/json"
"io"
"net/http"
"strings"
"sync"

"github.com/jan/fm-rds-tx/internal/audio"
@@ -49,6 +50,8 @@ type Server struct {
streamSrc *audio.StreamSource // optional, for live audio ingest
}

const maxConfigBodyBytes = 64 << 10 // 64 KiB

type ConfigPatch struct {
FrequencyMHz *float64 `json:"frequencyMHz,omitempty"`
OutputDrive *float64 `json:"outputDrive,omitempty"`
@@ -296,9 +299,14 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(cfg)
case http.MethodPost:
r.Body = http.MaxBytesReader(w, r.Body, maxConfigBodyBytes)
var patch ConfigPatch
if err := json.NewDecoder(r.Body).Decode(&patch); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
statusCode := http.StatusBadRequest
if strings.Contains(err.Error(), "http: request body too large") {
statusCode = http.StatusRequestEntityTooLarge
}
http.Error(w, err.Error(), statusCode)
return
}



+ 13
- 0
internal/control/control_test.go Bestand weergeven

@@ -133,6 +133,19 @@ func TestConfigPatch(t *testing.T) {
}
}

func TestConfigPatchRejectsOversizeBody(t *testing.T) {
srv := NewServer(cfgpkg.Default())
rec := httptest.NewRecorder()
payload := bytes.Repeat([]byte("x"), maxConfigBodyBytes+32)
body := append([]byte(`{"ps":"`), payload...)
body = append(body, []byte(`"}`)...)
req := httptest.NewRequest(http.MethodPost, "/config", bytes.NewReader(body))
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413, got %d response=%q", rec.Code, rec.Body.String())
}
}

func TestRuntimeWithoutDriver(t *testing.T) {
srv := NewServer(cfgpkg.Default())
rec := httptest.NewRecorder()


Laden…
Annuleren
Opslaan