mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Parse template when validating it (#49282)
This commit is contained in:
parent
0a95d493e3
commit
e8b498fe8b
@ -2,6 +2,7 @@ package definitions
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
@ -74,6 +75,11 @@ func (t *MessageTemplate) Validate() error {
|
||||
return fmt.Errorf("template must have content")
|
||||
}
|
||||
|
||||
_, err := template.New("").Parse(t.Template)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid template: %w", err)
|
||||
}
|
||||
|
||||
content := strings.TrimSpace(t.Template)
|
||||
found, err := regexp.MatchString(`\{\{\s*define`, content)
|
||||
if err != nil {
|
||||
|
@ -228,6 +228,42 @@ func TestTemplateService(t *testing.T) {
|
||||
|
||||
require.Equal(t, tmpl.Template, result.Template)
|
||||
})
|
||||
|
||||
t.Run("rejects syntactically invalid template", func(t *testing.T) {
|
||||
sut := createTemplateServiceSut()
|
||||
tmpl := definitions.MessageTemplate{
|
||||
Name: "name",
|
||||
Template: "{{ .MyField }",
|
||||
}
|
||||
sut.config.(*MockAMConfigStore).EXPECT().
|
||||
getsConfig(models.AlertConfiguration{
|
||||
AlertmanagerConfiguration: defaultConfig,
|
||||
})
|
||||
sut.config.(*MockAMConfigStore).EXPECT().saveSucceeds()
|
||||
sut.prov.(*MockProvisioningStore).EXPECT().saveSucceeds()
|
||||
|
||||
_, err := sut.SetTemplate(context.Background(), 1, tmpl)
|
||||
|
||||
require.ErrorIs(t, err, ErrValidation)
|
||||
})
|
||||
|
||||
t.Run("does not reject template with unknown field", func(t *testing.T) {
|
||||
sut := createTemplateServiceSut()
|
||||
tmpl := definitions.MessageTemplate{
|
||||
Name: "name",
|
||||
Template: "{{ .NotAField }}",
|
||||
}
|
||||
sut.config.(*MockAMConfigStore).EXPECT().
|
||||
getsConfig(models.AlertConfiguration{
|
||||
AlertmanagerConfiguration: defaultConfig,
|
||||
})
|
||||
sut.config.(*MockAMConfigStore).EXPECT().saveSucceeds()
|
||||
sut.prov.(*MockProvisioningStore).EXPECT().saveSucceeds()
|
||||
|
||||
_, err := sut.SetTemplate(context.Background(), 1, tmpl)
|
||||
|
||||
require.NoError(t, err)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("deleting templates", func(t *testing.T) {
|
||||
|
Loading…
Reference in New Issue
Block a user