Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions model/cc_audit_form.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

це дубль з store/sqlstore/cc_audit_form.go, і порівнюється він посимвольно: хтось поправить пробіл там, і список форм з TeamFilter почне віддавати помилку.

якщо внутрішній сорт не йтиме через валідацію (коментар), цей метод і такий самий в OnlineSkills можна прибрати

}
}

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")
Expand Down
1 change: 1 addition & 0 deletions model/online_skills.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
21 changes: 12 additions & 9 deletions store/sqlstore/cc_agent_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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(),
Expand Down Expand Up @@ -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))
}

Expand Down
11 changes: 9 additions & 2 deletions store/sqlstore/cc_member_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Передати екземпляр model.Member{} третім аргументом.

Suggested change
order, err := GetOrderBy("cc_member", sort)
order, err := GetOrderBy("cc_member", sort, model.Member{})

if err != nil {
return "order by created_at desc"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут невалідний sort неявно стає created_at desc, а в MultiDelete на той самий sort — 400. може, і тут повертати помилку (getMemberSortClause -> (string, error))? бо інакше клієнт не дізнається, що його сортування проігнорували

}

return order
}

// memberSearchFilters is the shared WHERE of SearchMembers and GetMaxCommunicationsCount, so both see the same rows.
Expand Down Expand Up @@ -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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Передати екземпляр model.Member{} третім аргументом.

Suggested change
if sort, err = GetOrderBy(model.Member{}.EntityName(), search.Sort); err != nil {
if sort, err = GetOrderBy(model.Member{}.EntityName(), search.Sort, model.Member{}); err != nil {

return nil, model.NewBadRequestError("store.sql_member.multi_delete.sort", err.Error())
}
}

filters := map[string]any{
Expand Down
50 changes: 30 additions & 20 deletions store/sqlstore/cc_quick_reply_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package sqlstore

import (
"context"
"errors"
"fmt"
"strings"

Expand Down Expand Up @@ -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,
}

Expand All @@ -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 (
Expand All @@ -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))
Expand All @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Передати екземпляр model.QuickReply{} третім аргументом для перевірки сортування.

Suggested change
order, err := GetOrderBy(model.QuickReply{}.EntityName(), search.Sort)
order, err := GetOrderBy(model.QuickReply{}.EntityName(), search.Sort, model.QuickReply{})

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 (
Expand All @@ -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)
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
81 changes: 61 additions & 20 deletions store/sqlstore/list_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package sqlstore

