automatically add host and viewer information to errors (#5807)

This commit is contained in:
Roberto Dip 2022-05-20 11:09:50 -03:00 committed by GitHub
parent a5ae8dce0e
commit 3954648c28
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 1 deletions

View file

@ -18,6 +18,9 @@ import (
"fmt"
"strings"
"time"
"github.com/fleetdm/fleet/v4/server/contexts/host"
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
)
type key int
@ -76,8 +79,25 @@ func setMetadata(ctx context.Context, data map[string]interface{}) map[string]in
data = map[string]interface{}{}
}
// TODO: add more metadata from ctx
data["timestamp"] = nowFn().Format(time.RFC3339)
if h, ok := host.FromContext(ctx); ok {
data["host"] = map[string]interface{}{
"platform": h.Platform,
"osquery_version": h.OsqueryVersion,
}
}
if v, ok := viewer.FromContext(ctx); ok {
vdata := map[string]interface{}{}
data["viewer"] = vdata
vdata["is_logged_in"] = v.IsLoggedIn()
if v.User != nil {
vdata["sso_enabled"] = v.User.SSOEnabled
}
}
return data
}

View file

@ -10,6 +10,9 @@ import (
"testing"
"time"
"github.com/fleetdm/fleet/v4/server/contexts/host"
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
"github.com/fleetdm/fleet/v4/server/fleet"
pkgerrors "github.com/pkg/errors" //nolint:depguard
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -341,3 +344,23 @@ func TestHandle(t *testing.T) {
Handle(ctx, err)
})
}
func TestAdditionalMetadata(t *testing.T) {
t.Run("saves additional data about the host if present", func(t *testing.T) {
ctx, cleanup := setup()
defer cleanup()
hctx := host.NewContext(ctx, &fleet.Host{Platform: "test_platform", OsqueryVersion: "5.0"})
err := New(hctx, "with host context").(*FleetError)
require.JSONEq(t, string(err.data), `{"host":{"osquery_version":"5.0","platform":"test_platform"},"timestamp":"1969-06-19T21:44:05Z"}`)
})
t.Run("saves additional data about the viewer if present", func(t *testing.T) {
ctx, cleanup := setup()
defer cleanup()
vctx := viewer.NewContext(ctx, viewer.Viewer{Session: &fleet.Session{ID: 1}, User: &fleet.User{SSOEnabled: true}})
err := New(vctx, "with host context").(*FleetError)
require.JSONEq(t, string(err.data), `{"viewer":{"is_logged_in":true,"sso_enabled":true},"timestamp":"1969-06-19T21:44:05Z"}`)
})
}