Files
Enterprise-Knowledge-Base/internal/middleware/logger_test.go
T
wizardchen 86b05d923e fix(middleware): mask camelCase secret fields in request logs
The request logger's sanitizeBody only matched lowercase / snake_case
field names (api_key, apikey, access_token, ...), so values for the
camelCase JSON fields actually used by the API (apiKey, secretKey,
refreshToken, accessToken, ...) were written to logs in clear text.

Replace the per-field patterns with a single case-insensitive regex
that tolerates optional `_`/`-` separators, covering snake_case,
camelCase and PascalCase variants, and extend coverage to id_token,
client_secret, private_key, auth_token, api_secret and passwd. The
field name is preserved; only its value is replaced with "***".

Add unit tests for sanitizeBody covering the previously-leaking
camelCase fields and common variants.

Fixes #1287
2026-05-12 19:27:29 +08:00

62 lines
1.5 KiB
Go

package middleware
import "testing"
func TestSanitizeBody(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{
name: "camelCase apiKey",
in: `{"modelName":"gpt-5.2","apiKey":"sk-secret-123","provider":"azure_openai"}`,
want: `{"modelName":"gpt-5.2","apiKey":"***","provider":"azure_openai"}`,
},
{
name: "snake_case api_key",
in: `{"api_key":"sk-secret-123"}`,
want: `{"api_key":"***"}`,
},
{
name: "PascalCase APIKey",
in: `{"APIKey":"sk-secret-123"}`,
want: `{"APIKey":"***"}`,
},
{
name: "secretKey camelCase",
in: `{"secretKey":"abc","accessKeyId":"id"}`,
want: `{"secretKey":"***","accessKeyId":"id"}`,
},
{
name: "refreshToken / accessToken camelCase",
in: `{"refreshToken":"rt","accessToken":"at"}`,
want: `{"refreshToken":"***","accessToken":"***"}`,
},
{
name: "password and token preserved as masked",
in: `{"password":"p","token":"t"}`,
want: `{"password":"***","token":"***"}`,
},
{
name: "extra whitespace around colon",
in: `{"apiKey" : "leak"}`,
want: `{"apiKey":"***"}`,
},
{
name: "non sensitive fields untouched",
in: `{"baseUrl":"https://example.com","modelName":"gpt"}`,
want: `{"baseUrl":"https://example.com","modelName":"gpt"}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := sanitizeBody(tc.in)
if got != tc.want {
t.Errorf("sanitizeBody(%q)\n got: %s\nwant: %s", tc.in, got, tc.want)
}
})
}
}