import (
"context"
"errors"
"fmt"
"slices"
"strings"
"time"

Expand All @@ -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 {
Expand Down Expand Up @@ -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, ")") ||
Expand All @@ -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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

додай, будь ласка, табличний тест на GetOrderBy: пейлоад з задачі ((case when (1=1) then (select 1 from pg_sleep(3)) else 1 end)), -created_at', звичайні +name / -id, порожній

s = strings.TrimSpace(s)
if s == "" {
return ""
return "", nil
}

if isRawOrder(s) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

думаю, проблема в тому, що через цю перевірку зараз ідуть і клієнтський sort, і наші внутрішні вирази. звідси і дублі сирого SQL у CustomSorts(), і регресія: в активних дзвінках rewriteCallSort перетворює +from / -to на coalesce(...), у model.Call нема CustomSorts, тож сортування по from/to (WTEL-9468) тепер падає з 500

пропоную розділити:

  • від клієнта приймати лише [+-]field, будь-який сирий вираз — 400 (поле і так квотиться через QuoteIdentifier, а перевірка по AllowFields() — як бонус);
  • внутрішні вирази (DefaultOrder, сорт форм аудиту по команді, from/to в дзвінках) передавати в Build вже готовим order, без валідації.

тоді CustomSorts і isRawOrder взагалі не потрібні. що скажеш?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kirychukyurii

від клієнта приймати лише [+-]field, будь-який сирий вираз — 400

well, першочергово я так і робив, бо не хотів сильно зачіпати обробку на рівні доступу до бази, але обробка запитів до бази була єдиним централізованим місцем, де це все можна відловити

якщо робити так, щоб відловлювати клієнтські запити, то це на рівні delivery або app/control треба додавати метод на кожен Get ендпоінт вручну на перевірку, чи філд входить до дозволених для сорту + це потрібно не забувати додавати на нові ендпоінти і так як в go немає махенізму якогось явного аспект орієнтованого програмування, то це потрібно реалізовувати явними викликами методів

але я погоджуюся, що так простіше в плані реалізації і викликає менше проблем описаних нижче в коментах і якщо додавання такої перевірки ок в усі методи List в сервісі engine, то мені не важко так переписати

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

по ендпоінтах розносити не треба, перевірка все ж лишається централізовано в Build / GetOrderBy, як у тебе..

різниця лише в тому, що саме ми там валідуємо:

  • req.Sort від клієнта - лише [+-]field, де field є в AllowFields(), інакше ErrInvalidSortField. тоді й isRawOrder не потрібен
  • DefaultOrder() - це наш код, тож Build бере його без перевірки, коли req.Sort порожній
  • from/to в дзвінках - клієнт шле +from, це звичайне поле. а підміну поля на вираз може віддавати сама сутність (умовно SortExpr(field) на model.Call, приклад нижче), і Build підставляє її вже після валідації
  • сорт форм аудиту по команді - окремим order, який стор передає поруч з req, а не через search.Sort

тоді нові ендпоінти захищені автоматично, бо все одно йдуть через Build, і сирий SQL у моделях дублювати не треба
лише тут знову таки потрібно узгодити з фронтом.. бо якщо вони сортують по полю, якого нема в AllowFields() , то біда

приблизно так:

// list_query.go

type SortMapper interface {
	SortExpr(field string) (string, bool)
}

func GetOrderBy(t, s string, e Entity) (string, error) {
	s = strings.TrimSpace(s)
	if s == "" {
		return "", nil
	}

	dir, field := orderBy(s)

	nulls := "NULLS LAST"
	if strings.EqualFold(dir, "desc") {
		nulls = "NULLS FIRST"
	}

	if m, ok := e.(SortMapper); ok {
		if expr, ok := m.SortExpr(field); ok {
			return fmt.Sprintf("order by %s %s %s", expr, dir, nulls), nil
		}
	}

	if !slices.Contains(e.AllowFields(), field) {
		return "", fmt.Errorf("%w: %q", ErrInvalidSortField, s)
	}

	return lookupOrderBy(t, field, dir, nulls), nil // те, що зараз з cc_is_lookup
}

func Build(req *model.ListRequest, schema, where string, e Entity, args map[string]any) (string, error) {
	// ...
	order := defaultOrderBy(e) // стара GetOrderBy як є, бо DefaultOrder - наш код
	if req.Sort != "" {
		var err error
		if order, err = GetOrderBy(e.EntityName(), req.Sort, e); err != nil {
			return "", err
		}
	}
	// ...
}
// model/call.go

func (Call) SortExpr(field string) (string, bool) {
	switch field {
	case "from":
		return `coalesce(nullif(("from"::text)::json->>'number', ''), ("from"::text)::json->>'name')`, true
	case "to":
		return `coalesce(nullif(("to"::text)::json->>'number', ''), ("to"::text)::json->>'name')`, true
	}

	return "", false
}

тоді rewriteCallSort у сторі вже не потрібен, а клієнт так і шле +from

по суті це той самий підхід, що й sorting у webitel/webitel.go#457.. тому можна буде використати ту ж лібу, щоб це було одним підходом

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])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return "", fmt.Errorf("%w custom not allowed", ErrInvalidSortField, e[0])
return "", fmt.Errorf("%w: %q", ErrInvalidSortField, s)

}

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)
Expand All @@ -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) {
Expand All @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут fields з ріквесту проходять через GetFields і AllowFields(), а в scheme_variables_store.go невідоме поле йде в SELECT як є

пропоную це теж в рамках цього PR зробити..

sort := ""

Expand All @@ -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
}

Expand All @@ -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)
Expand All @@ -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
}

Expand Down
Loading
Loading