first commit
This commit is contained in:
25
internal/http/middleware/adminauth.go
Normal file
25
internal/http/middleware/adminauth.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func AdminAuth(apiKey string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
provided := r.Header.Get("X-API-Key")
|
||||
if provided == "" || subtle.ConstantTimeCompare([]byte(provided), []byte(apiKey)) != 1 {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"error": "Unauthorized",
|
||||
"detail": "missing or invalid X-API-Key",
|
||||
})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
19
internal/http/middleware/bodylimit.go
Normal file
19
internal/http/middleware/bodylimit.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
// BodyLimit caps request body size. Returns 413 if exceeded.
|
||||
func BodyLimit(maxBytes int64) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.ContentLength > maxBytes {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
||||
_, _ = w.Write([]byte(`{"error":"PayloadTooLarge","detail":"request body exceeds limit"}`))
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
18
internal/http/middleware/cors.go
Normal file
18
internal/http/middleware/cors.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
func CORS(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("Access-Control-Allow-Origin", "*")
|
||||
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
h.Set("Access-Control-Allow-Headers", "Content-Type, X-API-Key, Authorization")
|
||||
h.Set("Access-Control-Max-Age", "86400")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
49
internal/http/middleware/logging.go
Normal file
49
internal/http/middleware/logging.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
applog "github.com/noderunners/nip05api/internal/log"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusRecorder) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
b := make([]byte, 8)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-ID")
|
||||
if id == "" {
|
||||
id = newRequestID()
|
||||
}
|
||||
w.Header().Set("X-Request-ID", id)
|
||||
ctx := applog.WithRequestID(r.Context(), id)
|
||||
rec := &statusRecorder{ResponseWriter: w, status: 200}
|
||||
start := time.Now()
|
||||
next.ServeHTTP(rec, r.WithContext(ctx))
|
||||
slog.Info("http",
|
||||
"request_id", id,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rec.status,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"remote", r.RemoteAddr,
|
||||
)
|
||||
})
|
||||
}
|
||||
27
internal/http/middleware/ratelimit.go
Normal file
27
internal/http/middleware/ratelimit.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/httprate"
|
||||
)
|
||||
|
||||
// RateLimit returns a middleware that limits requests per minute by IP.
|
||||
// Admin routes are skipped.
|
||||
func RateLimit(perMin int) func(http.Handler) http.Handler {
|
||||
if perMin <= 0 {
|
||||
return func(next http.Handler) http.Handler { return next }
|
||||
}
|
||||
limiter := httprate.LimitByIP(perMin, time.Minute)
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/v1/admin/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
limiter(next).ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
34
internal/http/middleware/realip.go
Normal file
34
internal/http/middleware/realip.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RealIP rewrites RemoteAddr from common reverse-proxy headers so downstream
|
||||
// rate limiters and loggers see the original client IP. Trusted unconditionally;
|
||||
// terminate this header at your proxy.
|
||||
func RealIP(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if ip := clientIP(r); ip != "" {
|
||||
r.RemoteAddr = ip + ":0"
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func clientIP(r *http.Request) string {
|
||||
if ip := r.Header.Get("X-Real-IP"); ip != "" {
|
||||
if parsed := net.ParseIP(strings.TrimSpace(ip)); parsed != nil {
|
||||
return parsed.String()
|
||||
}
|
||||
}
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
first := strings.TrimSpace(strings.SplitN(xff, ",", 2)[0])
|
||||
if parsed := net.ParseIP(first); parsed != nil {
|
||||
return parsed.String()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
42
internal/http/middleware/recoverer.go
Normal file
42
internal/http/middleware/recoverer.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
)
|
||||
|
||||
// Recoverer turns panics into 500 JSON responses without leaking the stack to
|
||||
// clients. The full stack is logged at error level.
|
||||
func Recoverer(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rv := recover(); rv != nil {
|
||||
slog.Error("panic recovered",
|
||||
"path", r.URL.Path,
|
||||
"method", r.Method,
|
||||
"err", rv,
|
||||
"stack", string(debug.Stack()),
|
||||
)
|
||||
if !headerWritten(w) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"error": "InternalError",
|
||||
"detail": "internal server error",
|
||||
})
|
||||
}
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// headerWritten is best-effort; if the response is hijacked we skip writing.
|
||||
func headerWritten(w http.ResponseWriter) bool {
|
||||
if rw, ok := w.(interface{ Status() int }); ok {
|
||||
return rw.Status() != 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user