api: Validate dashboards on save via coremodels, behind feature toggle (#48252)

* Add coremodelValidation feature flag

* coremodels: use stubs when feature flag is off

* api: validate dashboards on save

* Need pointer receiver for FeatureManager

* Update dashboard Go model

* Align doc comments

* Include CoremodelRegistry in test

* Wedge coremodel in on all test cases, ugh

* Ugh fix comment again

* Update pkg/framework/coremodel/staticregistry/provide.go

Co-authored-by: Artur Wierzbicki <wierzbicki.artur.94@gmail.com>

* Update Thema (and its deps) for better errs

* omg whitespace

Co-authored-by: Artur Wierzbicki <wierzbicki.artur.94@gmail.com>
This commit is contained in:
sam boyer
2022-05-21 20:44:12 -04:00
committed by GitHub
parent 03fe1435a0
commit a3402641d6
11 changed files with 111 additions and 15 deletions

View File

@@ -16,11 +16,14 @@ import (
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/components/dashdiffs"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/coremodel/dashboard"
"github.com/grafana/grafana/pkg/cuectx"
"github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/guardian"
pref "github.com/grafana/grafana/pkg/services/preference"
"github.com/grafana/grafana/pkg/services/star"
@@ -305,6 +308,28 @@ func (hs *HTTPServer) PostDashboard(c *models.ReqContext) response.Response {
if err := web.Bind(c.Req, &cmd); err != nil {
return response.Error(http.StatusBadRequest, "bad request data", err)
}
if hs.Features.IsEnabled(featuremgmt.FlagValidateDashboardsOnSave) {
// Ideally, coremodel validation calls would be integrated into the web
// framework. But this does the job for now.
if cm, has := hs.CoremodelRegistry.Get("dashboard"); has {
schv, err := cmd.Dashboard.Get("schemaVersion").Int()
// Only try to validate if the schemaVersion is at least the handoff version
// (the minimum schemaVersion against which the dashboard schema is known to
// work), or if schemaVersion is absent (which will happen once the Thema
// schema becomes canonical).
if err != nil || schv >= dashboard.HandoffSchemaVersion {
// Can't fail, web.Bind() already ensured it's valid JSON
b, _ := cmd.Dashboard.Bytes()
v, _ := cuectx.JSONtoCUE("dashboard.json", b)
if _, err := cm.CurrentSchema().Validate(v); err != nil {
return response.Error(http.StatusBadRequest, "invalid dashboard json", err)
}
}
}
}
return hs.postDashboard(c, cmd)
}