0.38.6_agent_hotfix

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-19 08:53:34 +01:00
1 parent 1239ff524d
commit d4a604970e
14 files changed
+478 -162

No files matched your search

+41 -1
View File
@@ -18,7 +18,11 @@ import (
"time"
)
const maxEnrollments = 8
const (
maxEnrollments = 8
enrollBurst = 6
enrollRefillPerSecond = 1.0
)
type enrollment struct {
TokenSHA256 string `json:"token_sha256"`
@@ -131,8 +135,38 @@ func (e *enroller) redeem(cfg config, presented string, now time.Time) bool {
return true
}
// The limiter is deliberately global: it has constant memory usage even if
// callers rotate source IPs. Enrollment is a rare administrative operation.
type enrollLimiter struct {
mu sync.Mutex
tokens float64
last time.Time
}
func (l *enrollLimiter) allow(now time.Time) bool {
l.mu.Lock()
defer l.mu.Unlock()
if l.last.IsZero() {
l.tokens = enrollBurst
l.last = now
}
if elapsed := now.Sub(l.last).Seconds(); elapsed > 0 {
l.tokens += elapsed * enrollRefillPerSecond
if l.tokens > enrollBurst {
l.tokens = enrollBurst
}
l.last = now
}
if l.tokens < 1 {
return false
}
l.tokens--
return true
}
func enrollHandler(cfg config) http.HandlerFunc {
state := &enroller{}
limiter := &enrollLimiter{}
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
@@ -142,6 +176,12 @@ func enrollHandler(cfg config) http.HandlerFunc {
http.Error(w, "enrollment requires HTTPS", http.StatusForbidden)
return
}
w.Header().Set("Cache-Control", "no-store")
if !limiter.allow(time.Now()) {
w.Header().Set("Retry-After", "1")
http.Error(w, "too many enrollment attempts", http.StatusTooManyRequests)
return
}
auth := strings.TrimSpace(r.Header.Get("Authorization"))
presented, ok := strings.CutPrefix(auth, "Bearer ")
if !ok || !state.redeem(cfg, strings.TrimSpace(presented), time.Now()) {