gateway_request_invalid_json_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //go:build unit
  2. package service
  3. import (
  4. "fmt"
  5. "strings"
  6. "testing"
  7. "github.com/Wei-Shaw/sub2api/internal/domain"
  8. "github.com/stretchr/testify/require"
  9. )
  10. func TestDescribeInvalidJSON_TruncatedBody(t *testing.T) {
  11. // Simulates a body cut off mid-stream (e.g. partially consumed by middleware).
  12. body := []byte(`{"model":"claude-sonnet-4-6","messages":[{"role":"user","content":"hi`)
  13. err := DescribeInvalidJSON(body)
  14. require.Error(t, err)
  15. require.Contains(t, err.Error(), fmt.Sprintf("len=%d", len(body)))
  16. require.Contains(t, err.Error(), "unexpected end of JSON input")
  17. }
  18. func TestDescribeInvalidJSON_InvalidCharacterWithOffset(t *testing.T) {
  19. body := []byte(`{"model": bad}`)
  20. err := DescribeInvalidJSON(body)
  21. require.Error(t, err)
  22. require.Contains(t, err.Error(), "offset=11")
  23. require.Contains(t, err.Error(), "invalid character")
  24. }
  25. func TestDescribeInvalidJSON_DoesNotLeakBodyContent(t *testing.T) {
  26. secret := "sk-super-secret-value"
  27. body := []byte(`{"api_key":"` + secret + `","broken":`)
  28. err := DescribeInvalidJSON(body)
  29. require.Error(t, err)
  30. require.NotContains(t, err.Error(), secret)
  31. }
  32. func TestParseGatewayRequest_InvalidJSONErrorIsDiagnostic(t *testing.T) {
  33. body := []byte(`{"model":"claude-sonnet-4-6","messages":[`)
  34. _, err := ParseGatewayRequest(NewRequestBodyRef(body), domain.PlatformAnthropic)
  35. require.Error(t, err)
  36. require.True(t, strings.HasPrefix(err.Error(), "invalid json (len="), "error should carry diagnostics, got: %s", err.Error())
  37. }