From a7e5f2690a6e614a075115271371d7ad8931e52a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Mon, 26 Jul 2021 14:46:44 +0200 Subject: [PATCH] Prevent long UIDs from being used --- dashboard/dashboard.go | 15 ++++++++++++++- dashboard/dashboard_test.go | 10 ++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/dashboard/dashboard.go b/dashboard/dashboard.go index 4189a469..357d2049 100644 --- a/dashboard/dashboard.go +++ b/dashboard/dashboard.go @@ -1,6 +1,10 @@ package dashboard import ( + // We're not using it for security stuff, so it's fine. + //nolint:gosec + "crypto/sha1" + "encoding/hex" "encoding/json" "github.com/K-Phoen/grabana/row" @@ -120,7 +124,16 @@ func ID(id uint) Option { // UID sets the UID used by the dashboard. func UID(uid string) Option { return func(builder *Builder) { - builder.board.UID = uid + validUID := uid + + if len(uid) > 40 { + // We're not using it for security stuff, so it's fine. + //nolint:gosec + sha := sha1.Sum([]byte(uid)) + validUID = hex.EncodeToString(sha[:]) + } + + builder.board.UID = validUID } } diff --git a/dashboard/dashboard_test.go b/dashboard/dashboard_test.go index c5c80e4c..4fa9d62a 100644 --- a/dashboard/dashboard_test.go +++ b/dashboard/dashboard_test.go @@ -74,6 +74,16 @@ func TestDashboardUIDCanBeSet(t *testing.T) { req.Equal("foo", panel.board.UID) } +func TestDashboardUIDWillBeHashedWhenTooLongForGrafana(t *testing.T) { + req := require.New(t) + + originalUID := "this-uid-is-more-than-forty-characters-and-grafana-does-not-like-it" + panel := New("", UID(originalUID)) + + req.NotEqual(originalUID, panel.board.UID) + req.Len(panel.board.UID, 40) +} + func TestDashboardCanBeMadeReadOnly(t *testing.T) { req := require.New(t)