From 6ce7b9b077c42138893decbdcdeeb84d31775424 Mon Sep 17 00:00:00 2001 From: suifri Date: Wed, 28 Oct 2026 15:30:40 +0200 Subject: [PATCH] [WTEL-10752]security(list_query): prevent raw SQL in sort --- model/cc_audit_form.go | 6 ++ model/online_skills.go | 1 + store/sqlstore/cc_agent_store.go | 21 ++++--- store/sqlstore/cc_member_store.go | 11 +++- store/sqlstore/cc_quick_reply_store.go | 50 +++++++++------- store/sqlstore/list_query.go | 81 +++++++++++++++++++------- store/sqlstore/pg_dialect.go | 3 + 7 files changed, 122 insertions(+), 51 deletions(-) diff --git a/model/cc_audit_form.go b/model/cc_audit_form.go index 53919a6f..ba6abfaf 100644 --- a/model/cc_audit_form.go +++ b/model/cc_audit_form.go @@ -84,6 +84,12 @@ func (AuditForm) EntityName() string { return "cc_audit_form_view" } +func (AuditForm) CustomSorts() []string { + return []string{ + "case when team_ids && array(select a.team_id from call_center.cc_agent a where a.user_id = :TeamUserID::int8 and a.team_id notnull) then 0 else 1 end asc,name asc", + } +} + func (af *AuditForm) IsValid() AppError { if len(af.Name) < 3 || len(af.Name) > 256 { return NewBadRequestError("app.audit_form.is_valid.name", "Name should not be less than 3 characters or greater than 256 characters") diff --git a/model/online_skills.go b/model/online_skills.go index b712a8ad..c53a4190 100644 --- a/model/online_skills.go +++ b/model/online_skills.go @@ -103,6 +103,7 @@ func (s OnlineSkills) DefaultFields() []string { } func (s OnlineSkills) EntityName() string { return "cc_online_skills_list" } func (s OnlineSkills) DefaultOrder() string { return "is_system desc, name asc" } +func (OnlineSkills) CustomSorts() []string { return []string{"is_system desc, name asc"} } func (s *OnlineSkills) Validate() AppError { if s == nil { diff --git a/store/sqlstore/cc_agent_store.go b/store/sqlstore/cc_agent_store.go index 38217a2a..44445ecd 100644 --- a/store/sqlstore/cc_agent_store.go +++ b/store/sqlstore/cc_agent_store.go @@ -597,7 +597,11 @@ group by q.id`, map[string]any{ } func (s SqlAgentStore) HistoryState(ctx context.Context, domainId int64, search *model.SearchAgentState) ([]*model.AgentState, model.AppError) { - order := GetOrderBy("cc_agent_state_history", search.Sort) + order, err := GetOrderBy("cc_agent_state_history", search.Sort) + if err != nil { + return nil, model.NewBadRequestError("store.sql_agent.get_state_history.sort", err.Error()) + } + if order == "" { order = "order by joined_at desc" } @@ -911,7 +915,6 @@ func (s SqlAgentStore) StatusStatistic(ctx context.Context, domainId, supervisor var ( list []*model.AgentStatusStatistics searchOperator string - sort string ) q, found := model.ParseRegexp(search.Q) @@ -921,7 +924,10 @@ func (s SqlAgentStore) StatusStatistic(ctx context.Context, domainId, supervisor searchOperator = ILikeComparisonOperator } - sort = GetOrderBy("t", search.Sort) + sort, err := GetOrderBy("t", search.Sort) + if err != nil { + return nil, model.NewBadRequestError("store.sql_agent.get_status_stats.sort", err.Error()) + } if sort == "" { sort = `order by case t.status @@ -932,10 +938,8 @@ func (s SqlAgentStore) StatusStatistic(ctx context.Context, domainId, supervisor } f := map[string]any{ - "DomainId": domainId, - "UserSupervisorId": supervisorUserId, - //"Groups": pq.Array(groups), - //"Access": access.Value(), + "DomainId": domainId, + "UserSupervisorId": supervisorUserId, "Q": q, "Limit": search.GetLimit(), "Offset": search.GetOffset(), @@ -1170,8 +1174,7 @@ where t.domain_id = :DomainId %s limit :Limit offset :Offset`, searchOperator, sort) - _, err := s.GetMaster().WithContext(ctx).Select(&list, query, f) - if err != nil { + if _, err = s.GetMaster().WithContext(ctx).Select(&list, query, f); err != nil { return nil, model.NewCustomCodeError("store.sql_agent.get_status_stats.app_error", err.Error(), extractCodeFromErr(err)) } diff --git a/store/sqlstore/cc_member_store.go b/store/sqlstore/cc_member_store.go index 931674b3..0caf9125 100644 --- a/store/sqlstore/cc_member_store.go +++ b/store/sqlstore/cc_member_store.go @@ -180,7 +180,12 @@ func getMemberSortClause(sort string) string { return fmt.Sprintf("order by (m.communications->0->>'destination') %s", direction) } - return GetOrderBy("cc_member", sort) + order, err := GetOrderBy("cc_member", sort) + if err != nil { + return "order by created_at desc" + } + + return order } // memberSearchFilters is the shared WHERE of SearchMembers and GetMaxCommunicationsCount, so both see the same rows. @@ -562,7 +567,9 @@ func (s SqlMemberStore) MultiDelete(ctx context.Context, domainId int64, search } if search.Sort != "" { - sort = GetOrderBy(model.Member{}.EntityName(), search.Sort) + if sort, err = GetOrderBy(model.Member{}.EntityName(), search.Sort); err != nil { + return nil, model.NewBadRequestError("store.sql_member.multi_delete.sort", err.Error()) + } } filters := map[string]any{ diff --git a/store/sqlstore/cc_quick_reply_store.go b/store/sqlstore/cc_quick_reply_store.go index 3506bf66..b5078ea3 100644 --- a/store/sqlstore/cc_quick_reply_store.go +++ b/store/sqlstore/cc_quick_reply_store.go @@ -2,6 +2,7 @@ package sqlstore import ( "context" + "errors" "fmt" "strings" @@ -78,12 +79,12 @@ func (s SqlQuickReplyStore) Create(ctx context.Context, domainId int64, reply *m func (s SqlQuickReplyStore) GetAllPage(ctx context.Context, domainId int64, search *model.SearchQuickReply, userId int64) ([]*model.QuickReply, model.AppError) { args := map[string]any{ - "DomainId": domainId, - "Q": quickReplySearchPattern(search.GetQ()), - "Ids": pq.Array(search.Ids), - "Name": search.Name, - "UserId": userId, - "Queue": pq.Array(search.Queue), + "DomainId": domainId, + "Q": quickReplySearchPattern(search.GetQ()), + "Ids": pq.Array(search.Ids), + "Name": search.Name, + "UserId": userId, + "Queue": pq.Array(search.Queue), "RestrictToAgent": search.RestrictToAgent, } @@ -92,7 +93,7 @@ func (s SqlQuickReplyStore) GetAllPage(ctx context.Context, domainId int64, sear AND (:Q::varchar isnull OR t.name ILIKE :Q::varchar OR t.text ILIKE :Q::varchar) AND (:Ids::int8[] isnull OR t.id = ANY(:Ids::bigint[])) and ( - :RestrictToAgent = false + :RestrictToAgent = false or ( (t.team_ids is null and t.queue_ids is null) or ( @@ -107,7 +108,7 @@ func (s SqlQuickReplyStore) GetAllPage(ctx context.Context, domainId int64, sear ) ) ` - + var replies []*model.QuickReply if err := s.ListQuery(ctx, &replies, search.ListRequest, where, model.QuickReply{}, args); err != nil { return nil, model.NewCustomCodeError("store.sql_quick_reply.get_all.app_error", err.Error(), extractCodeFromErr(err)) @@ -116,18 +117,27 @@ func (s SqlQuickReplyStore) GetAllPage(ctx context.Context, domainId int64, sear } func (s SqlQuickReplyStore) GetAllPageByAgentPriority(ctx context.Context, domainId, userId int64, search *model.SearchQuickReply) ([]*model.QuickReply, model.AppError) { - args := map[string]any { - "DomainId": domainId, - "UserId": userId, - "Q": quickReplySearchPattern(search.GetQ()), - "Ids": pq.Array(search.Ids), - "Name": search.Name, - "Queue": pq.Array(search.Queue), - "RestrictToAgent": search.RestrictToAgent, + args := map[string]any{ + "DomainId": domainId, + "UserId": userId, + "Q": quickReplySearchPattern(search.GetQ()), + "Ids": pq.Array(search.Ids), + "Name": search.Name, + "Queue": pq.Array(search.Queue), + "RestrictToAgent": search.RestrictToAgent, } fields := GetFields(search.Fields, &model.QuickReply{}) parsedFields := strings.Join(fields, ", ") - + + order, err := GetOrderBy(model.QuickReply{}.EntityName(), search.Sort) + if err != nil { + if errors.Is(err, ErrInvalidSortField) { + return nil, model.NewBadRequestError("store.sql_quick_reply.get_all_by_agent_priority.sort", err.Error()) + } + + return nil, model.NewCustomCodeError("store.sql_quick_reply.get_all_by_agent_priority.sort", err.Error(), 412) + } + query := fmt.Sprintf(` with agent_info_cte as ( select ( @@ -142,7 +152,7 @@ func (s SqlQuickReplyStore) GetAllPageByAgentPriority(ctx context.Context, domai filtered_quick_replies_cte as ( select %s, - case + case when t.queue_ids && agent_info.queues_ids then 1 when agent_info.team_id = any(t.team_ids) @@ -168,7 +178,7 @@ func (s SqlQuickReplyStore) GetAllPageByAgentPriority(ctx context.Context, domai %s offset %d limit %d - `, parsedFields, parsedFields, GetOrderBy(model.QuickReply{}.EntityName(), search.Sort), search.ListRequest.GetOffset(), search.ListRequest.GetLimit()) + `, parsedFields, parsedFields, order, search.ListRequest.GetOffset(), search.ListRequest.GetLimit()) var quickRepliesList []*model.QuickReply if _, err := s.GetReplica().WithContext(ctx).Select(&quickRepliesList, query, args); err != nil { @@ -218,7 +228,7 @@ func (s SqlQuickReplyStore) Update(ctx context.Context, domainId int64, reply *m where id = :Id and domain_id = :DomainId returning * ) - + select s.id , s.created_at , call_center.cc_get_lookup(uc.id, coalesce(uc.name, uc.username)) as created_by diff --git a/store/sqlstore/list_query.go b/store/sqlstore/list_query.go index d2b0a63f..fc8fb3be 100644 --- a/store/sqlstore/list_query.go +++ b/store/sqlstore/list_query.go @@ -2,7 +2,9 @@ package sqlstore import ( "context" + "errors" "fmt" + "slices" "strings" "time" @@ -20,6 +22,10 @@ type Entity interface { DefaultOrder() string } +type CustomSorter interface { + CustomSorts() []string +} + func GetFields(f []string, e Entity) []string { if f == nil || len(f) < 1 { @@ -62,7 +68,7 @@ func QuoteLiteral(name string) string { func isRawOrder(s string) bool { ls := strings.ToLower(s) - // якщо це складний вираз або кілька полів — віддаємо як є + return strings.Contains(ls, "case ") || strings.Contains(s, "(") || strings.Contains(s, ")") || @@ -71,14 +77,30 @@ func isRawOrder(s string) bool { strings.Contains(s, ",") } -func GetOrderBy(t, s string) string { +var ErrInvalidSortField = errors.New("invalid sort field") + +func GetOrderBy(t, s string, e ...Entity) (string, error) { s = strings.TrimSpace(s) if s == "" { - return "" + return "", nil } if isRawOrder(s) { - return "order by " + s + if len(e) == 0 || e[0] == nil { + return "", fmt.Errorf("%w: %s", ErrInvalidSortField, t) + } + + customSorter, ok := e[0].(CustomSorter) + if !ok { + return "", fmt.Errorf("%w custom not allowed", ErrInvalidSortField, e[0]) + } + + ls := strings.ToLower(s) + if !slices.ContainsFunc(customSorter.CustomSorts(), func(f string) bool { return strings.ToLower(f) == ls }) { + return "", fmt.Errorf("%w %s", ErrInvalidSortField, ls) + } + + return "order by " + s, nil } sort, field := orderBy(s) @@ -91,12 +113,12 @@ func GetOrderBy(t, s string) string { } return fmt.Sprintf( - `order by + `order by case when not call_center.cc_is_lookup(%s, %s) then %s end %s %s, case when call_center.cc_is_lookup(%s, %s) then COALESCE(((%s::text)::json->>'name'), ((%s::text)::json->0->>'name')) end %s %s`, QuoteLiteral(t), QuoteLiteral(field), fld, sort, nulls, QuoteLiteral(t), QuoteLiteral(field), fld, fld, sort, nulls, - ) + ), nil } func orderBy(s string) (sort string, field string) { @@ -118,7 +140,7 @@ func orderBy(s string) (sort string, field string) { } // TODO filter -func Build(req *model.ListRequest, schema string, where string, e Entity, args map[string]interface{}) string { +func Build(req *model.ListRequest, schema string, where string, e Entity, args map[string]any) (string, error) { s := GetFields(req.Fields, e) sort := "" @@ -137,35 +159,46 @@ func Build(req *model.ListRequest, schema string, where string, e Entity, args m t = pq.QuoteIdentifier(schema) + "." + t } - query := fmt.Sprintf(`select %s + order, err := GetOrderBy(e.EntityName(), sort, e) + if err != nil { + return "", err + } + + query := fmt.Sprintf(`select %s from %s as t where %s %s offset :Offset - limit :Limit`, strings.Join(s, ", "), t, where, GetOrderBy(e.EntityName(), sort)) + limit :Limit`, strings.Join(s, ", "), t, where, order) - return query + return query, nil } // fixme schema func (s *SqlSupplier) ListQuery(ctx context.Context, out interface{}, req model.ListRequest, where string, e Entity, params map[string]interface{}) error { - q := Build(&req, "call_center", where, e, params) - _, err := s.GetReplica().WithContext(ctx).Select(out, q, params) + q, err := Build(&req, "call_center", where, e, params) if err != nil { return err } + if _, err = s.GetReplica().WithContext(ctx).Select(out, q, params); err != nil { + return err + } + return nil } // fixme func (s *SqlSupplier) ListQueryMaster(ctx context.Context, out interface{}, req model.ListRequest, where string, e Entity, params map[string]interface{}) error { - q := Build(&req, "call_center", where, e, params) - _, err := s.GetMaster().WithContext(ctx).Select(out, q, params) + q, err := Build(&req, "call_center", where, e, params) if err != nil { return err } + if _, err = s.GetMaster().WithContext(ctx).Select(out, q, params); err != nil { + return err + } + return nil } @@ -178,7 +211,7 @@ func (s *SqlSupplier) One(ctx context.Context, out interface{}, where string, e t := pq.QuoteIdentifier(e.EntityName()) - query := fmt.Sprintf(`select %s + query := fmt.Sprintf(`select %s from call_center.%s as t where %s limit 1`, strings.Join(fields, ", "), t, where) @@ -192,24 +225,32 @@ func (s *SqlSupplier) One(ctx context.Context, out interface{}, where string, e } func (s *SqlSupplier) ListQueryTimeout(ctx context.Context, out interface{}, req model.ListRequest, where string, e Entity, params map[string]interface{}) error { - ctxTimeout, _ := context.WithTimeout(ctx, (time.Second * time.Duration(s.QueryTimeout()))) - q := Build(&req, "call_center", where, e, params) - _, err := s.GetReplica().WithContext(ctxTimeout).Select(out, q, params) + q, err := Build(&req, "call_center", where, e, params) if err != nil { return err } + ctxTimeout, cancel := context.WithTimeout(ctx, time.Second*time.Duration(s.QueryTimeout())) + defer cancel() + + if _, err = s.GetReplica().WithContext(ctxTimeout).Select(out, q, params); err != nil { + return err + } + return nil } // todo func (s *SqlSupplier) ListQueryFromSchema(ctx context.Context, out interface{}, schema string, req model.ListRequest, where string, e Entity, params map[string]interface{}) error { - q := Build(&req, schema, where, e, params) - _, err := s.GetReplica().WithContext(ctx).Select(out, q, params) + q, err := Build(&req, schema, where, e, params) if err != nil { return err } + if _, err = s.GetReplica().WithContext(ctx).Select(out, q, params); err != nil { + return err + } + return nil } diff --git a/store/sqlstore/pg_dialect.go b/store/sqlstore/pg_dialect.go index 3bda28eb..a58cf36f 100644 --- a/store/sqlstore/pg_dialect.go +++ b/store/sqlstore/pg_dialect.go @@ -47,7 +47,10 @@ func extractCodeFromErr(err error) int { case ForeignKeyViolationErrorCode, DuplicationViolationErrorCode, FromTriggerValidationErrorCode: code = http.StatusBadRequest } + } else if errors.Is(err, ErrInvalidSortField) { + code = 400 } + return code }