feat: harden HTTP server with rate limiting, request timeouts, and sanitized error messages
This commit is contained in:
+9
-1
@@ -7,6 +7,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
@@ -38,7 +39,14 @@ var serveCmd = &cobra.Command{
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
fmt.Fprintf(os.Stdout, "listening on %s\n", addr)
|
fmt.Fprintf(os.Stdout, "listening on %s\n", addr)
|
||||||
if err := http.ListenAndServe(addr, handler); err != nil {
|
srv := &http.Server{
|
||||||
|
Addr: addr,
|
||||||
|
Handler: handler,
|
||||||
|
ReadTimeout: 5 * time.Second,
|
||||||
|
WriteTimeout: 30 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
|
}
|
||||||
|
if err := srv.ListenAndServe(); err != nil {
|
||||||
fmt.Fprintln(os.Stderr, err)
|
fmt.Fprintln(os.Stderr, err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
@@ -144,13 +144,13 @@ func (h *authHandler) callback(w http.ResponseWriter, r *http.Request) {
|
|||||||
oauth2.SetAuthURLParam("code_verifier", pending.verifier),
|
oauth2.SetAuthURLParam("code_verifier", pending.verifier),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "token exchange failed: "+err.Error(), http.StatusBadRequest)
|
http.Error(w, "token exchange failed", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
username, err := h.extractUsername(r.Context(), token)
|
username, err := h.extractUsername(r.Context(), token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "failed to identify user: "+err.Error(), http.StatusInternalServerError)
|
http.Error(w, "failed to identify user", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +177,7 @@ func (h *authHandler) deviceStart(w http.ResponseWriter, r *http.Request) {
|
|||||||
oauth2.SetAuthURLParam("client_secret", h.cfg.ClientSecret),
|
oauth2.SetAuthURLParam("client_secret", h.cfg.ClientSecret),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusBadGateway, "device authorization request failed: "+err.Error())
|
writeError(w, http.StatusBadGateway, "device authorization request failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,7 +196,7 @@ func (h *authHandler) deviceStart(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
if p := h.pendingDevice[loginID]; p != nil {
|
if p := h.pendingDevice[loginID]; p != nil {
|
||||||
p.err = err.Error()
|
p.err = "device token exchange failed"
|
||||||
}
|
}
|
||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
return
|
return
|
||||||
@@ -206,7 +206,7 @@ func (h *authHandler) deviceStart(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
if p := h.pendingDevice[loginID]; p != nil {
|
if p := h.pendingDevice[loginID]; p != nil {
|
||||||
p.err = "failed to identify user: " + err.Error()
|
p.err = "failed to identify user"
|
||||||
}
|
}
|
||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package serve
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type visitor struct {
|
||||||
|
tokens float64
|
||||||
|
lastSeen time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type rateLimiter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
visitors map[string]*visitor
|
||||||
|
rate float64 // tokens per second
|
||||||
|
burst float64 // max tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRateLimiter(rate float64, burst int) *rateLimiter {
|
||||||
|
rl := &rateLimiter{
|
||||||
|
visitors: make(map[string]*visitor),
|
||||||
|
rate: rate,
|
||||||
|
burst: float64(burst),
|
||||||
|
}
|
||||||
|
go rl.cleanup()
|
||||||
|
return rl
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rl *rateLimiter) allow(ip string) bool {
|
||||||
|
rl.mu.Lock()
|
||||||
|
defer rl.mu.Unlock()
|
||||||
|
|
||||||
|
v, exists := rl.visitors[ip]
|
||||||
|
now := time.Now()
|
||||||
|
if !exists {
|
||||||
|
rl.visitors[ip] = &visitor{tokens: rl.burst - 1, lastSeen: now}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
elapsed := now.Sub(v.lastSeen).Seconds()
|
||||||
|
v.lastSeen = now
|
||||||
|
v.tokens += elapsed * rl.rate
|
||||||
|
if v.tokens > rl.burst {
|
||||||
|
v.tokens = rl.burst
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.tokens < 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
v.tokens--
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rl *rateLimiter) cleanup() {
|
||||||
|
for range time.Tick(time.Minute) {
|
||||||
|
rl.mu.Lock()
|
||||||
|
for ip, v := range rl.visitors {
|
||||||
|
if time.Since(v.lastSeen) > 5*time.Minute {
|
||||||
|
delete(rl.visitors, ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rl.mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func clientIP(r *http.Request) string {
|
||||||
|
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
if ip := r.Header.Get("X-Real-IP"); ip != "" {
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
return r.RemoteAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
func withRateLimit(rl *rateLimiter, next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !rl.allow(clientIP(r)) {
|
||||||
|
writeError(w, http.StatusTooManyRequests, "rate limit exceeded")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
+7
-5
@@ -24,6 +24,8 @@ func New(newSvc func(user string) (service.NodeService, error), oidcCfg *store.O
|
|||||||
mux.HandleFunc("DELETE /nodes/{id}", s.deleteNode)
|
mux.HandleFunc("DELETE /nodes/{id}", s.deleteNode)
|
||||||
mux.HandleFunc("GET /users", s.listUsers)
|
mux.HandleFunc("GET /users", s.listUsers)
|
||||||
mux.HandleFunc("POST /users", s.addUser)
|
mux.HandleFunc("POST /users", s.addUser)
|
||||||
|
rl := newRateLimiter(10, 30) // 10 req/s sustained, burst of 30
|
||||||
|
|
||||||
if oidcCfg != nil {
|
if oidcCfg != nil {
|
||||||
ah, err := newAuthHandler(*oidcCfg)
|
ah, err := newAuthHandler(*oidcCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -33,9 +35,9 @@ func New(newSvc func(user string) (service.NodeService, error), oidcCfg *store.O
|
|||||||
mux.HandleFunc("POST /auth/device/start", ah.deviceStart)
|
mux.HandleFunc("POST /auth/device/start", ah.deviceStart)
|
||||||
mux.HandleFunc("GET /auth/callback", ah.callback)
|
mux.HandleFunc("GET /auth/callback", ah.callback)
|
||||||
mux.HandleFunc("GET /auth/poll", ah.poll)
|
mux.HandleFunc("GET /auth/poll", ah.poll)
|
||||||
return withSessionAuth(ah, mux), nil
|
return withRateLimit(rl, withSessionAuth(ah, mux)), nil
|
||||||
}
|
}
|
||||||
return mux, nil
|
return withRateLimit(rl, mux), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type server struct {
|
type server struct {
|
||||||
@@ -53,7 +55,7 @@ func (s *server) svc(w http.ResponseWriter, r *http.Request) (service.NodeServic
|
|||||||
}
|
}
|
||||||
svc, err := s.newSvc(user)
|
svc, err := s.newSvc(user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, "internal error")
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
return svc, true
|
return svc, true
|
||||||
@@ -96,7 +98,7 @@ func (s *server) listNodes(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
nodes, err := svc.List(filter)
|
nodes, err := svc.List(filter)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, "internal error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, nodes)
|
writeJSON(w, nodes)
|
||||||
@@ -171,7 +173,7 @@ func (s *server) listUsers(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
users, err := svc.ListUsers()
|
users, err := svc.ListUsers()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, "internal error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, users)
|
writeJSON(w, users)
|
||||||
|
|||||||
Reference in New Issue
Block a user