diff --git a/cli/cmd/agent/create_test.go b/cli/cmd/agent/create_test.go index 9c68b3c3..396edc40 100644 --- a/cli/cmd/agent/create_test.go +++ b/cli/cmd/agent/create_test.go @@ -3,6 +3,7 @@ package agentcmd import ( "bytes" "context" + "encoding/json" "fmt" "strings" "testing" @@ -107,6 +108,11 @@ func TestCreate_From_CopiesThenUpdates(t *testing.T) { require.True(t, svc.updateCalled, "must Update after Copy when overrides present") assert.Equal(t, "ag_clone", svc.updateID) assert.Equal(t, "Renamed", svc.updateReq.Name) + body, err := json.Marshal(svc.updateReq) + require.NoError(t, err) + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal(body, &fields)) + assert.NotContains(t, fields, "avatar", "overrides must preserve the copied avatar") require.NotNil(t, svc.updateReq.Config) assert.Equal(t, "model-x", svc.updateReq.Config.ModelID) } diff --git a/cli/cmd/agent/edit_test.go b/cli/cmd/agent/edit_test.go index 67592b96..7803b2b2 100644 --- a/cli/cmd/agent/edit_test.go +++ b/cli/cmd/agent/edit_test.go @@ -3,6 +3,7 @@ package agentcmd import ( "bytes" "context" + "encoding/json" "fmt" "strings" "testing" @@ -81,7 +82,7 @@ func TestEdit_FetchThenUpdate_PreservesUntouchedFields(t *testing.T) { _, _ = iostreams.SetForTest(t) svc := &fakeEditSvc{ getResp: &sdk.Agent{ - ID: "ag_abc", Name: "Original", Description: "Keep me", + ID: "ag_abc", Name: "Original", Description: "Keep me", Avatar: "🤖", Config: &sdk.AgentConfig{ModelID: "model-x", Temperature: 0.7, KnowledgeBases: []string{"kb_a"}}, }, updateResp: &sdk.Agent{ID: "ag_abc"}, @@ -96,6 +97,11 @@ func TestEdit_FetchThenUpdate_PreservesUntouchedFields(t *testing.T) { require.NotNil(t, svc.updateReq) assert.Equal(t, "Original", svc.updateReq.Name, "Name must round-trip unchanged") assert.Equal(t, "Updated", svc.updateReq.Description) + body, err := json.Marshal(svc.updateReq) + require.NoError(t, err) + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal(body, &fields)) + assert.NotContains(t, fields, "avatar", "an unrelated edit must not clear the avatar") require.NotNil(t, svc.updateReq.Config) assert.Equal(t, "model-x", svc.updateReq.Config.ModelID, "ModelID must round-trip") assert.Equal(t, []string{"kb_a"}, svc.updateReq.Config.KnowledgeBases, "KBs must round-trip") diff --git a/client/agent_manage.go b/client/agent_manage.go index e8267935..38d4008a 100644 --- a/client/agent_manage.go +++ b/client/agent_manage.go @@ -165,10 +165,12 @@ type CreateAgentRequest struct { // UpdateAgentRequest represents the request to update an agent. // JSON field names mirror internal/handler.UpdateAgentRequest. type UpdateAgentRequest struct { - Name string `json:"name"` - Description string `json:"description"` - Avatar string `json:"avatar"` - Config *AgentConfig `json:"config"` + Name string `json:"name"` + Description string `json:"description"` + // Avatar is omitted when nil to preserve the stored value. A pointer to + // an empty string explicitly clears the avatar. + Avatar *string `json:"avatar,omitempty"` + Config *AgentConfig `json:"config"` } // AgentResponse represents the API response containing a single agent diff --git a/client/agent_manage_test.go b/client/agent_manage_test.go new file mode 100644 index 00000000..91e6ff80 --- /dev/null +++ b/client/agent_manage_test.go @@ -0,0 +1,64 @@ +package client + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestUpdateAgentAvatarPresence(t *testing.T) { + empty, replacement := "", "🐱" + for _, tc := range []struct { + name string + avatar *string + want string + }{ + {name: "omitted preserves avatar", want: "🤖"}, + {name: "explicit empty clears avatar", avatar: &empty}, + {name: "replacement", avatar: &replacement, want: replacement}, + } { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPut || r.URL.Path != "/api/v1/agents/agent-1" { + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + } + var body map[string]json.RawMessage + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + avatar := "🤖" + if raw, exists := body["avatar"]; exists { + if tc.avatar == nil { + t.Errorf("avatar must be omitted, got %s", raw) + } + if err := json.Unmarshal(raw, &avatar); err != nil { + t.Error(err) + } + } else if tc.avatar != nil { + t.Error("explicit avatar must be sent") + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(AgentResponse{ + Success: true, Data: Agent{ID: "agent-1", Avatar: avatar}, + }); err != nil { + t.Error(err) + } + })) + defer srv.Close() + + agent, err := NewClient(srv.URL).UpdateAgent(context.Background(), "agent-1", &UpdateAgentRequest{ + Name: "Updated", Avatar: tc.avatar, Config: &AgentConfig{}, + }) + if err != nil { + t.Fatal(err) + } + if agent.Avatar != tc.want { + t.Errorf("avatar = %q, want %q", agent.Avatar, tc.want) + } + }) + } +} diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go index 714b91ab..92fe94d7 100644 --- a/internal/application/service/custom_agent.go +++ b/internal/application/service/custom_agent.go @@ -247,8 +247,15 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge return result, nil } -// UpdateAgent updates an agent's information -func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) { +// UpdateAgent updates an agent's information. +// +// avatar carries the field presence the agent struct cannot: nil means the +// caller did not send an avatar and the stored one must survive, a pointer to +// "" is an explicit clear. Assigning agent.Avatar unconditionally made every +// config-only PUT erase the avatar while still answering 200. +func (s *customAgentService) UpdateAgent( + ctx context.Context, agent *types.CustomAgent, avatar *string, +) (*types.CustomAgent, error) { if agent.ID == "" { logger.Error(ctx, "Agent ID is empty") return nil, errors.New("agent ID cannot be empty") @@ -287,7 +294,16 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo // Update fields existingAgent.Name = agent.Name existingAgent.Description = agent.Description - existingAgent.Avatar = agent.Avatar + // An absent avatar keeps the stored one; only a sent value replaces it. + if avatar != nil { + // Second length check, for non-HTTP callers that never pass through + // the handler. Same validator, so the varchar(64) bound does not end + // up duplicated as two constants. + if err := (&types.CustomAgent{Avatar: *avatar}).ValidateAvatar(); err != nil { + return nil, err + } + existingAgent.Avatar = *avatar + } existingAgent.Config = agent.Config existingAgent.UpdatedAt = time.Now() diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go index 687a7d43..60801744 100644 --- a/internal/application/service/tenant_skill_install_test.go +++ b/internal/application/service/tenant_skill_install_test.go @@ -3103,8 +3103,11 @@ func (s *installCustomAgentService) ListAgents(context.Context) ([]*types.Custom } func (s *installCustomAgentService) UpdateAgent( - _ context.Context, agent *types.CustomAgent, + _ context.Context, agent *types.CustomAgent, avatar *string, ) (*types.CustomAgent, error) { + if avatar != nil { + agent.Avatar = *avatar + } return agent, nil } diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go index c205dc29..36bea15a 100644 --- a/internal/handler/custom_agent.go +++ b/internal/handler/custom_agent.go @@ -64,10 +64,14 @@ type CreateAgentRequest struct { // UpdateAgentRequest defines the request body for updating an agent type UpdateAgentRequest struct { - Name string `json:"name"` - Description string `json:"description"` - Avatar string `json:"avatar"` - Config types.CustomAgentConfig `json:"config"` + Name string `json:"name"` + Description string `json:"description"` + // Avatar travels as a pointer so an omitted field can be told apart from + // an explicit clear: nil keeps the stored avatar, a pointer to "" wipes + // it. As a plain string the two cases were indistinguishable, so a caller + // that PUT only a config silently zeroed the avatar and still got a 200. + Avatar *string `json:"avatar"` + Config types.CustomAgentConfig `json:"config"` } // CreateAgent godoc @@ -111,6 +115,13 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) { Config: req.Config, } agent.EnsureDefaults() + // The DB column (varchar(64)) has no application-level guard, so an + // oversized avatar used to reach postgres and come back as a raw driver + // 500. Reject it here with a 400 that names the limit. + if err := agent.ValidateAvatar(); err != nil { + _ = c.Error(errors.NewBadRequestError(err.Error())) + return + } if err := agent.Config.QuestionSuggestions.Validate(); err != nil { c.Error(errors.NewBadRequestError(err.Error())) return @@ -127,7 +138,11 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) { c.Error(errors.NewBadRequestError(err.Error())) return } - c.Error(errors.NewInternalServerError(err.Error())) + // Reached only after the typed sentinels and *errors.AppError + // above, so whatever lands here is a raw repository/driver error. + // Its text (SQLSTATE, column types) must not reach the client; + // the full detail is already logged above. + _ = c.Error(errors.NewInternalServerError("Failed to create agent")) return } @@ -176,7 +191,11 @@ func (h *CustomAgentHandler) GetAgent(c *gin.Context) { c.Error(appErr) return } - c.Error(errors.NewInternalServerError(err.Error())) + // Reached only after the typed sentinels and *errors.AppError above, so + // whatever lands here is a raw repository/driver error. Its text + // (SQLSTATE, column names) must not reach the client; the full detail + // is already logged above. + _ = c.Error(errors.NewInternalServerError("Failed to load agent")) return } @@ -204,7 +223,11 @@ func (h *CustomAgentHandler) ListAgents(c *gin.Context) { agents, err := h.service.ListAgents(ctx) if err != nil { logger.ErrorWithFields(ctx, err, nil) - c.Error(errors.NewInternalServerError(err.Error())) + // Reached only after the typed sentinels and *errors.AppError above, so + // whatever lands here is a raw repository/driver error. Its text + // (SQLSTATE, column names) must not reach the client; the full detail + // is already logged above. + _ = c.Error(errors.NewInternalServerError("Failed to list agents")) return } @@ -350,12 +373,24 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) { return } - // Build agent object + // Only a sent avatar is validated: nil means the caller never touched the + // field, so there is no value to bound. Checking the length here is what + // turns an oversized avatar into a 400 that names the limit, instead of + // the 500 that used to carry the database's own varchar(64) complaint. + if req.Avatar != nil { + if err := (&types.CustomAgent{Avatar: *req.Avatar}).ValidateAvatar(); err != nil { + logger.Error(ctx, "Invalid avatar", err) + _ = c.Error(errors.NewBadRequestError(err.Error())) + return + } + } + + // Build agent object. Avatar is deliberately absent here — it reaches the + // service as a separate pointer, so that "not sent" survives the trip. agent := &types.CustomAgent{ ID: id, Name: req.Name, Description: req.Description, - Avatar: req.Avatar, Config: req.Config, } agent.EnsureDefaults() @@ -368,7 +403,7 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) { secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.Name)) // Update the agent - updatedAgent, err := h.service.UpdateAgent(ctx, agent) + updatedAgent, err := h.service.UpdateAgent(ctx, agent, req.Avatar) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ "agent_id": id, @@ -381,7 +416,11 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) { case service.ErrAgentNameRequired: c.Error(errors.NewBadRequestError(err.Error())) default: - c.Error(errors.NewInternalServerError(err.Error())) + // Reached only after the typed sentinels and *errors.AppError above, so + // whatever lands here is a raw repository/driver error. Its text + // (SQLSTATE, column names) must not reach the client; the full detail + // is already logged above. + _ = c.Error(errors.NewInternalServerError("Failed to update agent")) } return } @@ -448,7 +487,11 @@ func (h *CustomAgentHandler) DeleteAgent(c *gin.Context) { case service.ErrCannotDeleteBuiltin: c.Error(errors.NewForbiddenError("Cannot delete built-in agent")) default: - c.Error(errors.NewInternalServerError(err.Error())) + // Reached only after the typed sentinels and *errors.AppError above, so + // whatever lands here is a raw repository/driver error. Its text + // (SQLSTATE, column names) must not reach the client; the full detail + // is already logged above. + _ = c.Error(errors.NewInternalServerError("Failed to delete agent")) } return } @@ -496,7 +539,11 @@ func (h *CustomAgentHandler) CopyAgent(c *gin.Context) { case service.ErrAgentNotFound: c.Error(errors.NewNotFoundError("Agent not found")) default: - c.Error(errors.NewInternalServerError(err.Error())) + // Reached only after the typed sentinels and *errors.AppError above, so + // whatever lands here is a raw repository/driver error. Its text + // (SQLSTATE, column names) must not reach the client; the full detail + // is already logged above. + _ = c.Error(errors.NewInternalServerError("Failed to copy agent")) } return } @@ -515,7 +562,11 @@ func (h *CustomAgentHandler) CopyAgent(c *gin.Context) { case service.ErrAgentNotFound: c.Error(errors.NewNotFoundError("Agent not found")) default: - c.Error(errors.NewInternalServerError(err.Error())) + // Reached only after the typed sentinels and *errors.AppError above, so + // whatever lands here is a raw repository/driver error. Its text + // (SQLSTATE, column names) must not reach the client; the full detail + // is already logged above. + _ = c.Error(errors.NewInternalServerError("Failed to copy agent")) } return } @@ -654,7 +705,11 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) { c.Error(appErr) return } - c.Error(errors.NewInternalServerError(err.Error())) + // Reached only after the typed sentinels and *errors.AppError above, so + // whatever lands here is a raw repository/driver error. Its text + // (SQLSTATE, column names) must not reach the client; the full detail + // is already logged above. + _ = c.Error(errors.NewInternalServerError("Failed to build suggested questions")) return } diff --git a/internal/handler/custom_agent_avatar_test.go b/internal/handler/custom_agent_avatar_test.go new file mode 100644 index 00000000..bd7d4581 --- /dev/null +++ b/internal/handler/custom_agent_avatar_test.go @@ -0,0 +1,103 @@ +package handler + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/application/service" + "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type agentAvatarRepository struct { + interfaces.CustomAgentRepository + agent *types.CustomAgent + err error + writes int +} + +func (r *agentAvatarRepository) GetAgentByID(context.Context, string, uint64) (*types.CustomAgent, error) { + return r.agent, r.err +} + +func (r *agentAvatarRepository) UpdateAgent(_ context.Context, a *types.CustomAgent) error { + r.writes++ + r.agent = a + return r.err +} + +func (r *agentAvatarRepository) CreateAgent(_ context.Context, a *types.CustomAgent) error { + r.writes++ + r.agent = a + return r.err +} + +func TestCustomAgentAvatarAndErrorResponses(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name, method, body, want string + status, writes int + repoErr error + }{ + {"omitted", "PUT", `{"name":"updated","config":{}}`, "🤖", 200, 1, nil}, + {"null", "PUT", `{"name":"updated","avatar":null}`, "🤖", 200, 1, nil}, + {"clear", "PUT", `{"name":"updated","avatar":""}`, "", 200, 1, nil}, + {"replace", "PUT", `{"name":"updated","avatar":"🐱"}`, "🐱", 200, 1, nil}, + { + name: "64 unicode", method: "PUT", + body: `{"name":"updated","avatar":"` + strings.Repeat("🤖", 64) + `"}`, + want: strings.Repeat("🤖", 64), status: 200, writes: 1, + }, + {"65 unicode update", "PUT", `{"name":"updated","avatar":"` + strings.Repeat("🤖", 65) + `"}`, "", 400, 0, nil}, + {"65 unicode create", "POST", `{"name":"updated","avatar":"` + strings.Repeat("🤖", 65) + `"}`, "", 400, 0, nil}, + {"config only still requires name", "PUT", `{"config":{}}`, "", 400, 0, nil}, + {"update hides database error", "PUT", `{"name":"updated"}`, "", 500, 0, errors.New("SQLSTATE secret_schema")}, + {"create hides database error", "POST", `{"name":"updated"}`, "", 500, 1, errors.New("SQLSTATE secret_schema")}, + {"get hides database error", "GET", ``, "", 500, 0, errors.New("SQLSTATE secret_schema")}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := &agentAvatarRepository{ + agent: &types.CustomAgent{ID: "custom-1", Name: "old", Avatar: "🤖", TenantID: 1}, + err: tc.repoErr, + } + svc := service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil) + h := &CustomAgentHandler{service: svc} + router := gin.New() + router.Use(middleware.ErrorHandler()) + router.PUT("/agents/:id", h.UpdateAgent) + router.POST("/agents", h.CreateAgent) + router.GET("/agents/:id", h.GetAgent) + path := "/agents/custom-1" + if tc.method == http.MethodPost { + path = "/agents" + } + req := httptest.NewRequest(tc.method, path, strings.NewReader(tc.body)) + req.Header.Set("Content-Type", "application/json") + req = req.WithContext(context.WithValue(req.Context(), types.TenantIDContextKey, uint64(1))) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + require.Equal(t, tc.status, rec.Code, rec.Body.String()) + require.Equal(t, tc.writes, repo.writes) + if tc.status == http.StatusOK { + var response struct { + Data types.CustomAgent `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response)) + require.Equal(t, tc.want, response.Data.Avatar) + require.Equal(t, tc.want, repo.agent.Avatar) + } + if tc.repoErr != nil { + require.NotContains(t, rec.Body.String(), "SQLSTATE") + require.NotContains(t, rec.Body.String(), "secret_schema") + } + }) + } +} diff --git a/internal/handler/session/resolve_agent_test.go b/internal/handler/session/resolve_agent_test.go index 54031971..d520f628 100644 --- a/internal/handler/session/resolve_agent_test.go +++ b/internal/handler/session/resolve_agent_test.go @@ -84,7 +84,9 @@ func (s *resolveOwnAgentStub) GetAgentByIDAndTenant(context.Context, string, uin func (s *resolveOwnAgentStub) ListAgents(context.Context) ([]*types.CustomAgent, error) { panic("not implemented") } -func (s *resolveOwnAgentStub) UpdateAgent(context.Context, *types.CustomAgent) (*types.CustomAgent, error) { +func (s *resolveOwnAgentStub) UpdateAgent( + context.Context, *types.CustomAgent, *string, +) (*types.CustomAgent, error) { panic("not implemented") } func (s *resolveOwnAgentStub) DeleteAgent(context.Context, string) error { diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go index 1c2216e5..53dd2906 100644 --- a/internal/types/custom_agent.go +++ b/internal/types/custom_agent.go @@ -94,6 +94,30 @@ type CustomAgent struct { CreatorName string `yaml:"-" json:"creator_name,omitempty" gorm:"-"` } +// maxAgentAvatarLength mirrors the custom_agents.avatar column limit +// (varchar(64)). See ValidateAvatar for why this is checked at the API +// boundary instead of being left to the database. +const maxAgentAvatarLength = 64 + +// ValidateAvatar rejects an avatar value the DB column cannot store. +// +// Without it, an oversized avatar (a data-URI icon, say) reaches postgres +// unchecked and comes back as a raw driver error — "ERROR: value too long for +// type character varying(64) (SQLSTATE 22001)" — which is then forwarded to +// the client as a 500. That is two problems at once: the caller only learns +// the real limit from a crash, and internal database details leak into a +// public API. Checking here turns it into an ordinary 400 that names the +// limit, like the other request validations. +func (a *CustomAgent) ValidateAvatar() error { + if a == nil { + return nil + } + if n := len([]rune(a.Avatar)); n > maxAgentAvatarLength { + return fmt.Errorf("avatar must not exceed %d characters, got %d", maxAgentAvatarLength, n) + } + return nil +} + // CustomAgentConfig represents the configuration of a custom agent type CustomAgentConfig struct { // ===== Basic Settings ===== diff --git a/internal/types/interfaces/custom_agent.go b/internal/types/interfaces/custom_agent.go index e96e2e80..c665cec9 100644 --- a/internal/types/interfaces/custom_agent.go +++ b/internal/types/interfaces/custom_agent.go @@ -46,7 +46,10 @@ type CustomAgentService interface { // Returns: // - Updated agent object // - Possible errors such as not existing, insufficient permissions, cannot modify built-in, etc. - UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) + // avatar carries field presence the agent struct cannot express: nil means + // the caller did not send an avatar and the stored one must survive, while + // a pointer to "" is an explicit clear. + UpdateAgent(ctx context.Context, agent *types.CustomAgent, avatar *string) (*types.CustomAgent, error) // DeleteAgent deletes an agent // Parameters: