diff --git a/cli/cli.go b/cli/cli.go index 011b2bcf..e7a49851 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -57,7 +57,7 @@ func Cli(version string) (err error) { if currentFlags.Serve { registry.ConfigureVendors() - err = restapi.Serve(registry, currentFlags.ServeAddress, currentFlags.ServeApiKey) + err = restapi.Serve(registry, currentFlags.ServeAddress, currentFlags.ServeAPIKey) return } diff --git a/cli/flags.go b/cli/flags.go index 0210c96c..62d583eb 100644 --- a/cli/flags.go +++ b/cli/flags.go @@ -64,7 +64,7 @@ type Flags struct { Serve bool `long:"serve" description:"Serve the Fabric Rest API"` ServeOllama bool `long:"serveOllama" description:"Serve the Fabric Rest API with ollama endpoints"` ServeAddress string `long:"address" description:"The address to bind the REST API" default:":8080"` - ServeApiKey string `long:"apikey" description:"API key used to secure server routes" default:""` + ServeAPIKey string `long:"api-key" description:"API key used to secure server routes" default:""` Config string `long:"config" description:"Path to YAML config file"` Version bool `long:"version" description:"Print current version"` ListExtensions bool `long:"listextensions" description:"List all registered extensions"` diff --git a/restapi/auth.go b/restapi/auth.go index 32538b9a..e6f239c1 100644 --- a/restapi/auth.go +++ b/restapi/auth.go @@ -1,18 +1,24 @@ package restapi import ( - "fmt" "net/http" "github.com/gin-gonic/gin" ) -func ApiKeyMiddleware(apiKey string) gin.HandlerFunc { +const APIKeyHeader = "X-API-Key" + +func APIKeyMiddleware(apiKey string) gin.HandlerFunc { return func(c *gin.Context) { - headerApiKey := c.GetHeader("X-API-Key") + headerApiKey := c.GetHeader(APIKeyHeader) + + if headerApiKey == "" { + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing API Key"}) + return + } if headerApiKey != apiKey { - c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": fmt.Sprintf("Wrong or missing API Key")}) + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Wrong API Key"}) return } diff --git a/restapi/serve.go b/restapi/serve.go index 90bf6c0e..f1a81a0d 100644 --- a/restapi/serve.go +++ b/restapi/serve.go @@ -1,6 +1,8 @@ package restapi import ( + "log/slog" + "github.com/danielmiessler/fabric/core" "github.com/gin-gonic/gin" ) @@ -13,7 +15,9 @@ func Serve(registry *core.PluginRegistry, address string, apiKey string) (err er r.Use(gin.Recovery()) if apiKey != "" { - r.Use(ApiKeyMiddleware(apiKey)) + r.Use(APIKeyMiddleware(apiKey)) + } else { + slog.Warn("Starting REST API server without API key authentication. This may pose security risks.") } // Register routes