From 9ac3b2941860a78c354860727d5890004a784842 Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Thu, 4 Nov 2021 14:10:43 +0100 Subject: [PATCH] outpost: add lightweight, anonymous metrics Signed-off-by: Jens Langhammer --- internal/outpost/ak/analytics.go | 80 ++++++++++++++++++++++++++++++++ internal/outpost/ak/api.go | 1 + 2 files changed, 81 insertions(+) create mode 100644 internal/outpost/ak/analytics.go diff --git a/internal/outpost/ak/analytics.go b/internal/outpost/ak/analytics.go new file mode 100644 index 000000000..5f37e1cda --- /dev/null +++ b/internal/outpost/ak/analytics.go @@ -0,0 +1,80 @@ +package ak + +import ( + "bytes" + "crypto/sha512" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "os" + + log "github.com/sirupsen/logrus" + "goauthentik.io/internal/constants" +) + +func exists(name string) bool { + _, err := os.Stat(name) + if err == nil { + return true + } + if errors.Is(err, os.ErrNotExist) { + return false + } + return false +} + +func getEnv() string { + if _, o := os.LookupEnv("KUBERNETES_SERVICE_HOST"); o { + return "kubernetes" + } + if _, o := os.LookupEnv("CI"); o { + return "ci" + } + if exists("/tmp/authentik-mode") { + return "embedded" + } + return "custom" +} + +func analytics(akURL url.URL, on string) { + if _, s := os.LookupEnv("AUTHENTIK_DISABLE_ANALYTICS"); s { + return + } + body := struct { + Domain string `json:"domain"` + Name string `json:"name"` + URL string `json:"url"` + Referrer string `json:"referrer"` + }{ + Domain: "authentik", + Name: "pageview", + URL: fmt.Sprintf("http://localhost/outpost/%s", getEnv()), + Referrer: fmt.Sprintf("%s (%s)", constants.VERSION, constants.BUILD()), + } + b, err := json.Marshal(body) + if err != nil { + log.WithError(err).Debug("test") + } + ua := fmt.Sprintf("%s-%s", akURL.Host, on) + h := sha512.New() + h.Write([]byte(ua)) + + req, err := http.NewRequest("POST", "https://goauthentik.io/api/event", bytes.NewReader(b)) + if err != nil { + log.WithError(err).Debug("test") + } + req.Header.Set("Content-Type", "text/plain") + req.Header.Set("User-Agent", hex.EncodeToString(h.Sum(nil))) + r, err := http.DefaultClient.Do(req) + if err != nil { + log.WithError(err).Debug("test") + } + if r.StatusCode >= 400 { + b, _ := ioutil.ReadAll(r.Body) + log.WithField("status", r.StatusCode).WithField("body", string(b)).Debug("failed") + } +} diff --git a/internal/outpost/ak/api.go b/internal/outpost/ak/api.go index 7db5a2110..6bf1b3c9c 100644 --- a/internal/outpost/ak/api.go +++ b/internal/outpost/ak/api.go @@ -67,6 +67,7 @@ func NewAPIController(akURL url.URL, token string) *APIController { } outpost := outposts.Results[0] doGlobalSetup(outpost.Config) + go analytics(akURL, outpost.Name) log.WithField("name", outpost.Name).Debug("Fetched outpost configuration")