package httpapi import ( "crypto/sha256" "crypto/subtle" "net" "net/http" "strings" "sync" "time" ) type quota struct { tokens float64 updated time.Time watches int } // Secure protects discovery, registration and relay with the same private-network // credential. It is not a per-device identity or multi-tenant authorization system. func Secure(next http.Handler, token string) http.Handler { expected := sha256.Sum256([]byte(token)) var mu sync.Mutex clients := make(map[string]*quota) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { host = r.RemoteAddr } now := time.Now() mu.Lock() q := clients[host] if q == nil { for key, old := range clients { if now.Sub(old.updated) > 5*time.Minute && old.watches == 0 { delete(clients, key) } } if len(clients) >= 4096 { mu.Unlock() http.Error(w, "server busy", 503) return } q = "a{tokens: 400, updated: now} clients[host] = q } q.tokens += now.Sub(q.updated).Seconds() * 200 if q.tokens > 400 { q.tokens = 400 } q.updated = now if q.tokens < 1 { mu.Unlock() w.Header().Set("Retry-After", "1") http.Error(w, "rate limited", 429) return } q.tokens-- mu.Unlock() if r.URL.Path == "/healthz" && r.Method == http.MethodGet { next.ServeHTTP(w, r) return } if token != "" { auth := r.Header.Get("Authorization") actual := sha256.Sum256([]byte(strings.TrimPrefix(auth, "Bearer "))) if !strings.HasPrefix(auth, "Bearer ") || subtle.ConstantTimeCompare(actual[:], expected[:]) != 1 { w.Header().Set("WWW-Authenticate", "Bearer") http.Error(w, "unauthorized", http.StatusUnauthorized) return } } if r.URL.Path == "/watch" { mu.Lock() if q.watches >= 4 { mu.Unlock() http.Error(w, "too many watches", 429) return } q.watches++ mu.Unlock() defer func() { mu.Lock(); q.watches--; mu.Unlock() }() } next.ServeHTTP(w, r) }) }