Chore: Return correct error for name taken and validation error on add/update datasource (#70465)
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -26,6 +27,11 @@ import (
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
)
|
||||
|
||||
const (
|
||||
maxDatasourceNameLen = 190
|
||||
maxDatasourceUrlLen = 255
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
SQLStore Store
|
||||
SecretsStore kvstore.SecretsKVStore
|
||||
@@ -172,6 +178,10 @@ func (s *Service) GetDataSourcesByType(ctx context.Context, query *datasources.G
|
||||
func (s *Service) AddDataSource(ctx context.Context, cmd *datasources.AddDataSourceCommand) (*datasources.DataSource, error) {
|
||||
var dataSource *datasources.DataSource
|
||||
|
||||
if err := validateFields(cmd.Name, cmd.URL); err != nil {
|
||||
return dataSource, err
|
||||
}
|
||||
|
||||
return dataSource, s.db.InTransaction(ctx, func(ctx context.Context) error {
|
||||
var err error
|
||||
|
||||
@@ -231,6 +241,11 @@ func (s *Service) DeleteDataSource(ctx context.Context, cmd *datasources.DeleteD
|
||||
|
||||
func (s *Service) UpdateDataSource(ctx context.Context, cmd *datasources.UpdateDataSourceCommand) (*datasources.DataSource, error) {
|
||||
var dataSource *datasources.DataSource
|
||||
|
||||
if err := validateFields(cmd.Name, cmd.URL); err != nil {
|
||||
return dataSource, err
|
||||
}
|
||||
|
||||
return dataSource, s.db.InTransaction(ctx, func(ctx context.Context) error {
|
||||
var err error
|
||||
|
||||
@@ -243,6 +258,21 @@ func (s *Service) UpdateDataSource(ctx context.Context, cmd *datasources.UpdateD
|
||||
return err
|
||||
}
|
||||
|
||||
if cmd.Name != "" && cmd.Name != dataSource.Name {
|
||||
query := &datasources.GetDataSourceQuery{
|
||||
Name: cmd.Name,
|
||||
OrgID: cmd.OrgID,
|
||||
}
|
||||
exist, err := s.SQLStore.GetDataSource(ctx, query)
|
||||
if exist != nil {
|
||||
return datasources.ErrDataSourceNameExists
|
||||
}
|
||||
|
||||
if err != nil && !errors.Is(err, datasources.ErrDataSourceNotFound) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
err = s.fillWithSecureJSONData(ctx, cmd, dataSource)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -631,6 +661,18 @@ func (s *Service) fillWithSecureJSONData(ctx context.Context, cmd *datasources.U
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateFields(name, url string) error {
|
||||
if len(name) > maxDatasourceNameLen {
|
||||
return datasources.ErrDataSourceNameInvalid.Errorf("max length is %d", maxDatasourceNameLen)
|
||||
}
|
||||
|
||||
if len(url) > maxDatasourceUrlLen {
|
||||
return datasources.ErrDataSourceURLInvalid.Errorf("max length is %d", maxDatasourceUrlLen)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readQuotaConfig(cfg *setting.Cfg) (*quota.Map, error) {
|
||||
limits := "a.Map{}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user