feat: enhance auth, add input validation and pagination
- Add IP validation in auth handler with detailed logging - Implement apiKeyMiddleware helper for API key verification - Add IP and CIDR validation for whitelist operations - Support pagination for listing temp and permanent entries - Add parsePagination helper to extract limit and offset - Include comprehensive unit tests for IsIP, IsCIDR, and IPMatch
This commit is contained in:
94
auth.go
94
auth.go
@@ -12,6 +12,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var startTime = time.Now()
|
||||
|
||||
func CheckAuth(db *sql.DB, r *http.Request) bool {
|
||||
ip := r.Header.Get("X-Real-IP")
|
||||
if ip == "" {
|
||||
@@ -30,14 +32,33 @@ func CheckAuth(db *sql.DB, r *http.Request) bool {
|
||||
|
||||
func authHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !CheckAuth(db, r) {
|
||||
ip := r.Header.Get("X-Real-IP")
|
||||
if ip == "" {
|
||||
slog.Warn("auth denied: no X-Real-IP", "remote_addr", r.RemoteAddr)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if !CheckAuth(db, r) {
|
||||
slog.Warn("auth denied", "ip", ip)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
slog.Info("auth allowed", "ip", ip)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func apiKeyMiddleware(next http.HandlerFunc, token string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, token) {
|
||||
slog.Warn("unauthorized API access")
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func whitelistTempHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, cfg.APIToken) {
|
||||
@@ -62,6 +83,10 @@ func whitelistTempHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
http.Error(w, "ip and ttl_seconds required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !IsIP(req.IP) {
|
||||
http.Error(w, "invalid IP address", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
clientIP := getClientIP(r)
|
||||
if err := AddTempEntry(db, req.IP, req.TTLSeconds, req.Reason, clientIP); err != nil {
|
||||
slog.Error("failed to add temp entry", "error", err)
|
||||
@@ -79,7 +104,12 @@ func whitelistListHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
entries, err := ListTempEntries(db)
|
||||
limit, offset, err := parsePagination(r)
|
||||
if err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
entries, err := ListTempEntriesPaginated(db, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, "database error", http.StatusInternalServerError)
|
||||
return
|
||||
@@ -95,7 +125,12 @@ func permWhitelistListHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
entries, err := ListPermEntries(db)
|
||||
limit, offset, err := parsePagination(r)
|
||||
if err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
entries, err := ListPermEntriesPaginated(db, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, "database error", http.StatusInternalServerError)
|
||||
return
|
||||
@@ -228,6 +263,10 @@ func permWhitelistAddHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
http.Error(w, "entry required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !IsIP(req.Entry) && !IsCIDR(req.Entry) {
|
||||
http.Error(w, "invalid entry (must be valid IP or CIDR range)", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
ok, err := AddPermanentEntry(db, req.Entry, getClientIP(r))
|
||||
if err != nil {
|
||||
slog.Error("failed to add perm entry", "error", err)
|
||||
@@ -274,7 +313,50 @@ func verifyAPIKey(r *http.Request, expectedToken string) bool {
|
||||
return r.Header.Get("Authorization") == "Bearer "+expectedToken
|
||||
}
|
||||
|
||||
func statusHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.Write([]byte("ok\n"))
|
||||
func statusHandler(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var permCount int
|
||||
var tempCount int
|
||||
var dbOK bool
|
||||
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM perm_whitelist`).Scan(&permCount); err == nil {
|
||||
dbOK = true
|
||||
}
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM temp_whitelist WHERE expires_at > ?`, time.Now().Format(time.RFC3339)).Scan(&tempCount); err == nil {
|
||||
dbOK = true
|
||||
} else {
|
||||
dbOK = false
|
||||
}
|
||||
|
||||
health := map[string]interface{}{
|
||||
"status": "ok",
|
||||
"uptime": time.Since(startTime).String(),
|
||||
"perm_whitelist_count": permCount,
|
||||
"temp_whitelist_count": tempCount,
|
||||
"db_ok": dbOK,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(health)
|
||||
}
|
||||
}
|
||||
|
||||
func parsePagination(r *http.Request) (int, int, error) {
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
offsetStr := r.URL.Query().Get("offset")
|
||||
|
||||
limit := 200
|
||||
offset := 0
|
||||
|
||||
if limitStr != "" {
|
||||
if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 && parsed <= 1000 {
|
||||
limit = parsed
|
||||
}
|
||||
}
|
||||
if offsetStr != "" {
|
||||
if parsed, err := strconv.Atoi(offsetStr); err == nil && parsed >= 0 {
|
||||
offset = parsed
|
||||
}
|
||||
}
|
||||
return limit, offset, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user