Repository navigation
[WTEL-10752]security(search_list): add sort fields check to prevent sql #574
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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) | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Передати екземпляр model.Member{} третім аргументом.
Suggested change
|
||||||
| if err != nil { | ||||||
| return "order by created_at desc" | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. тут невалідний sort неявно стає |
||||||
| } | ||||||
|
|
||||||
| 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 { | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Передати екземпляр model.Member{} третім аргументом.
Suggested change
|
||||||
| return nil, model.NewBadRequestError("store.sql_member.multi_delete.sort", err.Error()) | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| filters := map[string]any{ | ||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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) | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Передати екземпляр model.QuickReply{} третім аргументом для перевірки сортування.
Suggested change
|
||||||
| 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 | ||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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) { | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. додай, будь ласка, табличний тест на |
||||||
| s = strings.TrimSpace(s) | ||||||
| if s == "" { | ||||||
| return "" | ||||||
| return "", nil | ||||||
| } | ||||||
|
|
||||||
| if isRawOrder(s) { | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. думаю, проблема в тому, що через цю перевірку зараз ідуть і клієнтський sort, і наші внутрішні вирази. звідси і дублі сирого SQL у пропоную розділити:
тоді
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
well, першочергово я так і робив, бо не хотів сильно зачіпати обробку на рівні доступу до бази, але обробка запитів до бази була єдиним централізованим місцем, де це все можна відловити якщо робити так, щоб відловлювати клієнтські запити, то це на рівні delivery або app/control треба додавати метод на кожен Get ендпоінт вручну на перевірку, чи філд входить до дозволених для сорту + це потрібно не забувати додавати на нові ендпоінти і так як в go немає махенізму якогось явного аспект орієнтованого програмування, то це потрібно реалізовувати явними викликами методів але я погоджуюся, що так простіше в плані реалізації і викликає менше проблем описаних нижче в коментах і якщо додавання такої перевірки ок в усі методи List в сервісі engine, то мені не важко так переписати
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. по ендпоінтах розносити не треба, перевірка все ж лишається централізовано в різниця лише в тому, що саме ми там валідуємо:
тоді нові ендпоінти захищені автоматично, бо все одно йдуть через приблизно так: // 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
}тоді по суті це той самий підхід, що й |
||||||
| 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]) | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| } | ||||||
|
|
||||||
| 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) | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. тут пропоную це теж в рамках цього PR зробити.. |
||||||
| 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 | ||||||
| } | ||||||
|
|
||||||
|
|
||||||
There was a problem hiding this comment.
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можна прибрати