From 0bf105499b093578ddbaabf24403ba0aa776657a Mon Sep 17 00:00:00 2001 From: xiaojunxiang Date: Fri, 25 Sep 2026 22:23:27 +0800 Subject: [PATCH] fix(knowledge): reject invalid JSON uploads before async parse (#3360) * fix(knowledge): reject invalid JSON uploads before async parse Validate .json payloads at HTTP upload/replace time with the same gate used by the simple JSON reader, so JSONC or truncated files fail with HTTP 400 instead of after document-process retries. CreateKnowledgeFromFile itself skips the gate so datasource sync and IM still create a knowledge row that fails in async parse. Signed-off-by: xiaojunxiang * fix(knowledge): localize JSON upload validation messages The upload queue shows the backend message verbatim and the rest of the upload handler speaks Chinese. Map ValidateJSONContent's errors (now sentinels with unchanged text, still shared with the async JSON reader) to Chinese messages at the upload/replace boundary. --------- Signed-off-by: xiaojunxiang Co-authored-by: wizardchen Co-authored-by: lyingbug --- .../application/service/knowledge_create.go | 5 + .../service/knowledge_create_test.go | 35 +++++++ .../application/service/knowledge_replace.go | 5 + .../application/service/knowledge_util.go | 40 ++++++++ .../knowledge_util_json_upload_test.go | 93 +++++++++++++++++++ internal/handler/knowledge.go | 15 +++ .../docparser/json_converter.go | 30 ++++-- .../docparser/json_converter_test.go | 29 ++++++ 8 files changed, 246 insertions(+), 6 deletions(-) create mode 100644 internal/application/service/knowledge_util_json_upload_test.go diff --git a/internal/application/service/knowledge_create.go b/internal/application/service/knowledge_create.go index b84e807b..5b1212a4 100644 --- a/internal/application/service/knowledge_create.go +++ b/internal/application/service/knowledge_create.go @@ -76,6 +76,11 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context, return nil, ErrInvalidFileType } + // JSON content validation stays in the HTTP upload handler (and + // ReplaceKnowledgeFile), not here: datasource sync may have already + // deleted the previous knowledge for this external_id, and IM swallows + // create errors — an early 400 would drop the document with no failed row. + // Calculate file hash for deduplication logger.Info(ctx, "Calculating file hash") hash, err := calculateFileHash(file) diff --git a/internal/application/service/knowledge_create_test.go b/internal/application/service/knowledge_create_test.go index 8dda1b42..937a6375 100644 --- a/internal/application/service/knowledge_create_test.go +++ b/internal/application/service/knowledge_create_test.go @@ -192,6 +192,41 @@ func TestCreateKnowledgeFromFilePersistsStoredFilePathOnCreate(t *testing.T) { require.Equal(t, 1, task.calls) } +// Datasource sync deletes the previous knowledge for an external_id before +// calling CreateKnowledgeFromFile. Early JSON rejection here would leave a +// gap (old gone, nothing created). Malformed .json must still create a row +// and fail later in async parse — HTTP upload rejects via the handler instead. +func TestCreateKnowledgeFromFileAcceptsInvalidJSONForAsyncParse(t *testing.T) { + t.Parallel() + + repo := &createKnowledgeFileRepoStub{} + fileSvc := &createKnowledgeFileServiceStub{} + task := &createKnowledgeTaskEnqueuerStub{} + svc := &knowledgeService{ + repo: repo, + kbService: &createKnowledgeFileKBServiceStub{kb: &types.KnowledgeBase{ID: "kb-1"}}, + fileSvc: fileSvc, + task: task, + } + + knowledge, err := svc.CreateKnowledgeFromFile( + newCreateKnowledgeFileContext(), + "kb-1", + newMultipartFileHeader(t, "bad.json", "{\n// comment\n\"a\": 1\n}"), + map[string]string{"datasource_id": "ds-1", "external_id": "ext-1"}, + nil, + "bad.json", + nil, + "notion", + nil, + ) + + require.NoError(t, err) + require.NotNil(t, knowledge) + require.Equal(t, 1, repo.createCalls) + require.Equal(t, 1, task.calls) +} + func TestCreateKnowledgeFromImageFallsBackWhenLegacyStorageConfigIsIncomplete(t *testing.T) { t.Parallel() diff --git a/internal/application/service/knowledge_replace.go b/internal/application/service/knowledge_replace.go index af200bd4..e6099227 100644 --- a/internal/application/service/knowledge_replace.go +++ b/internal/application/service/knowledge_replace.go @@ -98,6 +98,11 @@ func (s *knowledgeService) ReplaceKnowledgeFile(ctx context.Context, return nil, err } + if err := ValidateJSONUploadContent(safeFileName, file); err != nil { + logger.Errorf(ctx, "Invalid JSON replacement content for knowledge %s: %v", existing.ID, err) + return nil, err + } + hash, err := calculateFileHash(file) if err != nil { return nil, err diff --git a/internal/application/service/knowledge_util.go b/internal/application/service/knowledge_util.go index c3da26e7..e520edbc 100644 --- a/internal/application/service/knowledge_util.go +++ b/internal/application/service/knowledge_util.go @@ -4,6 +4,7 @@ import ( "context" "crypto/md5" "encoding/hex" + "errors" "fmt" "io" "mime/multipart" @@ -14,6 +15,7 @@ import ( filesvc "github.com/Tencent/WeKnora/internal/application/service/file" werrors "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/infrastructure/docparser" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" @@ -103,6 +105,44 @@ func isValidURL(url string) bool { return false } +// readMultipartFileContent reads the full upload payload. Each Open() returns a +// fresh reader, so callers that hash or SaveFile later open again themselves. +func readMultipartFileContent(file *multipart.FileHeader) ([]byte, error) { + f, err := file.Open() + if err != nil { + return nil, err + } + defer func() { _ = f.Close() }() + return io.ReadAll(f) +} + +// ValidateJSONUploadContent rejects malformed .json uploads before they are +// stored and queued. Shares the same validity gate as the simple JSON reader. +// Call this from HTTP upload / replace handlers only — CreateKnowledgeFromFile +// itself must not, so datasource sync and IM can still create a knowledge row +// that fails in async parse (delete-then-create must not leave a gap). +func ValidateJSONUploadContent(fileName string, file *multipart.FileHeader) error { + if normalizeFileExtension(getFileType(fileName)) != "json" { + return nil + } + data, err := readMultipartFileContent(file) + if err != nil { + return err + } + // The upload queue shows this message verbatim, so localize it here rather + // than in docparser, whose error text is shared with the async JSON reader. + switch err := docparser.ValidateJSONContent(data); { + case err == nil: + return nil + case errors.Is(err, docparser.ErrEmptyJSONContent): + return werrors.NewBadRequestError("JSON 文件内容为空") + case errors.Is(err, docparser.ErrInvalidJSONContent): + return werrors.NewBadRequestError("JSON 文件内容无效,请检查格式") + default: + return werrors.NewBadRequestError(err.Error()) + } +} + // calculateFileHash calculates MD5 hash of a file func calculateFileHash(file *multipart.FileHeader) (string, error) { f, err := file.Open() diff --git a/internal/application/service/knowledge_util_json_upload_test.go b/internal/application/service/knowledge_util_json_upload_test.go new file mode 100644 index 00000000..772cb165 --- /dev/null +++ b/internal/application/service/knowledge_util_json_upload_test.go @@ -0,0 +1,93 @@ +package service + +import ( + "errors" + "testing" + + werrors "github.com/Tencent/WeKnora/internal/errors" +) + +func TestValidateJSONUploadContent(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + filename string + content string + wantErr string + }{ + { + name: "non-json skipped", + filename: "notes.md", + content: "not json at all", + }, + { + name: "valid object", + filename: "config.json", + content: `{"agents":{"list":[]}}`, + }, + { + name: "valid array", + filename: "items.JSON", + content: `[1,2,3]`, + }, + { + name: "jsonc comments rejected", + filename: "openclaw.json", + content: "{\n// comment\n\"a\": 1\n}", + wantErr: "JSON 文件内容无效,请检查格式", + }, + { + name: "leading junk rejected", + filename: "openclaw.json", + content: "openclaw.json\n\n{\"a\":1}", + wantErr: "JSON 文件内容无效,请检查格式", + }, + { + name: "trailing comma rejected", + filename: "bad.json", + content: `{"a":1,}`, + wantErr: "JSON 文件内容无效,请检查格式", + }, + { + name: "empty rejected", + filename: "empty.json", + content: "", + wantErr: "JSON 文件内容为空", + }, + { + name: "bom-prefixed valid", + filename: "bom.json", + content: "\ufeff{\"ok\":true}", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + file := newMultipartFileHeader(t, tt.filename, tt.content) + err := ValidateJSONUploadContent(tt.filename, file) + if tt.wantErr == "" { + if err != nil { + t.Fatalf("ValidateJSONUploadContent() unexpected err: %v", err) + } + return + } + if err == nil { + t.Fatalf("ValidateJSONUploadContent() err = nil, want %q", tt.wantErr) + } + appErr, ok := werrors.IsAppError(err) + if !ok { + t.Fatalf("want AppError, got %T (%v)", err, err) + } + if appErr.HTTPCode != 400 { + t.Fatalf("HTTPCode = %d, want 400", appErr.HTTPCode) + } + if !errors.Is(err, appErr) || appErr.Message != tt.wantErr { + if appErr.Message != tt.wantErr { + t.Fatalf("Message = %q, want %q", appErr.Message, tt.wantErr) + } + } + }) + } +} diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index c675cffa..a9fb8db4 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -408,6 +408,21 @@ func (h *KnowledgeHandler) CreateKnowledgeFromFile(c *gin.Context) { channel := c.PostForm("channel") + // Reject malformed .json at the HTTP boundary so users get 400 immediately. + // Kept out of CreateKnowledgeFromFile so datasource sync / IM keep creating + // a knowledge row that fails in async parse instead of vanishing. + jsonCheckName := file.Filename + if customFileName != "" { + if _, base := types.SplitKnowledgeRelativePath(customFileName); base != "" { + jsonCheckName = base + } + } + if err := service.ValidateJSONUploadContent(jsonCheckName, file); err != nil { + logger.Errorf(ctx, "Invalid JSON upload content for %s: %v", jsonCheckName, err) + _ = c.Error(err) + return + } + // Create knowledge entry from the file knowledge, err := h.kgService.CreateKnowledgeFromFile(ctx, kbID, file, metadata, enableMultimodel, customFileName, tagIDs, channel, processOverrides) // Check for duplicate knowledge error diff --git a/internal/infrastructure/docparser/json_converter.go b/internal/infrastructure/docparser/json_converter.go index 6b776e4e..a637ab81 100644 --- a/internal/infrastructure/docparser/json_converter.go +++ b/internal/infrastructure/docparser/json_converter.go @@ -2,6 +2,7 @@ package docparser import ( "encoding/json" + "errors" "fmt" "sort" "strconv" @@ -16,6 +17,26 @@ const defaultJSONChunkSize = 1536 // when the current chunk has reached at least this size. var minJSONChunkSize = defaultJSONChunkSize - 200 +// Errors returned by ValidateJSONContent. +var ( + ErrEmptyJSONContent = errors.New("empty JSON content") + ErrInvalidJSONContent = errors.New("invalid JSON content") +) + +// ValidateJSONContent reports whether data is well-formed JSON after stripping +// a leading UTF-8 BOM. Upload paths call this before enqueueing parse work so +// JSONC / truncated payloads fail immediately instead of after async retries. +func ValidateJSONContent(data []byte) error { + data = trimBOM(data) + if len(data) == 0 { + return ErrEmptyJSONContent + } + if !json.Valid(data) { + return ErrInvalidJSONContent + } + return nil +} + // jsonToMarkdown converts raw JSON bytes into markdown text // // Key properties: @@ -26,13 +47,10 @@ var minJSONChunkSize = defaultJSONChunkSize - 200 // - The output is a series of fenced ```json code blocks separated by \n\n, // which the downstream text chunker can split at block boundaries. func jsonToMarkdown(data []byte) (string, error) { + if err := ValidateJSONContent(data); err != nil { + return "", err + } data = trimBOM(data) - if len(data) == 0 { - return "", fmt.Errorf("empty JSON content") - } - if !json.Valid(data) { - return "", fmt.Errorf("invalid JSON content") - } var parsed interface{} if err := json.Unmarshal(data, &parsed); err != nil { diff --git a/internal/infrastructure/docparser/json_converter_test.go b/internal/infrastructure/docparser/json_converter_test.go index a2231b36..15c36e75 100644 --- a/internal/infrastructure/docparser/json_converter_test.go +++ b/internal/infrastructure/docparser/json_converter_test.go @@ -580,6 +580,35 @@ func TestSimpleFormatReader_JSON_Invalid(t *testing.T) { }) } +func TestValidateJSONContent(t *testing.T) { + tests := []struct { + name string + data string + wantErr string + }{ + {name: "object", data: `{"a":1}`}, + {name: "array", data: `[1,2]`}, + {name: "bom object", data: "\ufeff{\"a\":1}"}, + {name: "empty", data: "", wantErr: "empty JSON content"}, + {name: "jsonc", data: "{\n// x\n}", wantErr: "invalid JSON content"}, + {name: "truncated", data: `{"a":`, wantErr: "invalid JSON content"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := ValidateJSONContent([]byte(tt.data)) + if tt.wantErr == "" { + if err != nil { + t.Fatalf("ValidateJSONContent() err = %v", err) + } + return + } + if err == nil || err.Error() != tt.wantErr { + t.Fatalf("ValidateJSONContent() err = %v, want %q", err, tt.wantErr) + } + }) + } +} + func TestIsSimpleFormat_JSON(t *testing.T) { cases := []struct { input string