feat: Do not send metrics if the client used DNT or GPC
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
PapaTutuWawa 2024-02-09 21:02:17 +01:00
parent 617b68f43e
commit b2a27cad72
5 changed files with 23 additions and 5 deletions

View File

@ -71,6 +71,8 @@ func handleSubdomain(ctx *context.GlobalContext, domain, cname, path string, req
Path: path,
Referrer: req.Header.Get("Referer"),
UserAgent: req.Header.Get("User-Agent"),
DNT: req.Header.Get("DNT"),
GPC: req.Header.Get("Sec-GPC"),
Writer: w,
Global: ctx,
}

View File

@ -36,6 +36,8 @@ type Context struct {
// HTTP Stuff
Referrer string
UserAgent string
DNT string
GPC string
Writer http.ResponseWriter
// Pointer to the global context

View File

@ -16,12 +16,18 @@ type MetricConfig struct {
Enabled bool
}
// Checks if we should send a metric ping to Loki based on the served path.
func (c *MetricConfig) ShouldSendMetrics(path, userAgent string) bool {
// Checks if we should send a metric ping to page-metrics based on the served path.
func (c *MetricConfig) ShouldSendMetrics(path, userAgent, dnt, gpc string) bool {
if !strings.HasSuffix(path, ".html") || !c.Enabled {
return false
}
// Ignore requests where the user have set "Do-Not-Track" or "Do-Not-Sell-My-Data", even though
// there is no user data and we're not selling it.
if dnt == "1" || gpc == "1" {
return false
}
// Filter out bots
for _, pattern := range *c.BotUserAgents {
if pattern.MatchString(userAgent) {

View File

@ -14,11 +14,19 @@ func TestShouldPing(t *testing.T) {
},
}
if cfg.ShouldSendMetrics("/index.html", "random-bot/v23.5") {
if cfg.ShouldSendMetrics("/index.html", "random-bot/v23.5", "", "") {
t.Fatalf("Accepted bot user-agent")
}
if !cfg.ShouldSendMetrics("/index.html", "Firefox/...") {
if !cfg.ShouldSendMetrics("/index.html", "Firefox/...", "", "") {
t.Fatalf("Rejected real user-agent")
}
if cfg.ShouldSendMetrics("/index.html", "Firefox/...", "1", "") {
t.Fatalf("Ignored DNT")
}
if cfg.ShouldSendMetrics("/index.html", "Firefox/...", "", "1") {
t.Fatalf("Ignored GPC")
}
}

View File

@ -124,7 +124,7 @@ func ServeFile(context *context.Context) {
context.Writer.Write(content)
// Tell Loki about if, if desired
if context.Global.MetricConfig.ShouldSendMetrics(path, context.UserAgent) {
if context.Global.MetricConfig.ShouldSendMetrics(path, context.UserAgent, context.DNT, context.GPC) {
context.Global.MetricConfig.SendMetricPing(context.Domain, path, context.Referrer)
}
}