Files
sub2api/backend/internal/service/gateway_request_invalid_json_test.go
T
li 40c563c4ae fix(gateway): 记录请求体解析失败的真实原因,不再吞错
400 "Failed to parse request body" 此前丢弃底层错误,无法区分
JSON 真非法、还是 body 被截断/被中间件提前消费。

- 服务层 invalid json 错误增补 len/offset/非法字符信息
  (仅诊断元数据,不含 body 内容,可安全 wrap);
- handler 层新增 logRequestBodyParseFailure,向服务端日志输出
  底层错误 + body 长度 + 转义后的 head/tail 片段(各 256B),
  客户端响应文案保持不变;
- 接入全部 9 处入站解析点(messages/count_tokens/responses/
  chat_completions/embeddings,Anthropic 与 OpenAI 网关)。

Fixes #3715
2026-07-07 13:53:39 +08:00

53 lines
1.5 KiB
Go

//go:build unit
package service
import (
"fmt"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/domain"
"github.com/stretchr/testify/require"
)
func TestDescribeInvalidJSON_TruncatedBody(t *testing.T) {
// Simulates a body cut off mid-stream (e.g. partially consumed by middleware).
body := []byte(`{"model":"claude-sonnet-4-6","messages":[{"role":"user","content":"hi`)
err := DescribeInvalidJSON(body)
require.Error(t, err)
require.Contains(t, err.Error(), fmt.Sprintf("len=%d", len(body)))
require.Contains(t, err.Error(), "unexpected end of JSON input")
}
func TestDescribeInvalidJSON_InvalidCharacterWithOffset(t *testing.T) {
body := []byte(`{"model": bad}`)
err := DescribeInvalidJSON(body)
require.Error(t, err)
require.Contains(t, err.Error(), "offset=11")
require.Contains(t, err.Error(), "invalid character")
}
func TestDescribeInvalidJSON_DoesNotLeakBodyContent(t *testing.T) {
secret := "sk-super-secret-value"
body := []byte(`{"api_key":"` + secret + `","broken":`)
err := DescribeInvalidJSON(body)
require.Error(t, err)
require.NotContains(t, err.Error(), secret)
}
func TestParseGatewayRequest_InvalidJSONErrorIsDiagnostic(t *testing.T) {
body := []byte(`{"model":"claude-sonnet-4-6","messages":[`)
_, err := ParseGatewayRequest(NewRequestBodyRef(body), domain.PlatformAnthropic)
require.Error(t, err)
require.True(t, strings.HasPrefix(err.Error(), "invalid json (len="), "error should carry diagnostics, got: %s", err.Error())
}