Complete rewrite and re-architecture Osmedeus Engine in v5

This commit is contained in:
j3ssie
2026-01-18 19:32:24 +08:00
commit 7a2c5a5dc9
743 changed files with 99767 additions and 0 deletions
+118
View File
@@ -0,0 +1,118 @@
package middleware
import (
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
"github.com/j3ssie/osmedeus/v5/internal/config"
)
// Claims represents JWT claims
type Claims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
// JWTAuth creates JWT authentication middleware
func JWTAuth(cfg *config.Config) fiber.Handler {
return func(c *fiber.Ctx) error {
// Get token from Authorization header
authHeader := c.Get("Authorization")
if authHeader == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": true,
"message": "Missing authorization header",
})
}
// Check Bearer prefix
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": true,
"message": "Invalid authorization header format",
})
}
tokenString := parts[1]
// Parse and validate token
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(cfg.Server.JWT.SecretSigningKey), nil
})
if err != nil || !token.Valid {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": true,
"message": "Invalid or expired token",
})
}
// Store claims in context
c.Locals("user", claims)
return c.Next()
}
}
// GenerateToken generates a JWT token
func GenerateToken(username string, cfg *config.Config) (string, error) {
expiration := time.Duration(cfg.Server.JWT.ExpirationMinutes) * time.Minute
claims := &Claims{
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expiration)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(cfg.Server.JWT.SecretSigningKey))
}
// GetUser gets the current user from context
func GetUser(c *fiber.Ctx) *Claims {
claims, ok := c.Locals("user").(*Claims)
if !ok {
return nil
}
return claims
}
// APIKeyAuth creates API key authentication middleware
func APIKeyAuth(cfg *config.Config) fiber.Handler {
return func(c *fiber.Ctx) error {
apiKey := c.Get("x-osm-api-key")
if !isValidAPIKey(apiKey, cfg.Server.AuthAPIKey) {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": true,
"message": "Invalid or missing API key",
})
}
return c.Next()
}
}
// isValidAPIKey validates the provided API key against expected value
func isValidAPIKey(provided, expected string) bool {
// Reject empty or whitespace-only keys
trimmed := strings.TrimSpace(provided)
if trimmed == "" {
return false
}
// Reject suspicious placeholder values
lower := strings.ToLower(trimmed)
if lower == "null" || lower == "undefined" || lower == "nil" {
return false
}
// Compare with expected (case-sensitive, exact match)
return provided == expected
}
+117
View File
@@ -0,0 +1,117 @@
package middleware
import (
"net/http/httptest"
"testing"
"github.com/gofiber/fiber/v2"
"github.com/j3ssie/osmedeus/v5/internal/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAPIKeyAuth(t *testing.T) {
tests := []struct {
name string
headerKey string
configKey string
wantStatus int
}{
{"valid key", "secret-key-123", "secret-key-123", fiber.StatusOK},
{"missing header", "", "secret-key-123", fiber.StatusUnauthorized},
{"whitespace only", " ", "secret-key-123", fiber.StatusUnauthorized},
{"null string", "null", "secret-key-123", fiber.StatusUnauthorized},
{"NULL uppercase", "NULL", "secret-key-123", fiber.StatusUnauthorized},
{"undefined string", "undefined", "secret-key-123", fiber.StatusUnauthorized},
{"nil string", "nil", "secret-key-123", fiber.StatusUnauthorized},
{"wrong key", "wrong-key", "secret-key-123", fiber.StatusUnauthorized},
{"case mismatch", "Secret-Key-123", "secret-key-123", fiber.StatusUnauthorized},
// Note: HTTP headers with leading/trailing whitespace are trimmed by the HTTP library
{"leading whitespace trimmed by http", " secret-key-123", "secret-key-123", fiber.StatusOK},
{"trailing whitespace trimmed by http", "secret-key-123 ", "secret-key-123", fiber.StatusOK},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := &config.Config{
Server: config.ServerConfig{
EnabledAuthAPI: true,
AuthAPIKey: tt.configKey,
},
}
app := fiber.New()
app.Use(APIKeyAuth(cfg))
app.Get("/test", func(c *fiber.Ctx) error {
return c.SendString("ok")
})
req := httptest.NewRequest("GET", "/test", nil)
if tt.headerKey != "" {
req.Header.Set("x-osm-api-key", tt.headerKey)
}
resp, err := app.Test(req)
require.NoError(t, err)
assert.Equal(t, tt.wantStatus, resp.StatusCode)
})
}
}
func TestIsValidAPIKey(t *testing.T) {
tests := []struct {
name string
provided string
expected string
want bool
}{
{"exact match", "my-key", "my-key", true},
{"empty provided", "", "my-key", false},
{"whitespace only", " ", "my-key", false},
{"null lowercase", "null", "my-key", false},
{"null uppercase", "NULL", "my-key", false},
{"null mixed case", "Null", "my-key", false},
{"undefined lowercase", "undefined", "my-key", false},
{"undefined uppercase", "UNDEFINED", "my-key", false},
{"nil lowercase", "nil", "my-key", false},
{"nil uppercase", "NIL", "my-key", false},
{"wrong key", "other", "my-key", false},
{"case sensitive mismatch", "My-Key", "my-key", false},
{"leading whitespace", " my-key", "my-key", false},
{"trailing whitespace", "my-key ", "my-key", false},
{"both have whitespace identical", " my-key ", " my-key ", true}, // exact match even with whitespace
{"special characters", "my-key!@#$%", "my-key!@#$%", true},
{"long key", "this-is-a-very-long-api-key-with-many-characters-1234567890", "this-is-a-very-long-api-key-with-many-characters-1234567890", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := isValidAPIKey(tt.provided, tt.expected)
assert.Equal(t, tt.want, got)
})
}
}
func TestAPIKeyAuth_ResponseBody(t *testing.T) {
cfg := &config.Config{
Server: config.ServerConfig{
EnabledAuthAPI: true,
AuthAPIKey: "test-key",
},
}
app := fiber.New()
app.Use(APIKeyAuth(cfg))
app.Get("/test", func(c *fiber.Ctx) error {
return c.SendString("ok")
})
// Test that invalid key returns proper error response
req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("x-osm-api-key", "wrong-key")
resp, err := app.Test(req)
require.NoError(t, err)
assert.Equal(t, fiber.StatusUnauthorized, resp.StatusCode)
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
}
+144
View File
@@ -0,0 +1,144 @@
package middleware
import (
"bytes"
"encoding/json"
"io"
"github.com/gofiber/fiber/v2"
"github.com/j3ssie/osmedeus/v5/internal/logger"
"go.uber.org/zap"
)
// DebugRequestBody logs request bodies for POST/PUT/PATCH requests in debug mode
func DebugRequestBody() fiber.Handler {
return func(c *fiber.Ctx) error {
log := logger.Get()
method := c.Method()
// Only log bodies for methods that typically have request bodies
if method == "POST" || method == "PUT" || method == "PATCH" {
body := c.Body()
if len(body) > 0 {
// Try to pretty-print JSON
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, body, "", " "); err == nil {
log.Debug("Request body",
zap.String("method", method),
zap.String("path", c.Path()),
zap.String("body", prettyJSON.String()),
)
} else {
// Not JSON or invalid JSON, log as-is (truncated if too long)
bodyStr := string(body)
if len(bodyStr) > 2000 {
bodyStr = bodyStr[:2000] + "... (truncated)"
}
log.Debug("Request body",
zap.String("method", method),
zap.String("path", c.Path()),
zap.String("body", bodyStr),
)
}
}
}
// Log query parameters for all requests
if c.Request().URI().QueryString() != nil && len(c.Request().URI().QueryString()) > 0 {
log.Debug("Request query params",
zap.String("method", method),
zap.String("path", c.Path()),
zap.String("query", string(c.Request().URI().QueryString())),
)
}
return c.Next()
}
}
// DebugErrorHandler wraps responses to log detailed error information
func DebugErrorHandler(c *fiber.Ctx, err error) error {
log := logger.Get()
code := fiber.StatusInternalServerError
if e, ok := err.(*fiber.Error); ok {
code = e.Code
}
// Log detailed error information
log.Error("Request error",
zap.String("method", c.Method()),
zap.String("path", c.Path()),
zap.Int("status", code),
zap.Error(err),
zap.String("ip", c.IP()),
zap.String("user_agent", c.Get("User-Agent")),
)
// Log request body for failed POST/PUT/PATCH requests
if c.Method() == "POST" || c.Method() == "PUT" || c.Method() == "PATCH" {
// Re-read the body since it might have been consumed
body := c.Body()
if len(body) > 0 {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, body, "", " "); err == nil {
log.Error("Failed request body",
zap.String("body", prettyJSON.String()),
)
} else {
bodyStr := string(body)
if len(bodyStr) > 2000 {
bodyStr = bodyStr[:2000] + "... (truncated)"
}
log.Error("Failed request body",
zap.String("body", bodyStr),
)
}
}
}
// Return detailed error response in debug mode
return c.Status(code).JSON(fiber.Map{
"error": true,
"message": err.Error(),
"code": code,
"path": c.Path(),
"method": c.Method(),
})
}
// DebugResponseLogger logs response status for debugging
func DebugResponseLogger() fiber.Handler {
return func(c *fiber.Ctx) error {
err := c.Next()
log := logger.Get()
status := c.Response().StatusCode()
// Log non-2xx responses with more detail
if status >= 400 {
log.Debug("Response",
zap.String("method", c.Method()),
zap.String("path", c.Path()),
zap.Int("status", status),
zap.Int("body_size", len(c.Response().Body())),
)
}
return err
}
}
// Ensure body can be re-read for logging (use before DebugRequestBody)
func BodyReusable() fiber.Handler {
return func(c *fiber.Ctx) error {
// Store original body so it can be read multiple times
body := c.Body()
c.Request().SetBody(body)
// Also set body reader for handlers that use io.Reader
c.Request().SetBodyStream(io.NopCloser(bytes.NewReader(body)), len(body))
return c.Next()
}
}
+57
View File
@@ -0,0 +1,57 @@
package middleware
import (
"strconv"
"time"
"github.com/gofiber/fiber/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
httpRequestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "osmedeus_http_requests_total",
Help: "Total HTTP requests",
}, []string{"method", "path", "status"})
httpRequestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "osmedeus_http_request_duration_seconds",
Help: "HTTP request duration in seconds",
Buckets: prometheus.DefBuckets,
}, []string{"method", "path"})
httpRequestsInFlight = promauto.NewGauge(prometheus.GaugeOpts{
Name: "osmedeus_http_requests_in_flight",
Help: "Current number of HTTP requests being processed",
})
)
// PrometheusMetrics returns a Fiber middleware that records HTTP metrics
func PrometheusMetrics() fiber.Handler {
return func(c *fiber.Ctx) error {
httpRequestsInFlight.Inc()
start := time.Now()
err := c.Next()
duration := time.Since(start).Seconds()
httpRequestsInFlight.Dec()
// Normalize path to avoid high cardinality (replace IDs with :id)
path := normalizePath(c.Route().Path)
httpRequestDuration.WithLabelValues(c.Method(), path).Observe(duration)
httpRequestsTotal.WithLabelValues(c.Method(), path, strconv.Itoa(c.Response().StatusCode())).Inc()
return err
}
}
// normalizePath normalizes the path to avoid high cardinality metrics
func normalizePath(path string) string {
if path == "" {
return "/"
}
return path
}