Skip to content

Modern Docker Management, Designed for Everyone

refactor: migrate off gin to use echo for backend router (#2582)

Kyle Mendellb6c6e372d3e7
diff --git a/backend/internal/huma/huma.go b/backend/api/api.go
similarity index 93%
rename from backend/internal/huma/huma.go
rename to backend/api/api.go
index f414bf3df..83fd6b455 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/api/api.go
@@ -1,16 +1,17 @@
-package huma
+package api
import (
+ "net/http"
"reflect"
"strings"
"github.com/danielgtaylor/huma/v2"
- "github.com/danielgtaylor/huma/v2/adapters/humagin"
+ "github.com/danielgtaylor/huma/v2/adapters/humaecho"
+ "github.com/getarcaneapp/arcane/backend/api/handlers"
+ "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/getarcaneapp/arcane/backend/internal/huma/handlers"
- "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
)
const (
@@ -176,8 +177,8 @@ type Services struct {
Config *config.Config
}
-// SetupAPI creates and configures the Huma API alongside the existing Gin router.
-func SetupAPI(router *gin.Engine, apiGroup *gin.RouterGroup, cfg *config.Config, svc *Services) huma.API {
+// SetupAPI creates and configures the Huma API attached to the Echo router.
+func SetupAPI(e *echo.Echo, apiGroup *echo.Group, cfg *config.Config, svc *Services) huma.API {
humaConfig := huma.DefaultConfig("Arcane API", config.Version)
humaConfig.Info.Description = "Modern Docker Management, Designed for Everyone"
@@ -219,8 +220,8 @@ func SetupAPI(router *gin.Engine, apiGroup *gin.RouterGroup, cfg *config.Config,
// from different packages (e.g., image.Summary vs env.Summary)
humaConfig.Components.Schemas = huma.NewMapRegistry("#/components/schemas/", customSchemaNamer)
- // Create Huma API wrapping the Gin router group
- api := humagin.NewWithGroup(router, apiGroup, humaConfig)
+ // Create Huma API wrapping the Echo router group
+ api := humaecho.NewWithGroup(e, apiGroup, humaConfig)
// Add authentication middleware
api.UseMiddleware(middleware.NewAuthBridge(api, svc.Auth, svc.ApiKey, svc.Environment, cfg))
@@ -258,19 +259,19 @@ const scalarDocsHTML = `<!doctype html>
</html>`
// registerScalarDocs adds the Scalar API documentation endpoint.
-func registerScalarDocs(apiGroup *gin.RouterGroup) {
- apiGroup.GET("/docs", func(c *gin.Context) {
- c.Header("Content-Type", "text/html")
- c.String(200, scalarDocsHTML)
+func registerScalarDocs(apiGroup *echo.Group) {
+ apiGroup.GET("/docs", func(c echo.Context) error {
+ return c.HTML(http.StatusOK, scalarDocsHTML)
})
}
// SetupAPIForSpec creates a Huma API instance for OpenAPI spec generation only.
// No services are required - this is purely for schema generation.
func SetupAPIForSpec() huma.API {
- gin.SetMode(gin.ReleaseMode)
- router := gin.New()
- apiGroup := router.Group("/api")
+ e := echo.New()
+ e.HideBanner = true
+ e.HidePort = true
+ apiGroup := e.Group("/api")
humaConfig := huma.DefaultConfig("Arcane API", config.Version)
humaConfig.Info.Description = "Modern Docker Management, Designed for Everyone"
@@ -299,7 +300,7 @@ func SetupAPIForSpec() huma.API {
// Use custom schema namer to avoid conflicts between types with same name
humaConfig.Components.Schemas = huma.NewMapRegistry("#/components/schemas/", customSchemaNamer)
- api := humagin.NewWithGroup(router, apiGroup, humaConfig)
+ api := humaecho.NewWithGroup(e, apiGroup, humaConfig)
// Register handlers with nil services (just for schema)
registerHandlers(api, nil)
diff --git a/backend/internal/huma/huma_test.go b/backend/api/api_test.go
similarity index 99%
rename from backend/internal/huma/huma_test.go
rename to backend/api/api_test.go
index 2f8edee48..9caba8008 100644
--- a/backend/internal/huma/huma_test.go
+++ b/backend/api/api_test.go
@@ -1,4 +1,4 @@
-package huma
+package api
import (
"reflect"
diff --git a/backend/api/buildables.go b/backend/api/buildables.go
new file mode 100644
index 000000000..04d71fb37
--- /dev/null
+++ b/backend/api/buildables.go
@@ -0,0 +1,100 @@
+//go:build buildables
+
+package api
+
+import (
+ "errors"
+ "net/http"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/buildables"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
+ "github.com/getarcaneapp/arcane/types/auth"
+ "github.com/getarcaneapp/arcane/types/base"
+ "github.com/getarcaneapp/arcane/types/user"
+ "github.com/labstack/echo/v4"
+)
+
+// SetupBuildablesRoutes registers buildable feature routes based on EnabledFeatures.
+func SetupBuildablesRoutes(apiGroup *echo.Group, authService *services.AuthService) {
+ if buildables.HasBuildFeature("autologin") {
+ registerAutoLoginRoutes(apiGroup, authService)
+ }
+}
+
+func registerAutoLoginRoutes(apiGroup *echo.Group, authService *services.AuthService) {
+ authGroup := apiGroup.Group("/auth")
+
+ authGroup.GET("/auto-login-config", func(c echo.Context) error {
+ if authService == nil {
+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "service not available"})
+ }
+
+ config, err := authService.GetAutoLoginConfig(c.Request().Context())
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "failed to get auto-login config"})
+ }
+
+ return c.JSON(http.StatusOK, base.ApiResponse[auth.AutoLoginConfig]{
+ Success: true,
+ Data: *config,
+ })
+ })
+
+ authGroup.POST("/auto-login", func(c echo.Context) error {
+ if authService == nil {
+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "service not available"})
+ }
+
+ autoLoginConfig, err := authService.GetAutoLoginConfig(c.Request().Context())
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "failed to get auto-login config"})
+ }
+
+ if !autoLoginConfig.Enabled {
+ return c.JSON(http.StatusBadRequest, base.ErrorResponse{Error: "auto-login is not enabled"})
+ }
+
+ password := authService.GetAutoLoginPassword()
+ if password == "" {
+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "auto-login password not configured"})
+ }
+
+ userModel, tokenPair, err := authService.Login(c.Request().Context(), autoLoginConfig.Username, password)
+ if err != nil {
+ switch {
+ case errors.Is(err, services.ErrInvalidCredentials):
+ return c.JSON(http.StatusUnauthorized, base.ErrorResponse{Error: (&common.InvalidCredentialsError{}).Error()})
+ case errors.Is(err, services.ErrLocalAuthDisabled):
+ return c.JSON(http.StatusBadRequest, base.ErrorResponse{Error: (&common.LocalAuthDisabledError{}).Error()})
+ default:
+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: (&common.AuthFailedError{Err: err}).Error()})
+ }
+ }
+
+ var userResp user.User
+ if mapErr := mapper.MapStruct(userModel, &userResp); mapErr != nil {
+ return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: (&common.UserMappingError{Err: mapErr}).Error()})
+ }
+
+ maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
+ if maxAge < 0 {
+ maxAge = 0
+ }
+ maxAge += 60
+
+ c.Response().Header().Set("Set-Cookie", cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken))
+ return c.JSON(http.StatusOK, base.ApiResponse[auth.LoginResponse]{
+ Success: true,
+ Data: auth.LoginResponse{
+ Token: tokenPair.AccessToken,
+ RefreshToken: tokenPair.RefreshToken,
+ ExpiresAt: tokenPair.ExpiresAt,
+ User: userResp,
+ },
+ })
+ })
+}
diff --git a/backend/api/diagnostics.go b/backend/api/diagnostics.go
new file mode 100644
index 000000000..383b42d4d
--- /dev/null
+++ b/backend/api/diagnostics.go
@@ -0,0 +1,43 @@
+package api
+
+import (
+ "net/http"
+ "runtime"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/api/ws"
+ "github.com/getarcaneapp/arcane/backend/internal/middleware"
+ wshub "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
+ "github.com/labstack/echo/v4"
+)
+
+type DiagnosticsHandler struct {
+ wsMetrics *ws.WebSocketMetrics
+}
+
+func RegisterDiagnosticsRoutes(group *echo.Group, authMiddleware *middleware.AuthMiddleware, wsMetrics *ws.WebSocketMetrics) {
+ h := &DiagnosticsHandler{wsMetrics: wsMetrics}
+
+ diagnostics := group.Group("/diagnostics", authMiddleware.Add())
+ diagnostics.GET("/ws", h.WebSocketDiagnostics)
+}
+
+func (h *DiagnosticsHandler) WebSocketDiagnostics(c echo.Context) error {
+ val := c.Get("userIsAdmin")
+ if admin, ok := val.(bool); !ok || !admin {
+ return c.JSON(http.StatusForbidden, map[string]any{"error": "Admin access required"})
+ }
+
+ metrics := h.wsMetrics.Snapshot()
+ connections := h.wsMetrics.Connections()
+
+ return c.JSON(http.StatusOK, map[string]any{
+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
+ "goroutines": runtime.NumGoroutine(),
+ "wsWorkerGoroutine": wshub.CountWorkerGoroutines(),
+ "gomaxprocs": runtime.GOMAXPROCS(0),
+ "goVersion": runtime.Version(),
+ "activeConnections": metrics,
+ "connections": connections,
+ })
+}
diff --git a/backend/internal/huma/handlers/apikeys.go b/backend/api/handlers/apikeys.go
similarity index 96%
rename from backend/internal/huma/handlers/apikeys.go
rename to backend/api/handlers/apikeys.go
index a4c8d2372..22480322e 100644
--- a/backend/internal/huma/handlers/apikeys.go
+++ b/backend/api/handlers/apikeys.go
@@ -6,8 +6,8 @@ import (
"net/http"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/apikey"
@@ -152,7 +152,7 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput
}
// Check admin access
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -202,7 +202,7 @@ func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInp
}
// Check admin access
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -226,7 +226,7 @@ func (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*
}
// Check admin access
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -250,7 +250,7 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInp
}
// Check admin access
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -280,7 +280,7 @@ func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInp
}
// Check admin access
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/appimages.go b/backend/api/handlers/appimages.go
similarity index 100%
rename from backend/internal/huma/handlers/appimages.go
rename to backend/api/handlers/appimages.go
diff --git a/backend/internal/huma/handlers/appimages_test.go b/backend/api/handlers/appimages_test.go
similarity index 100%
rename from backend/internal/huma/handlers/appimages_test.go
rename to backend/api/handlers/appimages_test.go
diff --git a/backend/internal/huma/handlers/auth.go b/backend/api/handlers/auth.go
similarity index 99%
rename from backend/internal/huma/handlers/auth.go
rename to backend/api/handlers/auth.go
index 09e674aab..4e80eaca5 100644
--- a/backend/internal/huma/handlers/auth.go
+++ b/backend/api/handlers/auth.go
@@ -7,8 +7,8 @@ import (
"time"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
diff --git a/backend/internal/huma/handlers/build_workspaces.go b/backend/api/handlers/build_workspaces.go
similarity index 100%
rename from backend/internal/huma/handlers/build_workspaces.go
rename to backend/api/handlers/build_workspaces.go
diff --git a/backend/internal/huma/handlers/container_registries.go b/backend/api/handlers/container_registries.go
similarity index 97%
rename from backend/internal/huma/handlers/container_registries.go
rename to backend/api/handlers/container_registries.go
index 66d0a4b32..c9b94db23 100644
--- a/backend/internal/huma/handlers/container_registries.go
+++ b/backend/api/handlers/container_registries.go
@@ -223,7 +223,7 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Li
return nil, huma.Error500InternalServerError("service not available")
}
- params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
registries, paginationResp, err := h.registryService.GetRegistriesPaginated(ctx, params)
if err != nil {
@@ -270,7 +270,7 @@ func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *Cr
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -326,7 +326,7 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Up
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -357,7 +357,7 @@ func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *De
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -384,7 +384,7 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -439,7 +439,7 @@ func (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *Sy
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/containers.go b/backend/api/handlers/containers.go
similarity index 99%
rename from backend/internal/huma/handlers/containers.go
rename to backend/api/handlers/containers.go
index bf4e789b4..a35831301 100644
--- a/backend/internal/huma/handlers/containers.go
+++ b/backend/api/handlers/containers.go
@@ -8,8 +8,8 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
diff --git a/backend/internal/huma/handlers/customize.go b/backend/api/handlers/customize.go
similarity index 97%
rename from backend/internal/huma/handlers/customize.go
rename to backend/api/handlers/customize.go
index f60d86ec2..67ae280e7 100644
--- a/backend/internal/huma/handlers/customize.go
+++ b/backend/api/handlers/customize.go
@@ -6,8 +6,8 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/types/category"
"github.com/getarcaneapp/arcane/types/search"
diff --git a/backend/internal/huma/handlers/dashboard.go b/backend/api/handlers/dashboard.go
similarity index 100%
rename from backend/internal/huma/handlers/dashboard.go
rename to backend/api/handlers/dashboard.go
diff --git a/backend/internal/huma/handlers/dashboard_test.go b/backend/api/handlers/dashboard_test.go
similarity index 100%
rename from backend/internal/huma/handlers/dashboard_test.go
rename to backend/api/handlers/dashboard_test.go
diff --git a/backend/internal/huma/handlers/edge_mtls_ca.go b/backend/api/handlers/edge_mtls_ca.go
similarity index 100%
rename from backend/internal/huma/handlers/edge_mtls_ca.go
rename to backend/api/handlers/edge_mtls_ca.go
diff --git a/backend/internal/huma/handlers/edge_mtls_ca_test.go b/backend/api/handlers/edge_mtls_ca_test.go
similarity index 100%
rename from backend/internal/huma/handlers/edge_mtls_ca_test.go
rename to backend/api/handlers/edge_mtls_ca_test.go
diff --git a/backend/internal/huma/handlers/environments.go b/backend/api/handlers/environments.go
similarity index 98%
rename from backend/internal/huma/handlers/environments.go
rename to backend/api/handlers/environments.go
index 091d6852a..9812b6f1b 100644
--- a/backend/internal/huma/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -15,9 +15,9 @@ import (
"time"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
@@ -458,7 +458,7 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -613,7 +613,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -710,7 +710,7 @@ func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *Delet
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -744,7 +744,7 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConn
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -799,7 +799,7 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpu
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -832,7 +832,7 @@ func (h *EnvironmentHandler) SyncEnvironment(ctx context.Context, input *SyncEnv
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1007,7 +1007,7 @@ func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *G
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1155,7 +1155,7 @@ func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *G
// DownloadEdgeMTLSCA downloads the Arcane-managed edge mTLS CA certificate.
func (h *EnvironmentHandler) DownloadEdgeMTLSCA(ctx context.Context, _ *DownloadEdgeMTLSCAInput) (*huma.StreamResponse, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1197,7 +1197,7 @@ func (h *EnvironmentHandler) DownloadEdgeMTLSCA(ctx context.Context, _ *Download
}
func (h *EnvironmentHandler) DownloadEnvironmentMTLSBundle(ctx context.Context, input *DownloadEnvironmentMTLSBundleInput) (*huma.StreamResponse, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1259,7 +1259,7 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSBundle(ctx context.Context,
}
func (h *EnvironmentHandler) DownloadEnvironmentMTLSFile(ctx context.Context, input *DownloadEnvironmentMTLSFileInput) (*huma.StreamResponse, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/environments_test.go b/backend/api/handlers/environments_test.go
similarity index 100%
rename from backend/internal/huma/handlers/environments_test.go
rename to backend/api/handlers/environments_test.go
diff --git a/backend/internal/huma/handlers/events.go b/backend/api/handlers/events.go
similarity index 95%
rename from backend/internal/huma/handlers/events.go
rename to backend/api/handlers/events.go
index 698b65d53..320a59b59 100644
--- a/backend/internal/huma/handlers/events.go
+++ b/backend/api/handlers/events.go
@@ -147,11 +147,11 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
- params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Severity != "" {
params.Filters["severity"] = input.Severity
@@ -186,7 +186,7 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEve
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -194,7 +194,7 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEve
return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())
}
- params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Severity != "" {
params.Filters["severity"] = input.Severity
@@ -239,7 +239,7 @@ func (h *EventHandler) CreateEvent(ctx context.Context, input *CreateEventInput)
}
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -262,7 +262,7 @@ func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput)
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/fonts.go b/backend/api/handlers/fonts.go
similarity index 100%
rename from backend/internal/huma/handlers/fonts.go
rename to backend/api/handlers/fonts.go
diff --git a/backend/internal/huma/handlers/git_repositories.go b/backend/api/handlers/git_repositories.go
similarity index 97%
rename from backend/internal/huma/handlers/git_repositories.go
rename to backend/api/handlers/git_repositories.go
index 7728752ff..d14d6e5fd 100644
--- a/backend/internal/huma/handlers/git_repositories.go
+++ b/backend/api/handlers/git_repositories.go
@@ -4,8 +4,8 @@ import (
"context"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
@@ -245,7 +245,7 @@ func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *List
return nil, huma.Error500InternalServerError("service not available")
}
- params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
repositories, paginationResp, err := h.repoService.GetRepositoriesPaginated(ctx, params)
if err != nil {
@@ -273,7 +273,7 @@ func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *Crea
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -332,7 +332,7 @@ func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *Upda
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -366,7 +366,7 @@ func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *Dele
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -396,7 +396,7 @@ func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGi
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -469,7 +469,7 @@ func (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *Sync
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/git_repositories_test.go b/backend/api/handlers/git_repositories_test.go
similarity index 100%
rename from backend/internal/huma/handlers/git_repositories_test.go
rename to backend/api/handlers/git_repositories_test.go
diff --git a/backend/internal/huma/handlers/gitops_syncs.go b/backend/api/handlers/gitops_syncs.go
similarity index 98%
rename from backend/internal/huma/handlers/gitops_syncs.go
rename to backend/api/handlers/gitops_syncs.go
index fe7ff9f27..153b2a22e 100644
--- a/backend/internal/huma/handlers/gitops_syncs.go
+++ b/backend/api/handlers/gitops_syncs.go
@@ -4,8 +4,8 @@ import (
"context"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
@@ -253,7 +253,7 @@ func (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSync
return nil, huma.Error500InternalServerError("service not available")
}
- params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
syncs, paginationResp, counts, err := h.syncService.GetSyncsPaginated(ctx, input.EnvironmentID, params)
if err != nil {
diff --git a/backend/internal/huma/handlers/health.go b/backend/api/handlers/health.go
similarity index 100%
rename from backend/internal/huma/handlers/health.go
rename to backend/api/handlers/health.go
diff --git a/backend/internal/huma/handlers/helpers.go b/backend/api/handlers/helpers.go
similarity index 86%
rename from backend/internal/huma/handlers/helpers.go
rename to backend/api/handlers/helpers.go
index 6ddc41525..e006f68a9 100644
--- a/backend/internal/huma/handlers/helpers.go
+++ b/backend/api/handlers/helpers.go
@@ -6,24 +6,24 @@ import (
"errors"
"github.com/danielgtaylor/huma/v2"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/pkg/remenv"
)
-// checkAdmin checks if the current user is an admin and returns a 403 error if not.
-func checkAdmin(ctx context.Context) error {
+// checkAdminInternal checks if the current user is an admin and returns a 403 error if not.
+func checkAdminInternal(ctx context.Context) error {
if !humamw.IsAdminFromContext(ctx) {
return huma.Error403Forbidden("admin access required")
}
return nil
}
-// buildPaginationParams converts query parameters to pagination.QueryParams.
+// buildPaginationParamsInternal converts query parameters to pagination.QueryParams.
// It supports both the legacy nested style (page/limit) and the standard style (start/limit).
// A limit of -1 means "show all items" (no pagination).
-func buildPaginationParams(page, start, limit int, sortCol, sortDir, search string) pagination.QueryParams {
+func buildPaginationParamsInternal(page, start, limit int, sortCol, sortDir, search string) pagination.QueryParams {
// limit = -1 means "show all", preserve it; zero or other negative values default to 20
if limit < -1 {
limit = 20
diff --git a/backend/internal/huma/handlers/image_updates.go b/backend/api/handlers/image_updates.go
similarity index 100%
rename from backend/internal/huma/handlers/image_updates.go
rename to backend/api/handlers/image_updates.go
diff --git a/backend/internal/huma/handlers/images.go b/backend/api/handlers/images.go
similarity index 99%
rename from backend/internal/huma/handlers/images.go
rename to backend/api/handlers/images.go
index e7b1d094a..5f5504208 100644
--- a/backend/internal/huma/handlers/images.go
+++ b/backend/api/handlers/images.go
@@ -9,8 +9,8 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/base"
@@ -484,7 +484,7 @@ func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuil
return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())
}
- params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Status != "" {
params.Filters["status"] = input.Status
}
diff --git a/backend/internal/huma/handlers/job_schedules.go b/backend/api/handlers/job_schedules.go
similarity index 100%
rename from backend/internal/huma/handlers/job_schedules.go
rename to backend/api/handlers/job_schedules.go
diff --git a/backend/internal/huma/handlers/networks.go b/backend/api/handlers/networks.go
similarity index 99%
rename from backend/internal/huma/handlers/networks.go
rename to backend/api/handlers/networks.go
index 609b279fd..8dba638c1 100644
--- a/backend/internal/huma/handlers/networks.go
+++ b/backend/api/handlers/networks.go
@@ -9,8 +9,8 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
diff --git a/backend/internal/huma/handlers/notifications.go b/backend/api/handlers/notifications.go
similarity index 97%
rename from backend/internal/huma/handlers/notifications.go
rename to backend/api/handlers/notifications.go
index 3d7a8e0d2..17862c225 100644
--- a/backend/internal/huma/handlers/notifications.go
+++ b/backend/api/handlers/notifications.go
@@ -223,7 +223,7 @@ func (h *NotificationHandler) rejectIfAgentModeInternal() error {
}
func (h *NotificationHandler) GetAllNotificationSettings(ctx context.Context, input *GetAllNotificationSettingsInput) (*GetAllNotificationSettingsOutput, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
if err := h.rejectIfAgentModeInternal(); err != nil {
@@ -248,7 +248,7 @@ func (h *NotificationHandler) GetAllNotificationSettings(ctx context.Context, in
}
func (h *NotificationHandler) GetNotificationSettings(ctx context.Context, input *GetNotificationSettingsInput) (*GetNotificationSettingsOutput, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
if err := h.rejectIfAgentModeInternal(); err != nil {
@@ -272,7 +272,7 @@ func (h *NotificationHandler) GetNotificationSettings(ctx context.Context, input
}
func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Context, input *CreateOrUpdateNotificationSettingsInput) (*CreateOrUpdateNotificationSettingsOutput, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
if err := h.rejectIfAgentModeInternal(); err != nil {
@@ -304,7 +304,7 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Con
}
func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, input *DeleteNotificationSettingsInput) (*DeleteNotificationSettingsOutput, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
if err := h.rejectIfAgentModeInternal(); err != nil {
@@ -325,7 +325,7 @@ func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, in
}
func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestNotificationInput) (*TestNotificationOutput, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
if err := h.rejectIfAgentModeInternal(); err != nil {
@@ -350,7 +350,7 @@ func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestN
}
func (h *NotificationHandler) GetAppriseSettings(ctx context.Context, input *GetAppriseSettingsInput) (*GetAppriseSettingsOutput, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
if err := h.rejectIfAgentModeInternal(); err != nil {
@@ -376,7 +376,7 @@ func (h *NotificationHandler) GetAppriseSettings(ctx context.Context, input *Get
}
func (h *NotificationHandler) CreateOrUpdateAppriseSettings(ctx context.Context, input *CreateOrUpdateAppriseSettingsInput) (*CreateOrUpdateAppriseSettingsOutput, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
if err := h.rejectIfAgentModeInternal(); err != nil {
@@ -409,7 +409,7 @@ func (h *NotificationHandler) CreateOrUpdateAppriseSettings(ctx context.Context,
}
func (h *NotificationHandler) TestAppriseNotification(ctx context.Context, input *TestAppriseNotificationInput) (*TestAppriseNotificationOutput, error) {
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
if err := h.rejectIfAgentModeInternal(); err != nil {
diff --git a/backend/internal/huma/handlers/notifications_test.go b/backend/api/handlers/notifications_test.go
similarity index 100%
rename from backend/internal/huma/handlers/notifications_test.go
rename to backend/api/handlers/notifications_test.go
diff --git a/backend/internal/huma/handlers/oidc.go b/backend/api/handlers/oidc.go
similarity index 100%
rename from backend/internal/huma/handlers/oidc.go
rename to backend/api/handlers/oidc.go
diff --git a/backend/internal/huma/handlers/ports.go b/backend/api/handlers/ports.go
similarity index 100%
rename from backend/internal/huma/handlers/ports.go
rename to backend/api/handlers/ports.go
diff --git a/backend/internal/huma/handlers/projects.go b/backend/api/handlers/projects.go
similarity index 99%
rename from backend/internal/huma/handlers/projects.go
rename to backend/api/handlers/projects.go
index 610344a2d..c8f81727d 100644
--- a/backend/internal/huma/handlers/projects.go
+++ b/backend/api/handlers/projects.go
@@ -9,8 +9,8 @@ import (
"time"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
projects "github.com/getarcaneapp/arcane/backend/pkg/projects"
diff --git a/backend/internal/huma/handlers/remenv_handlers_test.go b/backend/api/handlers/remenv_handlers_test.go
similarity index 100%
rename from backend/internal/huma/handlers/remenv_handlers_test.go
rename to backend/api/handlers/remenv_handlers_test.go
diff --git a/backend/internal/huma/handlers/settings.go b/backend/api/handlers/settings.go
similarity index 98%
rename from backend/internal/huma/handlers/settings.go
rename to backend/api/handlers/settings.go
index d5c8d2595..ccc9a0ca2 100644
--- a/backend/internal/huma/handlers/settings.go
+++ b/backend/api/handlers/settings.go
@@ -8,9 +8,9 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/projects"
@@ -292,7 +292,7 @@ func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSetti
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -393,7 +393,7 @@ func (h *SettingsHandler) Search(ctx context.Context, input *SearchSettingsInput
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -411,7 +411,7 @@ func (h *SettingsHandler) GetCategories(ctx context.Context, input *struct{}) (*
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/settings_test.go b/backend/api/handlers/settings_test.go
similarity index 100%
rename from backend/internal/huma/handlers/settings_test.go
rename to backend/api/handlers/settings_test.go
diff --git a/backend/internal/huma/handlers/settings_validation_test.go b/backend/api/handlers/settings_validation_test.go
similarity index 100%
rename from backend/internal/huma/handlers/settings_validation_test.go
rename to backend/api/handlers/settings_validation_test.go
diff --git a/backend/internal/huma/handlers/swarm.go b/backend/api/handlers/swarm.go
similarity index 98%
rename from backend/internal/huma/handlers/swarm.go
rename to backend/api/handlers/swarm.go
index 60c996db7..17404ab79 100644
--- a/backend/internal/huma/handlers/swarm.go
+++ b/backend/api/handlers/swarm.go
@@ -10,9 +10,9 @@ import (
"github.com/containerd/errdefs"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
@@ -645,7 +645,7 @@ func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServ
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -674,7 +674,7 @@ func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServ
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -704,7 +704,7 @@ func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServ
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -762,7 +762,7 @@ func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarm
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -791,7 +791,7 @@ func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServic
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -878,7 +878,7 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwa
if h.swarmService == nil || h.environmentService == nil || h.cfg == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -982,7 +982,7 @@ func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInp
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1010,7 +1010,7 @@ func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInp
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1038,7 +1038,7 @@ func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeI
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1066,7 +1066,7 @@ func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInp
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1176,7 +1176,7 @@ func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackI
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1232,7 +1232,7 @@ func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackS
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1256,7 +1256,7 @@ func (h *SwarmHandler) UpdateStackSource(ctx context.Context, input *UpdateSwarm
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1286,7 +1286,7 @@ func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackI
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1453,7 +1453,7 @@ func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*I
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1482,7 +1482,7 @@ func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*J
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1510,7 +1510,7 @@ func (h *SwarmHandler) LeaveSwarm(ctx context.Context, input *LeaveSwarmInput) (
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1538,7 +1538,7 @@ func (h *SwarmHandler) UnlockSwarm(ctx context.Context, input *UnlockSwarmInput)
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1565,7 +1565,7 @@ func (h *SwarmHandler) GetUnlockKey(ctx context.Context, input *GetSwarmUnlockKe
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1591,7 +1591,7 @@ func (h *SwarmHandler) GetJoinTokens(ctx context.Context, input *GetSwarmJoinTok
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1618,7 +1618,7 @@ func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJ
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1646,7 +1646,7 @@ func (h *SwarmHandler) UpdateSwarmSpec(ctx context.Context, input *UpdateSwarmSp
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1727,7 +1727,7 @@ func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfi
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1756,7 +1756,7 @@ func (h *SwarmHandler) UpdateConfig(ctx context.Context, input *UpdateSwarmConfi
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1785,7 +1785,7 @@ func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfi
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1869,7 +1869,7 @@ func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecre
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1898,7 +1898,7 @@ func (h *SwarmHandler) UpdateSecret(ctx context.Context, input *UpdateSwarmSecre
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -1927,7 +1927,7 @@ func (h *SwarmHandler) DeleteSecret(ctx context.Context, input *DeleteSwarmSecre
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/system.go b/backend/api/handlers/system.go
similarity index 97%
rename from backend/internal/huma/handlers/system.go
rename to backend/api/handlers/system.go
index 90a288f32..4ae34f8f9 100644
--- a/backend/internal/huma/handlers/system.go
+++ b/backend/api/handlers/system.go
@@ -8,9 +8,9 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
"github.com/getarcaneapp/arcane/types/base"
@@ -359,7 +359,7 @@ func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*Pr
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -397,7 +397,7 @@ func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllC
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -420,7 +420,7 @@ func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *St
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -443,7 +443,7 @@ func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllCon
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -492,7 +492,7 @@ func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckU
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -523,7 +523,7 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgrad
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/templates.go b/backend/api/handlers/templates.go
similarity index 99%
rename from backend/internal/huma/handlers/templates.go
rename to backend/api/handlers/templates.go
index 8d9239265..60417e68c 100644
--- a/backend/internal/huma/handlers/templates.go
+++ b/backend/api/handlers/templates.go
@@ -396,7 +396,7 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplate
return nil, huma.Error500InternalServerError("service not available")
}
- params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
}
diff --git a/backend/internal/huma/handlers/templates_test.go b/backend/api/handlers/templates_test.go
similarity index 96%
rename from backend/internal/huma/handlers/templates_test.go
rename to backend/api/handlers/templates_test.go
index 59b615b51..afa1552ba 100644
--- a/backend/internal/huma/handlers/templates_test.go
+++ b/backend/api/handlers/templates_test.go
@@ -11,15 +11,15 @@ import (
"time"
"github.com/danielgtaylor/huma/v2"
- "github.com/danielgtaylor/huma/v2/adapters/humagin"
+ "github.com/danielgtaylor/huma/v2/adapters/humaecho"
+ humamiddleware "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/database"
- humamiddleware "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
glsqlite "github.com/glebarez/sqlite"
"github.com/golang-jwt/jwt/v5"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)
@@ -111,7 +111,7 @@ func TestHealthEndpointRemainsPublic(t *testing.T) {
require.Contains(t, rec.Body.String(), "UP")
}
-func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *gin.Engine {
+func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *echo.Echo {
t.Helper()
originalDir, err := os.Getwd()
@@ -137,7 +137,7 @@ func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *gin.Engi
authService := services.NewAuthService(userService, nil, nil, "test-secret", &config.Config{})
templateService := services.NewTemplateService(context.Background(), nil, httpClient, nil)
- router := gin.New()
+ router := echo.New()
apiGroup := router.Group("/api")
humaConfig := huma.DefaultConfig("test", "1.0.0")
@@ -157,7 +157,7 @@ func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *gin.Engi
{"ApiKeyAuth": {}},
}
- api := humagin.NewWithGroup(router, apiGroup, humaConfig)
+ api := humaecho.NewWithGroup(router, apiGroup, humaConfig)
api.UseMiddleware(humamiddleware.NewAuthBridge(api, authService, nil, nil, &config.Config{}))
RegisterHealth(api)
RegisterTemplates(api, templateService, nil)
diff --git a/backend/internal/huma/handlers/updater.go b/backend/api/handlers/updater.go
similarity index 100%
rename from backend/internal/huma/handlers/updater.go
rename to backend/api/handlers/updater.go
diff --git a/backend/internal/huma/handlers/users.go b/backend/api/handlers/users.go
similarity index 96%
rename from backend/internal/huma/handlers/users.go
rename to backend/api/handlers/users.go
index c4b67eeaf..14852f002 100644
--- a/backend/internal/huma/handlers/users.go
+++ b/backend/api/handlers/users.go
@@ -160,11 +160,11 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*Li
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
- params := buildPaginationParams(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(0, input.Start, input.Limit, input.Sort, input.Order, input.Search)
users, paginationResp, err := h.userService.ListUsersPaginated(ctx, params)
if err != nil {
@@ -192,7 +192,7 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -247,7 +247,7 @@ func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUse
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -275,7 +275,7 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
@@ -346,7 +346,7 @@ func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdmin(ctx); err != nil {
+ if err := checkAdminInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/internal/huma/handlers/users_test.go b/backend/api/handlers/users_test.go
similarity index 97%
rename from backend/internal/huma/handlers/users_test.go
rename to backend/api/handlers/users_test.go
index 290a16eb9..732864a9f 100644
--- a/backend/internal/huma/handlers/users_test.go
+++ b/backend/api/handlers/users_test.go
@@ -6,7 +6,7 @@ import (
"testing"
"github.com/danielgtaylor/huma/v2"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
usertypes "github.com/getarcaneapp/arcane/types/user"
diff --git a/backend/internal/huma/handlers/version.go b/backend/api/handlers/version.go
similarity index 100%
rename from backend/internal/huma/handlers/version.go
rename to backend/api/handlers/version.go
diff --git a/backend/internal/huma/handlers/volumes.go b/backend/api/handlers/volumes.go
similarity index 99%
rename from backend/internal/huma/handlers/volumes.go
rename to backend/api/handlers/volumes.go
index 07d8bade9..aede3a295 100644
--- a/backend/internal/huma/handlers/volumes.go
+++ b/backend/api/handlers/volumes.go
@@ -9,8 +9,8 @@ import (
"strconv"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
diff --git a/backend/internal/huma/handlers/volumes_upload_test.go b/backend/api/handlers/volumes_upload_test.go
similarity index 94%
rename from backend/internal/huma/handlers/volumes_upload_test.go
rename to backend/api/handlers/volumes_upload_test.go
index 620b08013..1960671ce 100644
--- a/backend/internal/huma/handlers/volumes_upload_test.go
+++ b/backend/api/handlers/volumes_upload_test.go
@@ -7,7 +7,7 @@ import (
"testing"
"github.com/danielgtaylor/huma/v2"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/stretchr/testify/assert"
diff --git a/backend/internal/huma/handlers/vulnerabilities.go b/backend/api/handlers/vulnerabilities.go
similarity index 98%
rename from backend/internal/huma/handlers/vulnerabilities.go
rename to backend/api/handlers/vulnerabilities.go
index 56683a7cf..7be33a6a8 100644
--- a/backend/internal/huma/handlers/vulnerabilities.go
+++ b/backend/api/handlers/vulnerabilities.go
@@ -5,8 +5,8 @@ import (
"net/http"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/vulnerability"
@@ -392,7 +392,7 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inp
return nil, huma.Error500InternalServerError("service not available")
}
- params := buildPaginationParams(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
}
@@ -453,7 +453,7 @@ func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input
return nil, huma.Error500InternalServerError("service not available")
}
- params := buildPaginationParams(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
}
@@ -629,7 +629,7 @@ func (h *VulnerabilityHandler) ListIgnoredVulnerabilities(ctx context.Context, i
return nil, huma.Error500InternalServerError("service not available")
}
- params := buildPaginationParams(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ params := buildPaginationParamsInternal(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
}
diff --git a/backend/internal/huma/handlers/webhooks.go b/backend/api/handlers/webhooks.go
similarity index 83%
rename from backend/internal/huma/handlers/webhooks.go
rename to backend/api/handlers/webhooks.go
index ddf922ef0..357e2cc96 100644
--- a/backend/internal/huma/handlers/webhooks.go
+++ b/backend/api/handlers/webhooks.go
@@ -6,12 +6,11 @@ import (
"net/http"
"github.com/danielgtaylor/huma/v2"
- humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/webhook"
- "github.com/gin-gonic/gin"
)
type WebhookHandler struct {
@@ -113,41 +112,6 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
}, h.DeleteWebhook)
}
-// RegisterWebhookTrigger registers the public (unauthenticated) trigger endpoint on the
-// raw Gin router, bypassing the Huma auth middleware. The token in the URL is the sole
-// authentication mechanism.
-//
-// Security note: tokens appear in server access logs and browser history. Ensure access
-// logs are appropriately protected, and consider rate-limiting this endpoint at the
-// reverse-proxy level.
-func RegisterWebhookTrigger(router *gin.RouterGroup, webhookService *services.WebhookService) {
- router.POST("/webhooks/trigger/:token", func(c *gin.Context) {
- if webhookService == nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "service not available"})
- return
- }
-
- token := c.Param("token")
- result, err := webhookService.TriggerByToken(c.Request.Context(), token)
- if err != nil {
- status := http.StatusInternalServerError
- if errors.Is(err, services.ErrWebhookNotFound) || errors.Is(err, services.ErrWebhookInvalid) {
- status = http.StatusNotFound
- } else if errors.Is(err, services.ErrWebhookDisabled) {
- status = http.StatusForbidden
- }
- msg := err.Error()
- if status == http.StatusInternalServerError {
- msg = "internal server error"
- }
- c.JSON(status, gin.H{"success": false, "error": msg})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
- })
-}
-
// ListWebhooks returns all webhooks for an environment (tokens are masked).
func (h *WebhookHandler) ListWebhooks(ctx context.Context, input *ListWebhooksInput) (*ListWebhooksOutput, error) {
if h.webhookService == nil {
diff --git a/backend/internal/huma/middleware/auth.go b/backend/api/middleware/auth.go
similarity index 81%
rename from backend/internal/huma/middleware/auth.go
rename to backend/api/middleware/auth.go
index cc3963ba0..6bd8cff4f 100644
--- a/backend/internal/huma/middleware/auth.go
+++ b/backend/api/middleware/auth.go
@@ -2,6 +2,7 @@ package middleware
import (
"context"
+ "errors"
"net/http"
"strings"
@@ -10,13 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"
-)
-
-const (
- headerAgentBootstrap = "X-Arcane-Agent-Bootstrap"
- headerAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
- headerApiKey = "X-API-Key" // #nosec G101: header name, not a credential
- agentPairingPrefix = "/api/environments/0/agent/pair"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
)
// ContextKey is a type for context keys used by Huma handlers.
@@ -106,22 +101,25 @@ func parseSecurityRequirementsInternal(api huma.API, ctx operationProvider) secu
return reqs
}
-// tryBearerAuthInternal attempts Bearer token authentication.
-func tryBearerAuthInternal(ctx huma.Context, authService *services.AuthService) (*models.User, bool) {
+// tryBearerAuthInternal attempts Bearer token authentication. Returns the
+// authenticated user on success, or the underlying error from VerifyToken so
+// the caller can distinguish a missing/invalid token from a token-version
+// mismatch (which requires clearing the stale cookie).
+func tryBearerAuthInternal(ctx huma.Context, authService *services.AuthService) (*models.User, error) {
token := extractBearerTokenInternal(ctx)
if token == "" {
- return nil, false
+ return nil, nil
}
user, err := authService.VerifyToken(ctx.Context(), token)
- if err != nil || user == nil {
- return nil, false
+ if err != nil {
+ return nil, err
}
- return user, true
+ return user, nil
}
// tryApiKeyAuthInternal checks if API key authentication should be allowed through.
func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *services.ApiKeyService) (*models.User, bool) {
- apiKey := ctx.Header(headerApiKey)
+ apiKey := ctx.Header(pkgutils.HeaderApiKey)
if apiKey == "" {
return nil, false
}
@@ -134,7 +132,7 @@ func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *services.ApiKeyServi
return user, true
}
-func tryEnvironmentAccessTokenAuth(ctx huma.Context, resolver environmentAccessTokenResolver, token string) (*models.User, bool) {
+func tryEnvironmentAccessTokenAuthInternal(ctx huma.Context, resolver environmentAccessTokenResolver, token string) (*models.User, bool) {
if resolver == nil || strings.TrimSpace(token) == "" {
return nil, false
}
@@ -144,7 +142,7 @@ func tryEnvironmentAccessTokenAuth(ctx huma.Context, resolver environmentAccessT
return nil, false
}
- return createEnvironmentSudoUser(env), true
+ return createEnvironmentSudoUserInternal(env), true
}
// tryAgentAuthInternal checks if the request is from an authenticated agent.
@@ -157,19 +155,19 @@ func tryAgentAuthInternal(ctx huma.Context, cfg *config.Config) (*models.User, b
path := ctx.URL().Path
// Check for agent bootstrap pairing
- if strings.HasPrefix(path, agentPairingPrefix) &&
+ if strings.HasPrefix(path, pkgutils.AgentPairingPrefix) &&
cfg.AgentToken != "" &&
- ctx.Header(headerAgentBootstrap) == cfg.AgentToken {
+ ctx.Header(pkgutils.HeaderAgentBootstrap) == cfg.AgentToken {
return createAgentSudoUserInternal(), true
}
// Check for agent token
- if tok := ctx.Header(headerAgentToken); tok != "" && cfg.AgentToken != "" && tok == cfg.AgentToken {
+ if tok := ctx.Header(pkgutils.HeaderAgentToken); tok != "" && cfg.AgentToken != "" && tok == cfg.AgentToken {
return createAgentSudoUserInternal(), true
}
// Check for API key as agent token
- if tok := ctx.Header(headerApiKey); tok != "" && cfg.AgentToken != "" && tok == cfg.AgentToken {
+ if tok := ctx.Header(pkgutils.HeaderApiKey); tok != "" && cfg.AgentToken != "" && tok == cfg.AgentToken {
return createAgentSudoUserInternal(), true
}
@@ -178,16 +176,15 @@ func tryAgentAuthInternal(ctx huma.Context, cfg *config.Config) (*models.User, b
// createAgentSudoUserInternal creates a sudo user for agent authentication.
func createAgentSudoUserInternal() *models.User {
- email := "[email protected]"
return &models.User{
BaseModel: models.BaseModel{ID: "agent"},
- Email: new(email),
+ Email: new("[email protected]"),
Username: "agent",
Roles: []string{"admin"},
}
}
-func createEnvironmentSudoUser(env *models.Environment) *models.User {
+func createEnvironmentSudoUserInternal(env *models.Environment) *models.User {
return &models.User{
BaseModel: models.BaseModel{ID: "environment:" + env.ID},
Username: env.Name,
@@ -223,14 +220,14 @@ func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyServic
// If API key header is present and API key auth is allowed, prioritize it.
// If validation fails, do NOT fall back to Bearer auth.
- if reqs.apiKeyAuth && ctx.Header(headerApiKey) != "" {
+ if reqs.apiKeyAuth && ctx.Header(pkgutils.HeaderApiKey) != "" {
if user, ok := tryApiKeyAuthInternal(ctx, apiKeyService); ok {
newCtx := setUserInContextInternal(ctx.Context(), user)
ctx = huma.WithContext(ctx, newCtx)
next(ctx)
return
}
- if user, ok := tryEnvironmentAccessTokenAuth(ctx, envTokenResolver, ctx.Header(headerApiKey)); ok {
+ if user, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(pkgutils.HeaderApiKey)); ok {
newCtx := setUserInContextInternal(ctx.Context(), user)
ctx = huma.WithContext(ctx, newCtx)
next(ctx)
@@ -241,7 +238,7 @@ func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyServic
return
}
- if user, ok := tryEnvironmentAccessTokenAuth(ctx, envTokenResolver, ctx.Header(headerAgentToken)); ok {
+ if user, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(pkgutils.HeaderAgentToken)); ok {
newCtx := setUserInContextInternal(ctx.Context(), user)
ctx = huma.WithContext(ctx, newCtx)
next(ctx)
@@ -249,12 +246,18 @@ func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyServic
}
if reqs.bearerAuth {
- if user, ok := tryBearerAuthInternal(ctx, authService); ok {
+ user, err := tryBearerAuthInternal(ctx, authService)
+ if err == nil && user != nil {
newCtx := setUserInContextInternal(ctx.Context(), user)
ctx = huma.WithContext(ctx, newCtx)
next(ctx)
return
}
+ if errors.Is(err, services.ErrTokenVersionMismatch) {
+ ctx.AppendHeader("Set-Cookie", cookie.BuildClearTokenCookieStringFor(ctx.TLS() != nil))
+ _ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Application has been updated. Please log in again.")
+ return
+ }
}
// Write unauthorized response directly
diff --git a/backend/internal/huma/middleware/auth_test.go b/backend/api/middleware/auth_test.go
similarity index 92%
rename from backend/internal/huma/middleware/auth_test.go
rename to backend/api/middleware/auth_test.go
index 256ad04cd..7e4678d70 100644
--- a/backend/internal/huma/middleware/auth_test.go
+++ b/backend/api/middleware/auth_test.go
@@ -7,11 +7,11 @@ import (
"testing"
"github.com/danielgtaylor/huma/v2"
- "github.com/danielgtaylor/huma/v2/adapters/humagin"
+ "github.com/danielgtaylor/huma/v2/adapters/humaecho"
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
)
@@ -35,10 +35,8 @@ func (r testEnvironmentAccessResolver) ResolveEnvironmentByAccessToken(_ context
}
func TestNewAuthBridge_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
token := "env-access-token"
- router := gin.New()
+ router := echo.New()
apiGroup := router.Group("/api")
humaConfig := huma.DefaultConfig("test", "1.0.0")
@@ -50,7 +48,7 @@ func TestNewAuthBridge_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {
},
}
- api := humagin.NewWithGroup(router, apiGroup, humaConfig)
+ api := humaecho.NewWithGroup(router, apiGroup, humaConfig)
api.UseMiddleware(NewAuthBridge(api, &services.AuthService{}, nil, testEnvironmentAccessResolver{
env: &models.Environment{
BaseModel: models.BaseModel{ID: "env-self"},
@@ -94,16 +92,14 @@ func (p testOperationProvider) Operation() *huma.Operation {
}
func TestParseSecurityRequirements(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
- router := gin.New()
+ router := echo.New()
apiGroup := router.Group("/api")
humaConfig := huma.DefaultConfig("test", "1.0.0")
humaConfig.Security = []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
}
- api := humagin.NewWithGroup(router, apiGroup, humaConfig)
+ api := humaecho.NewWithGroup(router, apiGroup, humaConfig)
testCases := []struct {
name string
diff --git a/backend/internal/api/playwright_handler.go b/backend/api/playwright.go
similarity index 55%
rename from backend/internal/api/playwright_handler.go
rename to backend/api/playwright.go
index f99095848..ee2f0b828 100644
--- a/backend/internal/api/playwright_handler.go
+++ b/backend/api/playwright.go
@@ -6,7 +6,7 @@ import (
"net/http"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
)
type PlaywrightHandler struct {
@@ -17,7 +17,7 @@ func NewPlaywrightHandler(playwrightService *services.PlaywrightService) *Playwr
return &PlaywrightHandler{PlaywrightService: playwrightService}
}
-func SetupPlaywrightRoutes(api *gin.RouterGroup, playwrightService *services.PlaywrightService) {
+func SetupPlaywrightRoutes(api *echo.Group, playwrightService *services.PlaywrightService) {
playwright := api.Group("/playwright")
playwrightHandler := NewPlaywrightHandler(playwrightService)
@@ -30,10 +30,9 @@ type CreateTestApiKeysRequest struct {
Count int `json:"count"`
}
-func (ph *PlaywrightHandler) CreateTestApiKeysHandler(c *gin.Context) {
+func (ph *PlaywrightHandler) CreateTestApiKeysHandler(c echo.Context) error {
var req CreateTestApiKeysRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- // Default to 2 if no count provided
+ if err := c.Bind(&req); err != nil {
req.Count = 2
}
@@ -41,20 +40,18 @@ func (ph *PlaywrightHandler) CreateTestApiKeysHandler(c *gin.Context) {
req.Count = 2
}
- apiKeys, err := ph.PlaywrightService.CreateTestApiKeys(c.Request.Context(), req.Count)
+ apiKeys, err := ph.PlaywrightService.CreateTestApiKeys(c.Request().Context(), req.Count)
if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
+ return c.JSON(http.StatusInternalServerError, map[string]any{"error": err.Error()})
}
- c.JSON(http.StatusCreated, gin.H{"apiKeys": apiKeys})
+ return c.JSON(http.StatusCreated, map[string]any{"apiKeys": apiKeys})
}
-func (ph *PlaywrightHandler) DeleteTestApiKeysHandler(c *gin.Context) {
- if err := ph.PlaywrightService.DeleteAllTestApiKeys(c.Request.Context()); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
+func (ph *PlaywrightHandler) DeleteTestApiKeysHandler(c echo.Context) error {
+ if err := ph.PlaywrightService.DeleteAllTestApiKeys(c.Request().Context()); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]any{"error": err.Error()})
}
- c.Status(http.StatusNoContent)
+ return c.NoContent(http.StatusNoContent)
}
diff --git a/backend/api/webhooks_trigger.go b/backend/api/webhooks_trigger.go
new file mode 100644
index 000000000..eed0ecdbb
--- /dev/null
+++ b/backend/api/webhooks_trigger.go
@@ -0,0 +1,41 @@
+package api
+
+import (
+ "errors"
+ "net/http"
+
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/labstack/echo/v4"
+)
+
+// RegisterWebhookTrigger registers the public (unauthenticated) trigger endpoint.
+// The token in the URL is the sole authentication mechanism.
+//
+// Security note: tokens appear in server access logs and browser history. Ensure access
+// logs are appropriately protected, and consider rate-limiting this endpoint at the
+// reverse-proxy level.
+func RegisterWebhookTrigger(g *echo.Group, webhookService *services.WebhookService) {
+ g.POST("/webhooks/trigger/:token", func(c echo.Context) error {
+ if webhookService == nil {
+ return c.JSON(http.StatusInternalServerError, map[string]any{"success": false, "error": "service not available"})
+ }
+
+ token := c.Param("token")
+ result, err := webhookService.TriggerByToken(c.Request().Context(), token)
+ if err != nil {
+ status := http.StatusInternalServerError
+ if errors.Is(err, services.ErrWebhookNotFound) || errors.Is(err, services.ErrWebhookInvalid) {
+ status = http.StatusNotFound
+ } else if errors.Is(err, services.ErrWebhookDisabled) {
+ status = http.StatusForbidden
+ }
+ msg := err.Error()
+ if status == http.StatusInternalServerError {
+ msg = "internal server error"
+ }
+ return c.JSON(status, map[string]any{"success": false, "error": msg})
+ }
+
+ return c.JSON(http.StatusOK, map[string]any{"success": true, "data": result})
+ })
+}
diff --git a/backend/internal/api/ws_handler.go b/backend/api/ws/handler.go
similarity index 89%
rename from backend/internal/api/ws_handler.go
rename to backend/api/ws/handler.go
index 4a5390c47..4f384cf32 100644
--- a/backend/internal/api/ws_handler.go
+++ b/backend/api/ws/handler.go
@@ -1,4 +1,4 @@
-package api
+package ws
import (
"context"
@@ -20,11 +20,11 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/services"
docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/system"
- ws "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
+ wshub "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
httputil "github.com/getarcaneapp/arcane/backend/pkg/utils/httpx"
systemtypes "github.com/getarcaneapp/arcane/types/system"
- "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
"github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/disk"
"github.com/shirou/gopsutil/v4/host"
@@ -189,7 +189,7 @@ type WebSocketHandler struct {
}
type wsLogStream struct {
- hub *ws.Hub
+ hub *wshub.Hub
cancel context.CancelFunc
firstSubscriber chan struct{}
format string
@@ -199,8 +199,8 @@ type wsLogStream struct {
seq atomic.Uint64
}
-func getContextUserIDInternal(c *gin.Context) string {
- if val, ok := c.Get("userID"); ok {
+func getContextUserIDInternal(c echo.Context) string {
+ if val := c.Get("userID"); val != nil {
if userID, ok := val.(string); ok {
return userID
}
@@ -208,14 +208,14 @@ func getContextUserIDInternal(c *gin.Context) string {
return ""
}
-func buildWSConnectionInfoInternal(c *gin.Context, kind, resourceID string) systemtypes.WebSocketConnectionInfo {
+func buildWSConnectionInfoInternal(c echo.Context, kind, resourceID string) systemtypes.WebSocketConnectionInfo {
return systemtypes.WebSocketConnectionInfo{
Kind: kind,
EnvID: c.Param("id"),
ResourceID: resourceID,
- ClientIP: c.ClientIP(),
+ ClientIP: c.RealIP(),
UserID: getContextUserIDInternal(c),
- UserAgent: c.GetHeader("User-Agent"),
+ UserAgent: c.Request().Header.Get("User-Agent"),
}
}
@@ -312,7 +312,7 @@ func (h *WebSocketHandler) markLogStreamDoneInternal(key string, stream *wsLogSt
}
func NewWebSocketHandler(
- group *gin.RouterGroup,
+ group *echo.Group,
projectService *services.ProjectService,
containerService *services.ContainerService,
swarmService *services.SwarmService,
@@ -336,16 +336,13 @@ func NewWebSocketHandler(
EnableCompression: true,
},
}
- wsGroup := group.Group("/environments/:id/ws")
- wsGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- wsGroup.GET("/projects/:projectId/logs", handler.ProjectLogs)
- wsGroup.GET("/containers/:containerId/logs", handler.ContainerLogs)
- wsGroup.GET("/containers/:containerId/stats", handler.ContainerStats)
- wsGroup.GET("/containers/:containerId/terminal", handler.ContainerExec)
- wsGroup.GET("/swarm/services/:serviceId/logs", handler.ServiceLogs)
- wsGroup.GET("/system/stats", handler.SystemStats)
- }
+ wsGroup := group.Group("/environments/:id/ws", authMiddleware.WithAdminNotRequired().Add())
+ wsGroup.GET("/projects/:projectId/logs", handler.ProjectLogs)
+ wsGroup.GET("/containers/:containerId/logs", handler.ContainerLogs)
+ wsGroup.GET("/containers/:containerId/stats", handler.ContainerStats)
+ wsGroup.GET("/containers/:containerId/terminal", handler.ContainerExec)
+ wsGroup.GET("/swarm/services/:serviceId/logs", handler.ServiceLogs)
+ wsGroup.GET("/system/stats", handler.SystemStats)
}
// ============================================================================
@@ -362,24 +359,32 @@ type logStreamParams struct {
batched bool
}
-func parseLogStreamParamsInternal(c *gin.Context) logStreamParams {
- tail, _ := httputil.GetQueryParam(c, "tail", false)
+func parseLogStreamParamsInternal(c echo.Context) logStreamParams {
+ req := c.Request()
+ tail, _ := httputil.GetQueryParam(req, "tail", false)
if tail == "" {
tail = "100"
}
- since, _ := httputil.GetQueryParam(c, "since", false)
- format, _ := httputil.GetQueryParam(c, "format", false)
+ since, _ := httputil.GetQueryParam(req, "since", false)
+ format, _ := httputil.GetQueryParam(req, "format", false)
if format == "" {
format = "text"
}
return logStreamParams{
- follow: c.DefaultQuery("follow", "true") == "true",
+ follow: queryParamWithDefaultInternal(c, "follow", "true") == "true",
tail: tail,
since: since,
- timestamps: c.DefaultQuery("timestamps", "false") == "true",
+ timestamps: queryParamWithDefaultInternal(c, "timestamps", "false") == "true",
format: format,
- batched: c.DefaultQuery("batched", "false") == "true",
+ batched: queryParamWithDefaultInternal(c, "batched", "false") == "true",
+ }
+}
+
+func queryParamWithDefaultInternal(c echo.Context, key, def string) string {
+ if v := c.QueryParam(key); v != "" {
+ return v
}
+ return def
}
// serveLogStreamInternal is the shared scaffold for all three WS log endpoints (project, container, service).
@@ -387,12 +392,12 @@ func parseLogStreamParamsInternal(c *gin.Context) logStreamParams {
// and serves the client. The caller-supplied hubBuilder constructs the underlying *wsLogStream
// when no hub already exists for streamKey.
func (h *WebSocketHandler) serveLogStreamInternal(
- c *gin.Context,
+ c echo.Context,
kind, resourceID string,
params logStreamParams,
hubBuilder func(streamKey string, onEmpty func(*wsLogStream)) *wsLogStream,
) {
- conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ conn, err := h.wsUpgrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
return
}
@@ -405,7 +410,7 @@ func (h *WebSocketHandler) serveLogStreamInternal(
// WebSocket connections use context.Background() because they are long-lived and should not
// be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback
// which triggers when all clients disconnect.
- ws.ServeClientWithOnRemove(context.Background(), stream.hub, conn, func() {
+ wshub.ServeClientWithOnRemove(context.Background(), stream.hub, conn, func() {
h.wsMetrics.UnregisterConnection(connID)
h.releaseLogStreamInternal(streamKey, stream)
})
@@ -418,12 +423,12 @@ func broadcastLogStreamErrorInternal(resourceLabel, errorPrefix string, resource
slog.Warn(resourceLabel+" failed", "resourceID", resourceID, "error", err)
if format == "json" {
- msg := ws.LogMessage{
+ msg := wshub.LogMessage{
Seq: ls.seq.Add(1),
Level: "error",
Message: errorPrefix + err.Error(),
Service: "arcane",
- Timestamp: ws.NowRFC3339(),
+ Timestamp: wshub.NowRFC3339(),
}
if b, marshalErr := json.Marshal(msg); marshalErr == nil {
ls.hub.Broadcast(b)
@@ -452,22 +457,22 @@ func broadcastLogStreamErrorInternal(resourceLabel, errorPrefix string, resource
// @Param format query string false "Output format (text or json)" default(text)
// @Param batched query bool false "Batch log messages" default(false)
// @Router /api/environments/{id}/ws/projects/{projectId}/logs [get]
-func (h *WebSocketHandler) ProjectLogs(c *gin.Context) {
+func (h *WebSocketHandler) ProjectLogs(c echo.Context) error {
projectID := c.Param("projectId")
if strings.TrimSpace(projectID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
- return
+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
}
params := parseLogStreamParamsInternal(c)
h.serveLogStreamInternal(c, systemtypes.WSKindProjectLogs, projectID, params, func(streamKey string, onEmpty func(*wsLogStream)) *wsLogStream {
return h.startProjectLogHub(streamKey, projectID, params.format, params.batched, params.follow, params.tail, params.since, params.timestamps, onEmpty)
})
+ return nil
}
func newWSLogStreamInternal(key, format string) (*wsLogStream, context.Context) {
ls := &wsLogStream{
- hub: ws.NewHub(1024),
+ hub: wshub.NewHub(1024),
firstSubscriber: make(chan struct{}),
format: format,
key: key,
@@ -536,17 +541,17 @@ func startProjectLogForwardersInternal(ctx context.Context, format string, batch
}
func startProjectJSONForwarderInternal(ctx context.Context, batched bool, lines <-chan string, ls *wsLogStream) {
- msgs := make(chan ws.LogMessage, 256)
+ msgs := make(chan wshub.LogMessage, 256)
go func() {
defer close(msgs)
for line := range lines {
- level, service, msg, ts := ws.NormalizeProjectLine(line)
+ level, service, msg, ts := wshub.NormalizeProjectLine(line)
seq := ls.seq.Add(1)
timestamp := ts
if timestamp == "" {
- timestamp = ws.NowRFC3339()
+ timestamp = wshub.NowRFC3339()
}
- msgs <- ws.LogMessage{
+ msgs <- wshub.LogMessage{
Seq: seq,
Level: level,
Message: msg,
@@ -557,11 +562,11 @@ func startProjectJSONForwarderInternal(ctx context.Context, batched bool, lines
}()
if batched {
- go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
+ go wshub.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
return
}
- go ws.ForwardLogJSON(ctx, ls.hub, msgs)
+ go wshub.ForwardLogJSON(ctx, ls.hub, msgs)
}
func startProjectTextForwarderInternal(ctx context.Context, lines <-chan string, ls *wsLogStream) {
@@ -569,12 +574,12 @@ func startProjectTextForwarderInternal(ctx context.Context, lines <-chan string,
go func() {
defer close(cleanChan)
for line := range lines {
- _, _, msg, _ := ws.NormalizeProjectLine(line)
+ _, _, msg, _ := wshub.NormalizeProjectLine(line)
cleanChan <- msg
}
}()
- go ws.ForwardLines(ctx, ls.hub, cleanChan)
+ go wshub.ForwardLines(ctx, ls.hub, cleanChan)
}
func (h *WebSocketHandler) startProjectLogHub(key, projectID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
@@ -611,17 +616,17 @@ func (h *WebSocketHandler) startProjectLogHub(key, projectID, format string, bat
// @Param format query string false "Output format (text or json)" default(text)
// @Param batched query bool false "Batch log messages" default(false)
// @Router /api/environments/{id}/ws/containers/{containerId}/logs [get]
-func (h *WebSocketHandler) ContainerLogs(c *gin.Context) {
+func (h *WebSocketHandler) ContainerLogs(c echo.Context) error {
containerID := c.Param("containerId")
if strings.TrimSpace(containerID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
- return
+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
}
params := parseLogStreamParamsInternal(c)
h.serveLogStreamInternal(c, systemtypes.WSKindContainerLogs, containerID, params, func(streamKey string, onEmpty func(*wsLogStream)) *wsLogStream {
return h.startContainerLogHub(streamKey, containerID, params.format, params.batched, params.follow, params.tail, params.since, params.timestamps, onEmpty)
})
+ return nil
}
func (h *WebSocketHandler) startContainerLogHub(key, containerID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
@@ -657,17 +662,17 @@ func (h *WebSocketHandler) startContainerLogHub(key, containerID, format string,
}(ctx)
if format == "json" {
- msgs := make(chan ws.LogMessage, 256)
+ msgs := make(chan wshub.LogMessage, 256)
go func() {
defer close(msgs)
for line := range lines {
- level, msg, ts := ws.NormalizeContainerLine(line)
+ level, msg, ts := wshub.NormalizeContainerLine(line)
seq := ls.seq.Add(1)
timestamp := ts
if timestamp == "" {
- timestamp = ws.NowRFC3339()
+ timestamp = wshub.NowRFC3339()
}
- msgs <- ws.LogMessage{
+ msgs <- wshub.LogMessage{
Seq: seq,
Level: level,
Message: msg,
@@ -676,12 +681,12 @@ func (h *WebSocketHandler) startContainerLogHub(key, containerID, format string,
}
}()
if batched {
- go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
+ go wshub.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
} else {
- go ws.ForwardLogJSON(ctx, ls.hub, msgs)
+ go wshub.ForwardLogJSON(ctx, ls.hub, msgs)
}
} else {
- go ws.ForwardLines(ctx, ls.hub, lines)
+ go wshub.ForwardLines(ctx, ls.hub, lines)
}
return ls
@@ -709,17 +714,17 @@ func (h *WebSocketHandler) broadcastContainerLogStreamErrorInternal(containerID,
// @Param format query string false "Output format (text or json)" default(text)
// @Param batched query bool false "Batch log messages" default(false)
// @Router /api/environments/{id}/ws/swarm/services/{serviceId}/logs [get]
-func (h *WebSocketHandler) ServiceLogs(c *gin.Context) {
+func (h *WebSocketHandler) ServiceLogs(c echo.Context) error {
serviceID := c.Param("serviceId")
if strings.TrimSpace(serviceID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Service ID is required"})
- return
+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": "Service ID is required"})
}
params := parseLogStreamParamsInternal(c)
h.serveLogStreamInternal(c, systemtypes.WSKindServiceLogs, serviceID, params, func(streamKey string, onEmpty func(*wsLogStream)) *wsLogStream {
return h.startServiceLogHub(streamKey, serviceID, params.format, params.batched, params.follow, params.tail, params.since, params.timestamps, onEmpty)
})
+ return nil
}
func (h *WebSocketHandler) startServiceLogHub(key, serviceID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
@@ -755,17 +760,17 @@ func (h *WebSocketHandler) startServiceLogHub(key, serviceID, format string, bat
}()
if format == "json" {
- msgs := make(chan ws.LogMessage, 256)
+ msgs := make(chan wshub.LogMessage, 256)
go func() {
defer close(msgs)
for line := range lines {
- level, msg, ts := ws.NormalizeContainerLine(line)
+ level, msg, ts := wshub.NormalizeContainerLine(line)
seq := ls.seq.Add(1)
timestamp := ts
if timestamp == "" {
- timestamp = ws.NowRFC3339()
+ timestamp = wshub.NowRFC3339()
}
- msgs <- ws.LogMessage{
+ msgs <- wshub.LogMessage{
Seq: seq,
Level: level,
Message: msg,
@@ -774,12 +779,12 @@ func (h *WebSocketHandler) startServiceLogHub(key, serviceID, format string, bat
}
}()
if batched {
- go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
+ go wshub.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
} else {
- go ws.ForwardLogJSON(ctx, ls.hub, msgs)
+ go wshub.ForwardLogJSON(ctx, ls.hub, msgs)
}
} else {
- go ws.ForwardLines(ctx, ls.hub, lines)
+ go wshub.ForwardLines(ctx, ls.hub, lines)
}
return ls
@@ -797,16 +802,16 @@ func (h *WebSocketHandler) broadcastServiceLogStreamErrorInternal(serviceID, for
// @Param id path string true "Environment ID"
// @Param containerId path string true "Container ID"
// @Router /api/environments/{id}/ws/containers/{containerId}/stats [get]
-func (h *WebSocketHandler) ContainerStats(c *gin.Context) {
+func (h *WebSocketHandler) ContainerStats(c echo.Context) error {
containerID := c.Param("containerId")
if strings.TrimSpace(containerID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
- return
+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
}
- conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ conn, err := h.wsUpgrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
- return
+ slog.DebugContext(c.Request().Context(), "Failed to upgrade WebSocket for container stats", "containerID", containerID, "error", err)
+ return nil //nolint:nilerr // Upgrade has already written an HTTP error response to the client.
}
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindContainerStats, containerID))
@@ -816,11 +821,12 @@ func (h *WebSocketHandler) ContainerStats(c *gin.Context) {
// WebSocket connections use context.Background() because they are long-lived and should not
// be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback
// which triggers when all clients disconnect.
- ws.ServeClient(context.Background(), hub, conn)
+ wshub.ServeClient(context.Background(), hub, conn)
+ return nil
}
-func (h *WebSocketHandler) startContainerStatsHub(containerID string, onEmptyHook func()) *ws.Hub {
- hub := ws.NewHub(64)
+func (h *WebSocketHandler) startContainerStatsHub(containerID string, onEmptyHook func()) *wshub.Hub {
+ hub := wshub.NewHub(64)
ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec // cancel is intentionally retained and invoked by the hub OnEmpty callback.
@@ -868,18 +874,17 @@ func (h *WebSocketHandler) startContainerStatsHub(containerID string, onEmptyHoo
// @Param containerId path string true "Container ID"
// @Param shell query string false "Shell to execute" default(/bin/sh)
// @Router /api/environments/{id}/ws/containers/{containerId}/terminal [get]
-func (h *WebSocketHandler) ContainerExec(c *gin.Context) {
+func (h *WebSocketHandler) ContainerExec(c echo.Context) error {
containerID := c.Param("containerId")
if strings.TrimSpace(containerID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
- return
+ return c.JSON(http.StatusBadRequest, map[string]any{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
}
- shell := c.DefaultQuery("shell", "/bin/sh")
+ shell := queryParamWithDefaultInternal(c, "shell", "/bin/sh")
- conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ conn, err := h.wsUpgrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
- return
+ return nil
}
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindContainerExec, containerID))
defer h.wsMetrics.UnregisterConnection(connID)
@@ -889,10 +894,11 @@ func (h *WebSocketHandler) ContainerExec(c *gin.Context) {
}
}()
- ctx, cancel := context.WithCancel(c.Request.Context())
+ ctx, cancel := context.WithCancel(c.Request().Context())
defer cancel()
h.runContainerExecInternal(ctx, cancel, conn, containerID, shell)
+ return nil
}
func (h *WebSocketHandler) runContainerExecInternal(ctx context.Context, cancel context.CancelFunc, conn *websocket.Conn, containerID, shell string) {
@@ -1324,22 +1330,21 @@ func (h *WebSocketHandler) getCachedCgroupLimitsInternal() *docker.CgroupLimits
// @Tags WebSocket
// @Param id path string true "Environment ID"
// @Router /api/environments/{id}/ws/system/stats [get]
-func (h *WebSocketHandler) SystemStats(c *gin.Context) {
- clientIP := c.ClientIP()
+func (h *WebSocketHandler) SystemStats(c echo.Context) error {
+ clientIP := c.RealIP()
count, allowed := h.checkRateLimit(clientIP)
if !allowed {
- c.JSON(http.StatusTooManyRequests, gin.H{
+ return c.JSON(http.StatusTooManyRequests, map[string]any{
"success": false,
"error": "Too many concurrent stats connections from this IP",
})
- return
}
defer h.releaseRateLimit(clientIP, count)
- conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ conn, err := h.wsUpgrader.Upgrade(c.Response().Writer, c.Request(), nil)
if err != nil {
- return
+ return nil
}
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindSystemStats, ""))
defer h.wsMetrics.UnregisterConnection(connID)
@@ -1349,7 +1354,7 @@ func (h *WebSocketHandler) SystemStats(c *gin.Context) {
}
}()
- interval, _ := httputil.GetIntQueryParam(c, "interval", false)
+ interval, _ := httputil.GetIntQueryParam(c.Request(), "interval", false)
if interval <= 0 {
interval = 2
}
@@ -1372,11 +1377,11 @@ func (h *WebSocketHandler) SystemStats(c *gin.Context) {
pingTicker := time.NewTicker(statsPingPeriod)
defer pingTicker.Stop()
- ctx, cancel := context.WithCancel(c.Request.Context())
+ ctx, cancel := context.WithCancel(c.Request().Context())
defer cancel()
if !h.acquireSystemStatsSamplerInternal(ctx) {
h.releaseSystemStatsSamplerInternal()
- return
+ return nil
}
defer h.releaseSystemStatsSamplerInternal()
@@ -1389,21 +1394,21 @@ func (h *WebSocketHandler) SystemStats(c *gin.Context) {
}
if err := send(); err != nil {
- return
+ return nil
}
for {
select {
case <-ctx.Done():
- return
+ return nil
case <-ticker.C:
if err := send(); err != nil {
- return
+ return nil
}
case <-pingTicker.C:
_ = conn.SetWriteDeadline(time.Now().Add(statsPingWriteWait))
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
- return
+ return nil
}
}
}
diff --git a/backend/internal/api/ws_handler_test.go b/backend/api/ws/handler_test.go
similarity index 96%
rename from backend/internal/api/ws_handler_test.go
rename to backend/api/ws/handler_test.go
index a82ac4f2f..c3683034f 100644
--- a/backend/internal/api/ws_handler_test.go
+++ b/backend/api/ws/handler_test.go
@@ -1,4 +1,4 @@
-package api
+package ws
import (
"context"
@@ -14,22 +14,22 @@ import (
docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/system"
- ws "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
+ wshub "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
systemtypes "github.com/getarcaneapp/arcane/types/system"
- "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
)
func TestBroadcastContainerLogStreamErrorInternal_JSON(t *testing.T) {
- hub := ws.NewHub(10)
+ hub := wshub.NewHub(10)
ctx := t.Context()
go hub.Run(ctx)
clientConn, serverConn, cleanup := newTestWSPairInternal(t)
t.Cleanup(cleanup)
- ws.ServeClient(ctx, hub, serverConn)
+ wshub.ServeClient(ctx, hub, serverConn)
stream := &wsLogStream{
hub: hub,
@@ -43,7 +43,7 @@ func TestBroadcastContainerLogStreamErrorInternal_JSON(t *testing.T) {
_, payload, err := clientConn.ReadMessage()
require.NoError(t, err)
- var message ws.LogMessage
+ var message wshub.LogMessage
require.NoError(t, json.Unmarshal(payload, &message))
require.Equal(t, "error", message.Level)
require.Equal(t, "Failed to stream container logs: boom", message.Message)
@@ -52,14 +52,14 @@ func TestBroadcastContainerLogStreamErrorInternal_JSON(t *testing.T) {
}
func TestBroadcastContainerLogStreamErrorInternal_Text(t *testing.T) {
- hub := ws.NewHub(10)
+ hub := wshub.NewHub(10)
ctx := t.Context()
go hub.Run(ctx)
clientConn, serverConn, cleanup := newTestWSPairInternal(t)
t.Cleanup(cleanup)
- ws.ServeClient(ctx, hub, serverConn)
+ wshub.ServeClient(ctx, hub, serverConn)
stream := &wsLogStream{
hub: hub,
@@ -130,7 +130,6 @@ func dialWebSocket(t *testing.T, serverURL, path string) *websocket.Conn {
}
func TestWebSocketHandler_ProjectLogs_SharedStreamPerTarget(t *testing.T) {
- gin.SetMode(gin.TestMode)
handler := newTestWebSocketHandler()
var starts atomic.Int32
@@ -156,7 +155,7 @@ func TestWebSocketHandler_ProjectLogs_SharedStreamPerTarget(t *testing.T) {
}
}
- router := gin.New()
+ router := echo.New()
router.GET("/api/environments/:id/ws/projects/:projectId/logs", handler.ProjectLogs)
server := httptest.NewServer(router)
defer server.Close()
@@ -209,7 +208,6 @@ func TestWebSocketHandler_ProjectLogs_SharedStreamPerTarget(t *testing.T) {
}
func TestWebSocketHandler_ProjectLogs_CompletedSourceStartsFreshStream(t *testing.T) {
- gin.SetMode(gin.TestMode)
handler := newTestWebSocketHandler()
var starts atomic.Int32
@@ -228,7 +226,7 @@ func TestWebSocketHandler_ProjectLogs_CompletedSourceStartsFreshStream(t *testin
return nil
}
- router := gin.New()
+ router := echo.New()
router.GET("/api/environments/:id/ws/projects/:projectId/logs", handler.ProjectLogs)
server := httptest.NewServer(router)
defer server.Close()
@@ -262,7 +260,6 @@ func TestWebSocketHandler_ProjectLogs_CompletedSourceStartsFreshStream(t *testin
}
func TestWebSocketHandler_ContainerLogs_BroadcastsStreamErrors(t *testing.T) {
- gin.SetMode(gin.TestMode)
handler := newTestWebSocketHandler()
handler.containerLogStreamer = func(ctx context.Context, containerID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error {
@@ -274,7 +271,7 @@ func TestWebSocketHandler_ContainerLogs_BroadcastsStreamErrors(t *testing.T) {
return errors.New("stream failed")
}
- router := gin.New()
+ router := echo.New()
router.GET("/api/environments/:id/ws/containers/:containerId/logs", handler.ContainerLogs)
server := httptest.NewServer(router)
defer server.Close()
@@ -301,7 +298,6 @@ func TestWebSocketHandler_ContainerLogs_BroadcastsStreamErrors(t *testing.T) {
}
func TestWebSocketHandler_ContainerLogs_ErrorStartsFreshStreamForNewSubscribers(t *testing.T) {
- gin.SetMode(gin.TestMode)
handler := newTestWebSocketHandler()
var starts atomic.Int32
@@ -315,7 +311,7 @@ func TestWebSocketHandler_ContainerLogs_ErrorStartsFreshStreamForNewSubscribers(
return errors.New("stream failed")
}
- router := gin.New()
+ router := echo.New()
router.GET("/api/environments/:id/ws/containers/:containerId/logs", handler.ContainerLogs)
server := httptest.NewServer(router)
defer server.Close()
@@ -357,7 +353,6 @@ func TestWebSocketHandler_ContainerLogs_ErrorStartsFreshStreamForNewSubscribers(
}
func TestWebSocketHandler_SystemStats_UsesSharedSampler(t *testing.T) {
- gin.SetMode(gin.TestMode)
handler := newTestWebSocketHandler()
var collects atomic.Int32
@@ -369,7 +364,7 @@ func TestWebSocketHandler_SystemStats_UsesSharedSampler(t *testing.T) {
}
}
- router := gin.New()
+ router := echo.New()
router.GET("/api/environments/:id/ws/system/stats", handler.SystemStats)
server := httptest.NewServer(router)
defer server.Close()
@@ -512,7 +507,7 @@ func TestWebSocketHandler_LogStream_ReplacesDoneStreamAndCleansStaleRefs(t *test
var staleCancels atomic.Int32
stale := &wsLogStream{
- hub: ws.NewHub(1),
+ hub: wshub.NewHub(1),
cancel: func() { staleCancels.Add(1) },
refs: 2,
done: true,
@@ -522,7 +517,7 @@ func TestWebSocketHandler_LogStream_ReplacesDoneStreamAndCleansStaleRefs(t *test
var freshCancels atomic.Int32
fresh := handler.getOrCreateLogStreamInternal(key, func(onEmpty func(*wsLogStream)) *wsLogStream {
return &wsLogStream{
- hub: ws.NewHub(1),
+ hub: wshub.NewHub(1),
cancel: func() { freshCancels.Add(1) },
}
})
@@ -563,7 +558,7 @@ func TestWebSocketHandler_LogStream_CancelsOnlyOnce(t *testing.T) {
var cancels atomic.Int32
stream := &wsLogStream{
- hub: ws.NewHub(1),
+ hub: wshub.NewHub(1),
cancel: func() { cancels.Add(1) },
refs: 1,
}
diff --git a/backend/cli/openapi.go b/backend/cli/openapi.go
index 16085bed5..7cba984cc 100644
--- a/backend/cli/openapi.go
+++ b/backend/cli/openapi.go
@@ -4,7 +4,7 @@ import (
"fmt"
"os"
- "github.com/getarcaneapp/arcane/backend/internal/huma"
+ "github.com/getarcaneapp/arcane/backend/api"
"github.com/spf13/cobra"
)
@@ -18,19 +18,19 @@ var openapiCmd = &cobra.Command{
outputFile, _ := cmd.Flags().GetString("output")
// Create Huma API for spec generation (no services needed)
- api := huma.SetupAPIForSpec()
+ humaAPI := api.SetupAPIForSpec()
// Generate output
var output []byte
var err error
if format == "json" {
- output, err = api.OpenAPI().MarshalJSON()
+ output, err = humaAPI.OpenAPI().MarshalJSON()
} else {
if downgrade {
- output, err = api.OpenAPI().DowngradeYAML()
+ output, err = humaAPI.OpenAPI().DowngradeYAML()
} else {
- output, err = api.OpenAPI().YAML()
+ output, err = humaAPI.OpenAPI().YAML()
}
}
diff --git a/backend/frontend/excluded.go b/backend/frontend/excluded.go
index 19ab84ad7..85644ca53 100644
--- a/backend/frontend/excluded.go
+++ b/backend/frontend/excluded.go
@@ -2,8 +2,9 @@
package frontend
-import "github.com/gin-gonic/gin"
+import "github.com/labstack/echo/v4"
-func RegisterFrontend(router *gin.Engine) error {
+func RegisterFrontend(e *echo.Echo) error {
+ _ = e
return ErrFrontendNotIncluded
}
diff --git a/backend/frontend/frontend.go b/backend/frontend/frontend.go
index ccd029378..97e8295bb 100644
--- a/backend/frontend/frontend.go
+++ b/backend/frontend/frontend.go
@@ -4,6 +4,7 @@ package frontend
import (
"embed"
+ "errors"
"fmt"
"io/fs"
"net/http"
@@ -11,7 +12,7 @@ import (
"strings"
"time"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
)
//go:embed all:dist
@@ -19,7 +20,10 @@ var frontendFS embed.FS
const indexHtmlFileConstant = "index.html"
-func RegisterFrontend(router *gin.Engine) error {
+// RegisterFrontend mounts the embedded SPA on the Echo instance and configures
+// a custom HTTP error handler that intercepts 404s to serve the SPA index
+// (preserving SvelteKit client-side routing) while keeping /api/* 404s as JSON.
+func RegisterFrontend(e *echo.Echo) error {
distFS, err := fs.Sub(frontendFS, "dist")
if err != nil {
return fmt.Errorf("failed to create sub FS: %w", err)
@@ -28,11 +32,20 @@ func RegisterFrontend(router *gin.Engine) error {
cacheMaxAge := time.Hour * 24
fileServer := NewFileServerWithCaching(http.FS(distFS), int(cacheMaxAge.Seconds()))
- router.NoRoute(func(c *gin.Context) {
- path := c.Request.URL.Path
+ defaultErrorHandler := e.HTTPErrorHandler
+ e.HTTPErrorHandler = func(handlerErr error, c echo.Context) {
+ var he *echo.HTTPError
+ isNotFound := errors.As(handlerErr, &he) && he.Code == http.StatusNotFound
+ if !isNotFound {
+ defaultErrorHandler(handlerErr, c)
+ return
+ }
+
+ req := c.Request()
+ path := req.URL.Path
if strings.HasPrefix(path, "/api/") {
- c.JSON(http.StatusNotFound, gin.H{
+ _ = c.JSON(http.StatusNotFound, map[string]any{
"success": false,
"error": fmt.Sprintf("API endpoint not found: %s", path),
})
@@ -44,12 +57,12 @@ func RegisterFrontend(router *gin.Engine) error {
requestedPath = indexHtmlFileConstant
}
- if _, err := fs.Stat(distFS, requestedPath); os.IsNotExist(err) {
- c.Request.URL.Path = "/"
+ if _, statErr := fs.Stat(distFS, requestedPath); os.IsNotExist(statErr) {
+ req.URL.Path = "/"
}
- fileServer.ServeHTTP(c.Writer, c.Request)
- })
+ fileServer.ServeHTTP(c.Response().Writer, req)
+ }
return nil
}
diff --git a/backend/go.mod b/backend/go.mod
index 3e1da5be5..be762efb0 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -21,8 +21,6 @@ require (
github.com/fsnotify/fsnotify v1.10.1
github.com/getarcaneapp/arcane/cli v1.16.3
github.com/getarcaneapp/arcane/types v1.18.1
- github.com/gin-contrib/cors v1.7.7
- github.com/gin-gonic/gin v1.12.0
github.com/glebarez/sqlite v1.11.0
github.com/go-git/go-git/v5 v5.19.0
github.com/goccy/go-yaml v1.19.2
@@ -34,6 +32,7 @@ require (
github.com/hashicorp/go-uuid v1.0.3
github.com/jinzhu/copier v0.4.0
github.com/joho/godotenv v1.5.1
+ github.com/labstack/echo/v4 v4.15.2
github.com/lmittmann/tint v1.1.3
github.com/moby/buildkit v0.29.0
github.com/moby/go-archive v0.2.0
@@ -45,7 +44,7 @@ require (
github.com/opencontainers/image-spec v1.1.1
github.com/orandin/slog-gorm v1.4.0
github.com/robfig/cron/v3 v3.0.1
- github.com/samber/slog-gin v1.21.1
+ github.com/samber/slog-echo v1.23.0
github.com/shirou/gopsutil/v4 v4.26.4
github.com/spf13/cobra v1.10.2
github.com/stretchr/testify v1.11.1
@@ -84,13 +83,9 @@ require (
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 // indirect
github.com/aws/smithy-go v1.25.1 // indirect
github.com/buger/goterm v1.0.4 // indirect
- github.com/bytedance/gopkg v0.1.3 // indirect
- github.com/bytedance/sonic v1.15.0 // indirect
- github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/cloudflare/circl v1.6.3 // indirect
- github.com/cloudwego/base64x v0.1.6 // indirect
github.com/containerd/console v1.0.5 // indirect
github.com/containerd/containerd/api v1.10.0 // indirect
github.com/containerd/containerd/v2 v2.2.3 // indirect
@@ -116,8 +111,6 @@ require (
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsevents v0.2.0 // indirect
github.com/fvbommel/sortorder v1.1.0 // indirect
- github.com/gabriel-vasile/mimetype v1.4.13 // indirect
- github.com/gin-contrib/sse v1.1.0 // indirect
github.com/glebarez/go-sqlite v1.22.0 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
github.com/go-git/go-billy/v5 v5.9.0 // indirect
@@ -125,11 +118,7 @@ require (
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
- github.com/go-playground/locales v0.14.1 // indirect
- github.com/go-playground/universal-translator v0.18.1 // indirect
- github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
- github.com/goccy/go-json v0.10.5 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/golang/protobuf v1.5.4 // indirect
@@ -154,11 +143,10 @@ require (
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jonboulle/clockwork v0.5.0 // indirect
- github.com/json-iterator/go v1.1.12 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/klauspost/compress v1.18.5 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
- github.com/leodido/go-urn v1.4.0 // indirect
+ github.com/labstack/gommon v0.5.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
@@ -177,8 +165,6 @@ require (
github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
- github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
- github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
github.com/morikuni/aec v1.1.0 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/pelletier/go-toml/v2 v2.3.1 // indirect
@@ -187,9 +173,8 @@ require (
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
- github.com/quic-go/qpack v0.6.0 // indirect
- github.com/quic-go/quic-go v0.59.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ github.com/samber/lo v1.52.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
github.com/secure-systems-lab/go-securesystemslib v0.10.0 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
@@ -208,12 +193,11 @@ require (
github.com/tonistiigi/go-csvvalue v0.0.0-20240814133006-030d3b2625d0 // indirect
github.com/tonistiigi/units v0.0.0-20180711220420-6950e57a87ea // indirect
github.com/tonistiigi/vt100 v0.0.0-20240514184818-90bafcd6abab // indirect
- github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
- github.com/ugorji/go/codec v1.3.1 // indirect
+ github.com/valyala/bytebufferpool v1.0.0 // indirect
+ github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xhit/go-str2duration/v2 v2.1.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
- go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0 // indirect
@@ -231,7 +215,6 @@ require (
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.podman.io/storage v1.62.0 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.4 // indirect
- golang.org/x/arch v0.24.0 // indirect
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
golang.org/x/sys v0.44.0 // indirect
golang.org/x/term v0.43.0 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 811c41a02..335334512 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -65,12 +65,6 @@ github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdn
github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
github.com/buger/goterm v1.0.4 h1:Z9YvGmOih81P0FbVtEYTFF6YsSgxSUKEhf/f9bTMXbY=
github.com/buger/goterm v1.0.4/go.mod h1:HiFWV3xnkolgrBV3mY8m0X0Pumt4zg4QhbdOzQtB8tE=
-github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
-github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
-github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
-github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
-github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
-github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -79,8 +73,6 @@ github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJ
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
-github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
-github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb h1:EDmT6Q9Zs+SbUoc7Ik9EfrFqcylYqgPZ9ANSbTAntnE=
github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb/go.mod h1:ZjrT6AXHbDs86ZSdt/osfBi5qfexBrKUdONk989Wnk4=
github.com/compose-spec/compose-go/v2 v2.10.2 h1:USa1NUbDcl/cjb8T9iwnuFsnO79H+2ho2L5SjFKz3uI=
@@ -183,14 +175,6 @@ github.com/fvbommel/sortorder v1.1.0 h1:fUmoe+HLsBTctBDoaBwpQo5N+nrCp8g/BjKb/6ZQ
github.com/fvbommel/sortorder v1.1.0/go.mod h1:uk88iVf1ovNn1iLfgUVU2F9o5eO30ui720w+kxuqRs0=
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
-github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
-github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
-github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q=
-github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE=
-github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
-github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
-github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
-github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
@@ -257,20 +241,10 @@ github.com/go-openapi/swag/yamlutils v0.25.5 h1:kASCIS+oIeoc55j28T4o8KwlV2S4ZLPT
github.com/go-openapi/swag/yamlutils v0.25.5/go.mod h1:Gek1/SjjfbYvM+Iq4QGwa/2lEXde9n2j4a3wI3pNuOQ=
github.com/go-openapi/validate v0.25.2 h1:12NsfLAwGegqbGWr2CnvT65X/Q2USJipmJ9b7xDJZz0=
github.com/go-openapi/validate v0.25.2/go.mod h1:Pgl1LpPPGFnZ+ys4/hTlDiRYQdI1ocKypgE+8Q8BLfY=
-github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
-github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
-github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
-github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
-github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
-github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
-github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
-github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
-github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
-github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=
@@ -299,7 +273,6 @@ github.com/google/go-github/v39 v39.2.0 h1:rNNM311XtPOz5rDdsJXAp2o8F67X9FnROXTvt
github.com/google/go-github/v39 v39.2.0/go.mod h1:C1s8C5aCC9L+JXIYpJM5GYytdX52vC1bLvHEF1IhBrE=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
-github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 h1:EwtI+Al+DeppwYX2oXJCETMO23COyaKGP6fHVpkpWpg=
github.com/google/pprof v0.0.0-20260402051712-545e8a4df936/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
@@ -353,8 +326,6 @@ github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=
github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
-github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
-github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
@@ -370,8 +341,10 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
-github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
-github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
+github.com/labstack/echo/v4 v4.15.2 h1:nnh2sCzGCVYnU+wCisMPiYapEg/QVo/gcI9ePKg5/T4=
+github.com/labstack/echo/v4 v4.15.2/go.mod h1:Xzp1Ns1RA2c9fY7nSgUJkpkUZGNbEIVHZbtbOMPktBI=
+github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c=
+github.com/labstack/gommon v0.5.0/go.mod h1:Rzlg7HHy1maLfzBYGg9NZcVuz1sA68HHhLjhcEllYE0=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lmittmann/tint v1.1.3 h1:Hv4EaHWXQr+GTFnOU4VKf8UvAtZgn0VuKT+G0wFlO3I=
@@ -424,12 +397,6 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
-github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
-github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
-github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=
-github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/morikuni/aec v1.1.0 h1:vBBl0pUnvi/Je71dsRrhMBtreIqNMYErSAbEeb8jrXQ=
github.com/morikuni/aec v1.1.0/go.mod h1:xDRgiq/iw5l+zkao76YTKzKttOp2cwPEne25HDkJnBw=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
@@ -479,10 +446,6 @@ github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9Z
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
-github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
-github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
-github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
-github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
@@ -490,8 +453,10 @@ github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzG
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
-github.com/samber/slog-gin v1.21.1 h1:DUsQyZdeT2vEfz/3xkoD4KWYVeuYWGz3XrEkjLwNCO4=
-github.com/samber/slog-gin v1.21.1/go.mod h1:7R4VMQGENllRLLnwGyoB5nUSB+qzxThpGe5G02xla6o=
+github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
+github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
+github.com/samber/slog-echo v1.23.0 h1:jFzK9t9hLvEjic2tfIkgXt2r22Zz2UYaYrUyM/S0pks=
+github.com/samber/slog-echo v1.23.0/go.mod h1:caG3zeXgrPRlGKaPVqyWG1MEc6nwrmtDjoLN/mc0PrM=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/secure-systems-lab/go-securesystemslib v0.10.0 h1:l+H5ErcW0PAehBNrBxoGv1jjNpGYdZ9RcheFkB2WI14=
@@ -529,19 +494,12 @@ github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
-github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
-github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
-github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
-github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/theupdateframework/go-tuf v0.7.0 h1:CqbQFrWo1ae3/I0UCblSbczevCCbS31Qvs5LdxRWqRI=
@@ -567,10 +525,10 @@ github.com/transparency-dev/formats v0.0.0-20251017110053-404c0d5b696c h1:5a2XDQ
github.com/transparency-dev/formats v0.0.0-20251017110053-404c0d5b696c/go.mod h1:g85IafeFJZLxlzZCDRu4JLpfS7HKzR+Hw9qRh3bVzDI=
github.com/transparency-dev/merkle v0.0.2 h1:Q9nBoQcZcgPamMkGn7ghV8XiTZ/kRxn1yCG81+twTK4=
github.com/transparency-dev/merkle v0.0.2/go.mod h1:pqSy+OXefQ1EDUVmAJ8MUhHB9TXGuzVAT58PqBoHz1A=
-github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
-github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
-github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
-github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
+github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
+github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
+github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
+github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/vbatts/tar-split v0.12.2 h1:w/Y6tjxpeiFMR47yzZPlPj/FcPLpXbTUi/9H7d3CPa4=
github.com/vbatts/tar-split v0.12.2/go.mod h1:eF6B6i6ftWQcDqEn3/iGFRFRo8cBIMSJVOpnNdfTMFA=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
@@ -583,8 +541,6 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
-go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
-go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
@@ -631,8 +587,6 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v4 v4.0.0-rc.4 h1:UP4+v6fFrBIb1l934bDl//mmnoIZEDK0idg1+AIvX5U=
go.yaml.in/yaml/v4 v4.0.0-rc.4/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
-golang.org/x/arch v0.24.0 h1:qlJ3M9upxvFfwRM51tTg3Yl+8CP9vCC1E7vlFpgv99Y=
-golang.org/x/arch v0.24.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
diff --git a/backend/internal/api/buildables_handler.go b/backend/internal/api/buildables_handler.go
deleted file mode 100644
index b9060db38..000000000
--- a/backend/internal/api/buildables_handler.go
+++ /dev/null
@@ -1,108 +0,0 @@
-//go:build buildables
-
-package api
-
-import (
- "errors"
- "net/http"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/buildables"
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
- "github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
- "github.com/getarcaneapp/arcane/types/auth"
- "github.com/getarcaneapp/arcane/types/base"
- "github.com/getarcaneapp/arcane/types/user"
- "github.com/gin-gonic/gin"
-)
-
-// SetupBuildablesRoutes registers buildable feature routes based on EnabledFeatures.
-func SetupBuildablesRoutes(apiGroup *gin.RouterGroup, authService *services.AuthService) {
- if buildables.HasBuildFeature("autologin") {
- registerAutoLoginRoutes(apiGroup, authService)
- }
-}
-
-func registerAutoLoginRoutes(apiGroup *gin.RouterGroup, authService *services.AuthService) {
- authGroup := apiGroup.Group("/auth")
-
- authGroup.GET("/auto-login-config", func(c *gin.Context) {
- if authService == nil {
- c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "service not available"})
- return
- }
-
- config, err := authService.GetAutoLoginConfig(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "failed to get auto-login config"})
- return
- }
-
- c.JSON(http.StatusOK, base.ApiResponse[auth.AutoLoginConfig]{
- Success: true,
- Data: *config,
- })
- })
-
- authGroup.POST("/auto-login", func(c *gin.Context) {
- if authService == nil {
- c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "service not available"})
- return
- }
-
- autoLoginConfig, err := authService.GetAutoLoginConfig(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "failed to get auto-login config"})
- return
- }
-
- if !autoLoginConfig.Enabled {
- c.JSON(http.StatusBadRequest, base.ErrorResponse{Error: "auto-login is not enabled"})
- return
- }
-
- password := authService.GetAutoLoginPassword()
- if password == "" {
- c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "auto-login password not configured"})
- return
- }
-
- userModel, tokenPair, err := authService.Login(c.Request.Context(), autoLoginConfig.Username, password)
- if err != nil {
- switch {
- case errors.Is(err, services.ErrInvalidCredentials):
- c.JSON(http.StatusUnauthorized, base.ErrorResponse{Error: (&common.InvalidCredentialsError{}).Error()})
- case errors.Is(err, services.ErrLocalAuthDisabled):
- c.JSON(http.StatusBadRequest, base.ErrorResponse{Error: (&common.LocalAuthDisabledError{}).Error()})
- default:
- c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: (&common.AuthFailedError{Err: err}).Error()})
- }
- return
- }
-
- var userResp user.User
- if mapErr := mapper.MapStruct(userModel, &userResp); mapErr != nil {
- c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: (&common.UserMappingError{Err: mapErr}).Error()})
- return
- }
-
- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
- if maxAge < 0 {
- maxAge = 0
- }
- maxAge += 60
-
- c.Header("Set-Cookie", cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken))
- c.JSON(http.StatusOK, base.ApiResponse[auth.LoginResponse]{
- Success: true,
- Data: auth.LoginResponse{
- Token: tokenPair.AccessToken,
- RefreshToken: tokenPair.RefreshToken,
- ExpiresAt: tokenPair.ExpiresAt,
- User: userResp,
- },
- })
- })
-}
diff --git a/backend/internal/api/diagnostics_handler.go b/backend/internal/api/diagnostics_handler.go
deleted file mode 100644
index a2348b71b..000000000
--- a/backend/internal/api/diagnostics_handler.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package api
-
-import (
- "net/http"
- "runtime"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- ws "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
- "github.com/gin-gonic/gin"
-)
-
-type DiagnosticsHandler struct {
- wsMetrics *WebSocketMetrics
-}
-
-func RegisterDiagnosticsRoutes(group *gin.RouterGroup, authMiddleware *middleware.AuthMiddleware, wsMetrics *WebSocketMetrics) {
- h := &DiagnosticsHandler{wsMetrics: wsMetrics}
-
- diagnostics := group.Group("/diagnostics")
- diagnostics.Use(authMiddleware.Add())
- {
- diagnostics.GET("/ws", h.WebSocketDiagnostics)
- }
-}
-
-func (h *DiagnosticsHandler) WebSocketDiagnostics(c *gin.Context) {
- isAdmin, _ := c.Get("userIsAdmin")
- if admin, ok := isAdmin.(bool); !ok || !admin {
- c.JSON(http.StatusForbidden, gin.H{"error": "Admin access required"})
- return
- }
-
- metrics := h.wsMetrics.Snapshot()
- connections := h.wsMetrics.Connections()
-
- c.JSON(http.StatusOK, gin.H{
- "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
- "goroutines": runtime.NumGoroutine(),
- "wsWorkerGoroutine": ws.CountWorkerGoroutines(),
- "gomaxprocs": runtime.GOMAXPROCS(0),
- "goVersion": runtime.Version(),
- "activeConnections": metrics,
- "connections": connections,
- })
-}
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index b77c642fd..5462b07a3 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -42,7 +42,7 @@ func Bootstrap(ctx context.Context) error {
}
cfg.DockerConfig = runtimeIdentityCfg.DockerConfig
- SetupGinLogger(cfg)
+ SetupSlogLogger(cfg)
ConfigureGormLogger(cfg)
slog.InfoContext(ctx, "Arcane is starting", "version", config.Version)
diff --git a/backend/internal/bootstrap/buildables_router_bootstrap.go b/backend/internal/bootstrap/buildables_router_bootstrap.go
index 51942c7c2..a1d338052 100644
--- a/backend/internal/bootstrap/buildables_router_bootstrap.go
+++ b/backend/internal/bootstrap/buildables_router_bootstrap.go
@@ -3,12 +3,12 @@
package bootstrap
import (
- "github.com/getarcaneapp/arcane/backend/internal/api"
- "github.com/gin-gonic/gin"
+ "github.com/getarcaneapp/arcane/backend/api"
+ "github.com/labstack/echo/v4"
)
func init() {
- registerBuildableRoutes = append(registerBuildableRoutes, func(apiGroup *gin.RouterGroup, svc *Services) {
+ registerBuildableRoutes = append(registerBuildableRoutes, func(apiGroup *echo.Group, svc *Services) {
api.SetupBuildablesRoutes(apiGroup, svc.Auth)
})
}
diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.go
index e34d43392..8d85672b8 100644
--- a/backend/internal/bootstrap/edge_bootstrap.go
+++ b/backend/internal/bootstrap/edge_bootstrap.go
@@ -11,7 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
)
// registerEdgeTunnelRoutes configures the manager-side edge tunnel server.
@@ -20,7 +20,7 @@ import (
func registerEdgeTunnelRoutes(
ctx context.Context,
cfg *config.Config,
- apiGroup *gin.RouterGroup,
+ apiGroup *echo.Group,
appServices *Services,
) *edge.TunnelServer {
// Resolver that validates API key and returns the environment ID
@@ -133,8 +133,8 @@ func registerEdgeTunnelRoutes(
// Rate-limit agent mTLS enrollment per-IP. Enrollment is authenticated
// only by the agent token, so we cap bursts to mitigate brute-force or
// token-abuse attempts without impacting normal agent lifecycles.
- apiGroup.POST("/tunnel/mtls/enroll", middleware.PerIPRateLimit(10, 3), middleware.PerAgentTokenRateLimit(10, 3), server.HandleMTLSEnroll)
- apiGroup.GET("/tunnel/connect", middleware.PerIPRateLimit(60, 30), middleware.PerAgentTokenRateLimit(10, 3), server.HandleConnect)
+ apiGroup.POST("/tunnel/mtls/enroll", server.HandleMTLSEnroll, middleware.PerIPRateLimit(10, 3), middleware.PerAgentTokenRateLimit(10, 3))
+ apiGroup.GET("/tunnel/connect", server.HandleConnect, middleware.PerIPRateLimit(60, 30), middleware.PerAgentTokenRateLimit(10, 3))
slog.InfoContext(ctx, "Configured edge tunnel server",
"poll_enabled", true,
"grpc_enabled", !cfg.AgentMode,
diff --git a/backend/internal/bootstrap/logger_bootstrap.go b/backend/internal/bootstrap/logger_bootstrap.go
index 7aa71cea4..bca888c75 100644
--- a/backend/internal/bootstrap/logger_bootstrap.go
+++ b/backend/internal/bootstrap/logger_bootstrap.go
@@ -16,7 +16,8 @@ import (
)
// timeFilterHandler wraps a slog.Handler and removes redundant time attributes
-// from grouped attributes (like request.time and response.time from slog-gin)
+// from grouped attributes (like request.time and response.time emitted by HTTP
+// request loggers such as slog-echo).
type timeFilterHandler struct {
handler slog.Handler
}
@@ -116,7 +117,7 @@ func (h *attrFilterHandler) WithGroup(name string) slog.Handler {
return &attrFilterHandler{handler: h.handler.WithGroup(name), dropKeys: h.dropKeys}
}
-func SetupGinLogger(cfg *config.Config) {
+func SetupSlogLogger(cfg *config.Config) {
var lvl slog.Level
switch strings.ToLower(cfg.LogLevel) {
case "debug":
@@ -142,7 +143,7 @@ func SetupGinLogger(cfg *config.Config) {
})
}
- // Wrap with timeFilterHandler to remove redundant time attributes from slog-gin
+ // Wrap with timeFilterHandler to remove redundant time attributes from slog-echo
h = &timeFilterHandler{handler: h}
slog.SetDefault(slog.New(h))
diff --git a/backend/internal/bootstrap/playwright_router_bootstrap.go b/backend/internal/bootstrap/playwright_router_bootstrap.go
index e90abe94d..57629c65b 100644
--- a/backend/internal/bootstrap/playwright_router_bootstrap.go
+++ b/backend/internal/bootstrap/playwright_router_bootstrap.go
@@ -5,14 +5,14 @@ package bootstrap
import (
"log/slog"
- "github.com/getarcaneapp/arcane/backend/internal/api"
+ "github.com/getarcaneapp/arcane/backend/api"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
)
func init() {
- registerPlaywrightRoutes = []func(apiGroup *gin.RouterGroup, services *Services){
- func(apiGroup *gin.RouterGroup, svc *Services) {
+ registerPlaywrightRoutes = []func(apiGroup *echo.Group, services *Services){
+ func(apiGroup *echo.Group, svc *Services) {
playwrightService := services.NewPlaywrightService(svc.ApiKey, svc.User)
if playwrightService == nil {
slog.Warn("Playwright service not available, skipping playwright routes")
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index d6d22c55d..5074f9ae5 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -6,14 +6,14 @@ import (
"path"
"strings"
- "github.com/gin-gonic/gin"
- sloggin "github.com/samber/slog-gin"
+ "github.com/labstack/echo/v4"
+ echomiddleware "github.com/labstack/echo/v4/middleware"
+ slogecho "github.com/samber/slog-echo"
+ "github.com/getarcaneapp/arcane/backend/api"
+ "github.com/getarcaneapp/arcane/backend/api/ws"
"github.com/getarcaneapp/arcane/backend/frontend"
- "github.com/getarcaneapp/arcane/backend/internal/api"
"github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/getarcaneapp/arcane/backend/internal/huma"
- "github.com/getarcaneapp/arcane/backend/internal/huma/handlers"
"github.com/getarcaneapp/arcane/backend/internal/middleware"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
@@ -21,8 +21,8 @@ import (
)
var (
- registerPlaywrightRoutes []func(apiGroup *gin.RouterGroup, services *Services)
- registerBuildableRoutes []func(apiGroup *gin.RouterGroup, services *Services)
+ registerPlaywrightRoutes []func(apiGroup *echo.Group, services *Services)
+ registerBuildableRoutes []func(apiGroup *echo.Group, services *Services)
)
var loggerSkipPatterns = []string{
@@ -40,8 +40,8 @@ var loggerSkipPatterns = []string{
"HEAD /api/health",
}
-func shouldLogRequest(c *gin.Context) bool {
- mp := c.Request.Method + " " + c.Request.URL.Path
+func shouldLogRequestInternal(c echo.Context) bool {
+ mp := c.Request().Method + " " + c.Request().URL.Path
for _, pat := range loggerSkipPatterns {
if pat == mp {
return false
@@ -61,24 +61,28 @@ func shouldLogRequest(c *gin.Context) bool {
return true
}
-func requestLoggerMiddlewareInternal() gin.HandlerFunc {
- loggerMiddleware := sloggin.NewWithConfig(slog.Default(), sloggin.Config{
- Filters: []sloggin.Filter{shouldLogRequest},
+// requestLoggerMiddlewareInternal wraps slog-echo and filters out internal
+// edge tunnel requests plus high-volume endpoints (health, WS, static).
+func requestLoggerMiddlewareInternal() echo.MiddlewareFunc {
+ loggerMiddleware := slogecho.NewWithConfig(slog.Default(), slogecho.Config{
+ Filters: []slogecho.Filter{shouldLogRequestInternal},
})
- return func(c *gin.Context) {
- if edge.IsInternalTunnelRequest(c.Request.Context()) {
- c.Next()
- return
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ if edge.IsInternalTunnelRequest(c.Request().Context()) {
+ return next(c)
+ }
+ return loggerMiddleware(next)(c)
}
- loggerMiddleware(c)
}
}
-func createAuthValidator(appServices *Services) middleware.AuthValidator {
- return func(ctx context.Context, c *gin.Context) bool {
+func createAuthValidatorInternal(appServices *Services) middleware.AuthValidator {
+ return func(ctx context.Context, c echo.Context) bool {
+ req := c.Request()
// Check for API key authentication
- if apiKey := c.GetHeader("X-API-Key"); apiKey != "" {
+ if apiKey := req.Header.Get("X-API-Key"); apiKey != "" {
// User-owned API key
if user, err := appServices.ApiKey.ValidateApiKey(ctx, apiKey); err == nil && user != nil {
return true
@@ -93,9 +97,9 @@ func createAuthValidator(appServices *Services) middleware.AuthValidator {
// Check for Bearer token authentication
token := ""
- if auth := c.GetHeader("Authorization"); strings.HasPrefix(auth, "Bearer ") {
+ if auth := req.Header.Get("Authorization"); strings.HasPrefix(auth, "Bearer ") {
token = strings.TrimPrefix(auth, "Bearer ")
- } else if cookieToken, err := cookie.GetTokenCookie(c); err == nil && cookieToken != "" {
+ } else if cookieToken, err := cookie.GetTokenCookie(req); err == nil && cookieToken != "" {
token = cookieToken
}
@@ -108,24 +112,20 @@ func createAuthValidator(appServices *Services) middleware.AuthValidator {
}
}
-func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services) (*gin.Engine, *edge.TunnelServer) {
- if cfg.Environment == "production" {
- gin.SetMode(gin.ReleaseMode)
- } else {
- gin.SetMode(gin.DebugMode)
- }
- router := gin.New()
- router.Use(gin.Recovery())
+func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services) (*echo.Echo, *edge.TunnelServer) {
+ e := echo.New()
+ e.HideBanner = true
+ e.HidePort = true
- router.Use(requestLoggerMiddlewareInternal()) //nolint:contextcheck
+ e.Use(echomiddleware.Recover())
+ e.Use(requestLoggerMiddlewareInternal()) //nolint:contextcheck
authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).
WithApiKeyValidator(appServices.ApiKey).
WithEnvironmentAccessTokenResolver(appServices.Environment)
- corsMiddleware := middleware.NewCORSMiddleware(cfg).Add()
- router.Use(corsMiddleware)
+ e.Use(middleware.NewCORSMiddleware(cfg).Add())
- apiGroup := router.Group("/api")
+ apiGroup := e.Group("/api")
tunnelRegistry := edge.NewTunnelRegistry()
edge.SetDefaultRegistry(tunnelRegistry)
envResolver := func(ctx context.Context, id string) (string, *string, bool, error) {
@@ -137,17 +137,18 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
}
// Register public webhook trigger endpoint before auth middleware (token in URL is the sole auth)
- handlers.RegisterWebhookTrigger(apiGroup, appServices.Webhook) //nolint:contextcheck
+ api.RegisterWebhookTrigger(apiGroup, appServices.Webhook) //nolint:contextcheck
+ //nolint:contextcheck // Echo middleware reads context from echo.Context.Request().Context(), not a parameter.
envProxyMiddleware := middleware.NewEnvProxyMiddlewareWithParam(
types.LOCAL_DOCKER_ENVIRONMENT_ID,
"id",
envResolver,
- createAuthValidator(appServices),
+ createAuthValidatorInternal(appServices),
)
apiGroup.Use(envProxyMiddleware)
- humaServices := &huma.Services{
+ humaServices := &api.Services{
User: appServices.User,
Auth: appServices.Auth,
Oidc: appServices.Oidc,
@@ -187,16 +188,16 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
Config: cfg,
}
- _ = huma.SetupAPI(router, apiGroup, cfg, humaServices)
+ _ = api.SetupAPI(e, apiGroup, cfg, humaServices)
for _, register := range registerBuildableRoutes {
register(apiGroup, appServices)
}
- api.RegisterDiagnosticsRoutes(apiGroup, authMiddleware, api.DefaultWebSocketMetrics()) //nolint:contextcheck
+ api.RegisterDiagnosticsRoutes(apiGroup, authMiddleware, ws.DefaultWebSocketMetrics()) //nolint:contextcheck
- // Remaining Gin handlers (WebSocket/streaming)
- api.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.Swarm, appServices.System, authMiddleware, cfg) //nolint:contextcheck
+ // Remaining echo handlers (WebSocket/streaming)
+ ws.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.Swarm, appServices.System, authMiddleware, cfg) //nolint:contextcheck
// Register edge tunnel endpoint for manager to accept agent connections
// This is only registered when NOT in agent mode (i.e., running as manager)
@@ -211,9 +212,9 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
}
}
- if err := frontend.RegisterFrontend(router); err != nil {
- _, _ = gin.DefaultErrorWriter.Write([]byte("Failed to register frontend: " + err.Error() + "\n"))
+ if err := frontend.RegisterFrontend(e); err != nil {
+ slog.Error("Failed to register frontend", "error", err)
}
- return router, tunnelServer
+ return e, tunnelServer
}
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index 06455a37c..a314e4f76 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -12,14 +12,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/services"
pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
- "github.com/gin-gonic/gin"
-)
-
-const (
- headerAgentBootstrap = "X-Arcane-Agent-Bootstrap"
- headerAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
- headerApiKey = "X-API-Key" // #nosec G101: header name, not a credential
- agentPairingPrefix = "/api/environments/0/agent/pair"
+ "github.com/labstack/echo/v4"
)
type AuthOptions struct {
@@ -69,150 +62,135 @@ func (m *AuthMiddleware) WithAdminNotRequired() *AuthMiddleware {
return &clone
}
-func (m *AuthMiddleware) Add() gin.HandlerFunc {
- return func(c *gin.Context) {
- reqCtx := c.Request.Context()
- if m.cfg != nil && m.cfg.AgentMode {
- m.agentAuth(reqCtx, c)
- return
+func (m *AuthMiddleware) Add() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ reqCtx := c.Request().Context()
+ if m.cfg != nil && m.cfg.AgentMode {
+ return m.agentAuth(reqCtx, c, next)
+ }
+ return m.managerAuth(reqCtx, c, next)
}
- m.managerAuth(reqCtx, c)
}
}
-func (m *AuthMiddleware) agentAuth(ctx context.Context, c *gin.Context) {
- if isPreflight(c) {
- c.Next()
- return
+func (m *AuthMiddleware) agentAuth(ctx context.Context, c echo.Context, next echo.HandlerFunc) error {
+ if isPreflightInternal(c) {
+ return next(c)
}
- if strings.HasPrefix(c.Request.URL.Path, agentPairingPrefix) &&
+ req := c.Request()
+ if strings.HasPrefix(req.URL.Path, pkgutils.AgentPairingPrefix) &&
m.cfg.AgentToken != "" &&
- c.GetHeader(headerAgentBootstrap) == m.cfg.AgentToken {
- slog.InfoContext(ctx, "Agent auth: bootstrap pairing accepted", "path", c.Request.URL.Path, "method", c.Request.Method)
- agentSudo(c)
- return
+ req.Header.Get(pkgutils.HeaderAgentBootstrap) == m.cfg.AgentToken {
+ slog.InfoContext(ctx, "Agent auth: bootstrap pairing accepted", "path", req.URL.Path, "method", req.Method)
+ agentSudoInternal(c)
+ return next(c)
}
- if tok := c.GetHeader(headerAgentToken); tok != "" && m.cfg.AgentToken != "" && tok == m.cfg.AgentToken {
- agentSudo(c)
- return
+ if tok := req.Header.Get(pkgutils.HeaderAgentToken); tok != "" && m.cfg.AgentToken != "" && tok == m.cfg.AgentToken {
+ agentSudoInternal(c)
+ return next(c)
}
// Check for API key as agent token
- if tok := c.GetHeader(headerApiKey); tok != "" && m.cfg.AgentToken != "" && tok == m.cfg.AgentToken {
- agentSudo(c)
- return
+ if tok := req.Header.Get(pkgutils.HeaderApiKey); tok != "" && m.cfg.AgentToken != "" && tok == m.cfg.AgentToken {
+ agentSudoInternal(c)
+ return next(c)
}
slog.WarnContext(ctx, "Agent auth forbidden",
- "path", c.Request.URL.Path,
- "method", c.Request.Method,
- "has_agent_token_hdr", c.GetHeader(headerAgentToken) != "",
+ "path", req.URL.Path,
+ "method", req.Method,
+ "has_agent_token_hdr", req.Header.Get(pkgutils.HeaderAgentToken) != "",
"agent_token_config_set", m.cfg.AgentToken != "",
)
- c.JSON(http.StatusForbidden, models.APIError{
+ return c.JSON(http.StatusForbidden, models.APIError{
Code: "FORBIDDEN",
Message: "Invalid or missing agent token",
})
- c.Abort()
}
-func (m *AuthMiddleware) managerAuth(ctx context.Context, c *gin.Context) {
- if agentToken := c.GetHeader(headerAgentToken); agentToken != "" {
+func (m *AuthMiddleware) managerAuth(ctx context.Context, c echo.Context, next echo.HandlerFunc) error {
+ req := c.Request()
+ if agentToken := req.Header.Get(pkgutils.HeaderAgentToken); agentToken != "" {
if env, ok := m.resolveEnvironmentAccessToken(ctx, agentToken); ok {
- environmentSudo(c, env)
- return
+ environmentSudoInternal(c, env)
+ return next(c)
}
}
// First, check for API key in X-API-Key header
- if apiKey := c.GetHeader(headerApiKey); apiKey != "" {
+ if apiKey := req.Header.Get(pkgutils.HeaderApiKey); apiKey != "" {
if m.apiKeyValidator != nil {
user, err := m.apiKeyValidator.ValidateApiKey(ctx, apiKey)
if err == nil && user != nil {
isAdmin := pkgutils.UserHasRole(user.Roles, "admin")
if m.options.AdminRequired && !isAdmin {
- c.JSON(http.StatusForbidden, models.APIError{
+ return c.JSON(http.StatusForbidden, models.APIError{
Code: "FORBIDDEN",
Message: "You don't have permission to access this resource",
})
- c.Abort()
- return
}
c.Set("userID", user.ID)
c.Set("currentUser", user)
c.Set("userIsAdmin", isAdmin)
c.Set("authMethod", "api_key")
- c.Next()
- return
+ return next(c)
}
}
if env, ok := m.resolveEnvironmentAccessToken(ctx, apiKey); ok {
- environmentSudo(c, env)
- return
+ environmentSudoInternal(c, env)
+ return next(c)
}
- // If API key validation fails, return unauthorized
- c.JSON(http.StatusUnauthorized, models.APIError{
+ return c.JSON(http.StatusUnauthorized, models.APIError{
Code: models.APIErrorCodeUnauthorized,
Message: "Invalid or expired API key",
})
- c.Abort()
- return
}
- token := extractBearerOrCookieToken(c)
+ token := extractBearerOrCookieTokenInternal(c)
if token == "" {
if m.options.SuccessOptional {
- c.Next()
- return
+ return next(c)
}
- c.JSON(http.StatusUnauthorized, models.APIError{
+ return c.JSON(http.StatusUnauthorized, models.APIError{
Code: models.APIErrorCodeUnauthorized,
Message: "Authentication required",
})
- c.Abort()
- return
}
user, err := m.authService.VerifyToken(ctx, token)
if err != nil {
if errors.Is(err, services.ErrTokenVersionMismatch) {
- cookie.ClearTokenCookie(c)
- c.JSON(http.StatusUnauthorized, models.APIError{
+ cookie.ClearTokenCookie(c.Response().Writer, req)
+ return c.JSON(http.StatusUnauthorized, models.APIError{
Code: models.APIErrorCodeUnauthorized,
Message: "Application has been updated. Please log in again.",
})
- c.Abort()
- return
}
if m.options.SuccessOptional {
- c.Next()
- return
+ return next(c)
}
- c.JSON(http.StatusUnauthorized, models.APIError{
+ return c.JSON(http.StatusUnauthorized, models.APIError{
Code: models.APIErrorCodeUnauthorized,
Message: "Invalid or expired token",
})
- c.Abort()
- return
}
isAdmin := pkgutils.UserHasRole(user.Roles, "admin")
if m.options.AdminRequired && !isAdmin {
- c.JSON(http.StatusForbidden, models.APIError{
+ return c.JSON(http.StatusForbidden, models.APIError{
Code: "FORBIDDEN",
Message: "You don't have permission to access this resource",
})
- c.Abort()
- return
}
c.Set("userID", user.ID)
c.Set("currentUser", user)
c.Set("userIsAdmin", isAdmin)
- c.Next()
+ return next(c)
}
func (m *AuthMiddleware) resolveEnvironmentAccessToken(ctx context.Context, token string) (*models.Environment, bool) {
@@ -228,11 +206,11 @@ func (m *AuthMiddleware) resolveEnvironmentAccessToken(ctx context.Context, toke
return env, true
}
-func isPreflight(c *gin.Context) bool {
- return c.Request.Method == http.MethodOptions
+func isPreflightInternal(c echo.Context) bool {
+ return c.Request().Method == http.MethodOptions
}
-func agentSudo(c *gin.Context) {
+func agentSudoInternal(c echo.Context) {
agentUser := &models.User{
BaseModel: models.BaseModel{ID: "agent"},
Email: new("[email protected]"),
@@ -243,10 +221,9 @@ func agentSudo(c *gin.Context) {
c.Set("currentUser", agentUser)
c.Set("userIsAdmin", true)
c.Set("authMethod", "agent_token")
- c.Next()
}
-func environmentSudo(c *gin.Context, env *models.Environment) {
+func environmentSudoInternal(c echo.Context, env *models.Environment) {
envUser := &models.User{
BaseModel: models.BaseModel{ID: "environment:" + env.ID},
Username: env.Name,
@@ -256,15 +233,15 @@ func environmentSudo(c *gin.Context, env *models.Environment) {
c.Set("currentUser", envUser)
c.Set("userIsAdmin", true)
c.Set("authMethod", "environment_access_token")
- c.Next()
}
-func extractBearerOrCookieToken(c *gin.Context) string {
- authHeader := c.GetHeader("Authorization")
+func extractBearerOrCookieTokenInternal(c echo.Context) string {
+ req := c.Request()
+ authHeader := req.Header.Get("Authorization")
if after, ok := strings.CutPrefix(authHeader, "Bearer "); ok {
return after
}
- if tok, err := cookie.GetTokenCookie(c); err == nil && tok != "" {
+ if tok, err := cookie.GetTokenCookie(req); err == nil && tok != "" {
return tok
}
return ""
diff --git a/backend/internal/middleware/auth_middleware_test.go b/backend/internal/middleware/auth_middleware_test.go
index 5509e9409..3932ace73 100644
--- a/backend/internal/middleware/auth_middleware_test.go
+++ b/backend/internal/middleware/auth_middleware_test.go
@@ -8,7 +8,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
)
@@ -26,10 +26,8 @@ func (r testEnvironmentTokenResolver) ResolveEnvironmentByAccessToken(_ context.
var ErrInvalidEnvironmentAccessTokenForTest = context.Canceled
func TestAuthMiddleware_ManagerAuthAcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
token := "env-access-token"
- router := gin.New()
+ router := echo.New()
router.Use(
NewAuthMiddleware(nil, &config.Config{}).
WithEnvironmentAccessTokenResolver(testEnvironmentTokenResolver{
@@ -41,17 +39,17 @@ func TestAuthMiddleware_ManagerAuthAcceptsEnvironmentAccessTokenViaAPIKey(t *tes
}).
Add(),
)
- router.GET("/secure", func(c *gin.Context) {
- currentUser, exists := c.Get("currentUser")
- require.True(t, exists)
+ router.GET("/secure", func(c echo.Context) error {
+ currentUser := c.Get("currentUser")
+ require.NotNil(t, currentUser)
user, ok := currentUser.(*models.User)
require.True(t, ok)
require.Equal(t, "environment:env-self", user.ID)
require.Equal(t, "Self Target", user.Username)
- require.Equal(t, "environment_access_token", c.GetString("authMethod"))
+ require.Equal(t, "environment_access_token", c.Get("authMethod"))
- c.JSON(http.StatusOK, gin.H{"userId": user.ID})
+ return c.JSON(http.StatusOK, map[string]any{"userId": user.ID})
})
req := httptest.NewRequest(http.MethodGet, "/secure", nil)
diff --git a/backend/internal/middleware/cors_middleware.go b/backend/internal/middleware/cors_middleware.go
index 225157bd9..f79fc9001 100644
--- a/backend/internal/middleware/cors_middleware.go
+++ b/backend/internal/middleware/cors_middleware.go
@@ -6,8 +6,8 @@ import (
"strings"
"github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/gin-contrib/cors"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
+ echomiddleware "github.com/labstack/echo/v4/middleware"
)
type CORSMiddleware struct {
@@ -19,49 +19,48 @@ func NewCORSMiddleware(cfg *config.Config) *CORSMiddleware {
return &CORSMiddleware{cfg: cfg}
}
-func (m *CORSMiddleware) Add() gin.HandlerFunc {
+func (m *CORSMiddleware) Add() echo.MiddlewareFunc {
// Edge Agent mode: skip CORS entirely. The agent only receives server-to-server
// requests through the edge tunnel from the manager — never from browsers.
- // CORS has no purpose here and actively causes 403 rejections when the
- // manager forwards browser Origin headers through the tunnel.
if m.cfg != nil && m.cfg.EdgeAgent {
- return func(c *gin.Context) { c.Next() }
- }
-
- conf := cors.DefaultConfig()
- conf.AllowOrigins = deriveAllowedOrigins(m.cfg, m.customOrigins)
- conf.AllowCredentials = true
- conf.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"}
- conf.AllowHeaders = []string{
- "Authorization",
- "Content-Type",
- "X-CSRF-Token",
- "X-Requested-With",
- "Accept",
- "Accept-Language",
- "Accept-Encoding",
- "User-Agent",
- "Cache-Control",
- "Origin",
- "Referer",
- "X-Arcane-Agent-Token",
- "X-API-Key",
- }
- conf.ExposeHeaders = []string{
- "Content-Length",
- "Content-Type",
- "X-Total-Count",
- "X-Page",
- "X-Per-Page",
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error { return next(c) }
+ }
}
- conf.MaxAge = 300
- return cors.New(conf)
+ return echomiddleware.CORSWithConfig(echomiddleware.CORSConfig{
+ AllowOrigins: deriveAllowedOriginsInternal(m.cfg, m.customOrigins),
+ AllowCredentials: true,
+ AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"},
+ AllowHeaders: []string{
+ "Authorization",
+ "Content-Type",
+ "X-CSRF-Token",
+ "X-Requested-With",
+ "Accept",
+ "Accept-Language",
+ "Accept-Encoding",
+ "User-Agent",
+ "Cache-Control",
+ "Origin",
+ "Referer",
+ "X-Arcane-Agent-Token",
+ "X-API-Key",
+ },
+ ExposeHeaders: []string{
+ "Content-Length",
+ "Content-Type",
+ "X-Total-Count",
+ "X-Page",
+ "X-Per-Page",
+ },
+ MaxAge: 300,
+ })
}
-func deriveAllowedOrigins(cfg *config.Config, custom []string) []string {
+func deriveAllowedOriginsInternal(cfg *config.Config, custom []string) []string {
if len(custom) > 0 {
- return dedupe(custom)
+ return dedupeInternal(custom)
}
var origins []string
@@ -86,21 +85,20 @@ func deriveAllowedOrigins(cfg *config.Config, custom []string) []string {
)
}
- origins = dedupe(origins)
+ origins = dedupeInternal(origins)
if len(origins) == 0 {
if cfg != nil && cfg.Environment == "production" {
slog.Warn("CORS: No origins specified for production - defaulting to https://localhost")
return []string{"https://localhost"}
}
- // Fallback in dev (avoid "*" with credentials=true)
return []string{"http://localhost:3000"}
}
return origins
}
-func dedupe(in []string) []string {
+func dedupeInternal(in []string) []string {
seen := make(map[string]struct{}, len(in))
out := make([]string, 0, len(in))
for _, v := range in {
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index 18064fbd8..1501fb1e8 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -13,8 +13,8 @@ import (
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
wsutil "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
- "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
)
const (
@@ -52,7 +52,7 @@ type EnvResolver func(ctx context.Context, id string) (string, *string, bool, er
// AuthValidator validates authentication for a request.
// Returns true if the request is authenticated, false otherwise.
-type AuthValidator func(ctx context.Context, c *gin.Context) bool
+type AuthValidator func(ctx context.Context, c echo.Context) bool
// EnvironmentMiddleware proxies requests for remote environments to their respective agents.
type EnvironmentMiddleware struct {
@@ -65,12 +65,7 @@ type EnvironmentMiddleware struct {
}
// NewEnvProxyMiddlewareWithParam creates middleware that proxies requests to remote environments.
-// - localID: the ID representing the local environment (requests to this ID are not proxied)
-// - paramName: the URL parameter name containing the environment ID (e.g., "id")
-// - resolver: function to resolve environment ID to connection details
-// - envService: environment service for additional lookups
-// - authValidator: function to validate authentication before proxying (required for security)
-func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, authValidator AuthValidator) gin.HandlerFunc {
+func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, authValidator AuthValidator) echo.MiddlewareFunc {
return NewEnvProxyMiddlewareWithParamAndRegistry(localID, paramName, resolver, authValidator, edge.GetRegistry())
}
@@ -81,7 +76,7 @@ func NewEnvProxyMiddlewareWithParamAndRegistry(
resolver EnvResolver,
authValidator AuthValidator,
registry *edge.TunnelRegistry,
-) gin.HandlerFunc {
+) echo.MiddlewareFunc {
if registry == nil {
registry = edge.NewTunnelRegistry()
}
@@ -94,135 +89,113 @@ func NewEnvProxyMiddlewareWithParamAndRegistry(
httpClient: &http.Client{Timeout: proxyTimeout},
registry: registry,
}
- return m.Handle
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ return m.Handle(c, next)
+ }
+ }
}
// Handle is the main middleware handler.
-func (m *EnvironmentMiddleware) Handle(c *gin.Context) {
+func (m *EnvironmentMiddleware) Handle(c echo.Context, next echo.HandlerFunc) error {
envID := m.extractEnvironmentID(c)
- // Local environment or no environment - continue to next handler
if envID == "" || envID == m.localID {
- c.Next()
- return
+ return next(c)
}
- // Only proxy requests with additional path segments after the environment ID
- // Examples: /api/environments/{id}/containers, /api/environments/{id}/projects
- // Not proxied: /api/environments/{id} (management operations)
if !m.hasResourcePath(c, envID) {
- c.Next()
- return
+ return next(c)
}
// SECURITY: Validate authentication BEFORE proxying to remote environments.
- // The proxy attaches the agent token to forwarded requests, which grants full access
- // on the remote agent. Without this check, unauthenticated users could access
- // remote environment resources.
- if m.authValidator != nil && !m.authValidator(c.Request.Context(), c) {
- c.JSON(http.StatusUnauthorized, gin.H{
+ if m.authValidator != nil && !m.authValidator(c.Request().Context(), c) {
+ return c.JSON(http.StatusUnauthorized, map[string]any{
"success": false,
- "data": gin.H{"error": errUnauthorized},
+ "data": map[string]any{"error": errUnauthorized},
})
- c.Abort()
- return
}
- // Resolve remote environment
- apiURL, accessToken, enabled, err := m.resolver(c.Request.Context(), envID)
+ apiURL, accessToken, enabled, err := m.resolver(c.Request().Context(), envID)
if err != nil || apiURL == "" {
- c.JSON(http.StatusNotFound, gin.H{
+ return c.JSON(http.StatusNotFound, map[string]any{
"success": false,
- "data": gin.H{"error": errEnvironmentNotFound},
+ "data": map[string]any{"error": errEnvironmentNotFound},
})
- c.Abort()
- return
}
if !enabled {
- c.JSON(http.StatusBadRequest, gin.H{
+ return c.JSON(http.StatusBadRequest, map[string]any{
"success": false,
- "data": gin.H{"error": errEnvironmentDisabled},
+ "data": map[string]any{"error": errEnvironmentDisabled},
})
- c.Abort()
- return
}
isEdgeEnvironment := isEdgeEnvironmentURLInternal(apiURL)
- if m.proxyActiveEdgeTunnelInternal(c, envID, accessToken) {
- return
+ if handled, err := m.proxyActiveEdgeTunnelInternal(c, envID, accessToken); handled {
+ return err
}
if isEdgeEnvironment {
- if m.proxyRecoveredEdgeTunnelInternal(c, envID, accessToken) {
- return
+ if handled, err := m.proxyRecoveredEdgeTunnelInternal(c, envID, accessToken); handled {
+ return err
}
- slog.WarnContext(c.Request.Context(), "No active edge tunnel for environment", "environment_id", envID)
- m.abortEdgeTunnelUnavailable(c)
- return
+ slog.WarnContext(c.Request().Context(), "No active edge tunnel for environment", "environment_id", envID)
+ return m.abortEdgeTunnelUnavailable(c)
}
target := m.buildTargetURL(c, envID, apiURL)
if m.isWebSocketUpgrade(c) {
- m.proxyWebSocket(c, target, accessToken, envID)
- } else {
- m.proxyHTTP(c, target, accessToken)
+ return m.proxyWebSocket(c, target, accessToken, envID)
}
+ return m.proxyHTTP(c, target, accessToken)
}
-func (m *EnvironmentMiddleware) proxyActiveEdgeTunnelInternal(c *gin.Context, envID string, accessToken *string) bool {
+func (m *EnvironmentMiddleware) proxyActiveEdgeTunnelInternal(c echo.Context, envID string, accessToken *string) (bool, error) {
tunnel, ok := m.getActiveEdgeTunnelInternal(envID)
if !ok {
- return false
+ return false, nil
}
- slog.DebugContext(c.Request.Context(), "Routing request through edge tunnel", "environment_id", envID, "path", c.Request.URL.Path)
+ slog.DebugContext(c.Request().Context(), "Routing request through edge tunnel", "environment_id", envID, "path", c.Request().URL.Path)
m.setProxyContextHeadersInternal(c, accessToken)
- m.proxyThroughTunnelInternal(c, tunnel, envID)
- return true
+ return true, m.proxyThroughTunnelInternal(c, tunnel, envID)
}
-func (m *EnvironmentMiddleware) proxyRecoveredEdgeTunnelInternal(c *gin.Context, envID string, accessToken *string) bool {
+func (m *EnvironmentMiddleware) proxyRecoveredEdgeTunnelInternal(c echo.Context, envID string, accessToken *string) (bool, error) {
edge.TouchTunnelDemand(envID, edge.DefaultTunnelDemandTTL)
- tunnel, ok := m.waitForActiveEdgeTunnelInternal(c.Request.Context(), envID, edge.DefaultTunnelAcquireTimeout())
+ tunnel, ok := m.waitForActiveEdgeTunnelInternal(c.Request().Context(), envID, edge.DefaultTunnelAcquireTimeout())
if !ok {
- return false
+ return false, nil
}
- slog.InfoContext(c.Request.Context(), "Recovered edge tunnel during request", "environment_id", envID)
+ slog.InfoContext(c.Request().Context(), "Recovered edge tunnel during request", "environment_id", envID)
m.setProxyContextHeadersInternal(c, accessToken)
- m.proxyThroughTunnelInternal(c, tunnel, envID)
- return true
+ return true, m.proxyThroughTunnelInternal(c, tunnel, envID)
}
-func (m *EnvironmentMiddleware) setProxyContextHeadersInternal(c *gin.Context, accessToken *string) {
- // ProxyHTTPRequest and ProxyWebSocketRequest copy headers from c.Request.Header,
- // so setting these here ensures the agent receives proper authentication.
+func (m *EnvironmentMiddleware) setProxyContextHeadersInternal(c echo.Context, accessToken *string) {
if accessToken != nil && *accessToken != "" {
- c.Request.Header.Set(edge.HeaderAgentToken, *accessToken)
- c.Request.Header.Set(edge.HeaderAPIKey, *accessToken)
+ c.Request().Header.Set(edge.HeaderAgentToken, *accessToken)
+ c.Request().Header.Set(edge.HeaderAPIKey, *accessToken)
}
}
-func (m *EnvironmentMiddleware) proxyThroughTunnelInternal(c *gin.Context, tunnel *edge.AgentTunnel, envID string) {
+func (m *EnvironmentMiddleware) proxyThroughTunnelInternal(c echo.Context, tunnel *edge.AgentTunnel, envID string) error {
proxyPath := m.buildProxyPath(c, envID)
if m.isWebSocketUpgrade(c) {
- edge.ProxyWebSocketRequest(c, tunnel, proxyPath)
- } else {
- edge.ProxyHTTPRequest(c, tunnel, proxyPath)
+ return edge.ProxyWebSocketRequest(c, tunnel, proxyPath)
}
- c.Abort()
+ return edge.ProxyHTTPRequest(c, tunnel, proxyPath)
}
// hasResourcePath reports whether the request targets a proxiable resource path.
-// Returns true for paths like /api/environments/{id}/containers (should be proxied).
-// Returns false for /api/environments/{id} exactly or any management endpoint.
-func (m *EnvironmentMiddleware) hasResourcePath(c *gin.Context, envID string) bool {
- suffix, ok := strings.CutPrefix(c.Request.URL.Path, apiEnvironmentsPrefix+envID)
+func (m *EnvironmentMiddleware) hasResourcePath(c echo.Context, envID string) bool {
+ suffix, ok := strings.CutPrefix(c.Request().URL.Path, apiEnvironmentsPrefix+envID)
if !ok || len(suffix) <= 1 || suffix[0] != '/' {
return false
}
@@ -243,21 +216,17 @@ func isManagementPathInternal(suffix string) bool {
}
// extractEnvironmentID gets the environment ID from the request.
-// Only processes paths containing "/environments/" to avoid conflicts with other routes.
-func (m *EnvironmentMiddleware) extractEnvironmentID(c *gin.Context) string {
- requestPath := c.Request.URL.Path
+func (m *EnvironmentMiddleware) extractEnvironmentID(c echo.Context) string {
+ requestPath := c.Request().URL.Path
- // Skip non-environment routes (e.g., /api-keys/{id})
if !strings.Contains(requestPath, environmentsPathMarker) {
return ""
}
- // Try path parameter first
if envID := c.Param(m.paramName); envID != "" {
return envID
}
- // Fall back to parsing the URL path
if _, rest, ok := strings.Cut(requestPath, environmentsPathMarker); ok {
if envID, _, _ := strings.Cut(rest, "/"); envID != "" {
return envID
@@ -277,29 +246,24 @@ func (m *EnvironmentMiddleware) buildResourceSuffix(requestPath, envID string) s
}
// buildTargetURL constructs the full proxy target URL for a remote environment.
-func (m *EnvironmentMiddleware) buildTargetURL(c *gin.Context, envID, apiURL string) string {
- suffix := m.buildResourceSuffix(c.Request.URL.Path, envID)
+func (m *EnvironmentMiddleware) buildTargetURL(c echo.Context, envID, apiURL string) string {
+ req := c.Request()
+ suffix := m.buildResourceSuffix(req.URL.Path, envID)
target := strings.TrimRight(apiURL, "/") + path.Join(apiEnvironmentsPrefix, m.localID) + suffix
- if qs := c.Request.URL.RawQuery; qs != "" {
+ if qs := req.URL.RawQuery; qs != "" {
target += "?" + qs
}
return target
}
// buildProxyPath constructs the path sent through the edge tunnel.
-// Includes the /api/environments/{localID} prefix so the agent can route it properly.
-func (m *EnvironmentMiddleware) buildProxyPath(c *gin.Context, envID string) string {
- return path.Join(apiEnvironmentsPrefix, m.localID) + m.buildResourceSuffix(c.Request.URL.Path, envID)
+func (m *EnvironmentMiddleware) buildProxyPath(c echo.Context, envID string) string {
+ return path.Join(apiEnvironmentsPrefix, m.localID) + m.buildResourceSuffix(c.Request().URL.Path, envID)
}
// isWebSocketUpgrade checks if this is a WebSocket upgrade request.
-// A valid WebSocket handshake requires ALL of: Upgrade: websocket header,
-// Connection: upgrade header, and Sec-WebSocket-Key header. Checking them
-// individually causes false positives when a reverse proxy (e.g. nginx with
-// proxy_set_header Upgrade/Connection) forwards partial headers on normal
-// HTTP requests, resulting in 426 Upgrade Required errors. See #1216.
-func (m *EnvironmentMiddleware) isWebSocketUpgrade(c *gin.Context) bool {
- return websocket.IsWebSocketUpgrade(c.Request)
+func (m *EnvironmentMiddleware) isWebSocketUpgrade(c echo.Context) bool {
+ return websocket.IsWebSocketUpgrade(c.Request())
}
func isEdgeEnvironmentURLInternal(apiURL string) bool {
@@ -346,98 +310,89 @@ func (m *EnvironmentMiddleware) waitForActiveEdgeTunnelInternal(ctx context.Cont
}
}
-func (m *EnvironmentMiddleware) abortEdgeTunnelUnavailable(c *gin.Context) {
- c.JSON(http.StatusBadGateway, gin.H{
+func (m *EnvironmentMiddleware) abortEdgeTunnelUnavailable(c echo.Context) error {
+ return c.JSON(http.StatusBadGateway, map[string]any{
"success": false,
- "data": gin.H{
+ "data": map[string]any{
"error": "Edge agent is not connected",
},
})
- c.Abort()
}
// proxyWebSocket handles WebSocket proxy requests.
-func (m *EnvironmentMiddleware) proxyWebSocket(c *gin.Context, target string, accessToken *string, envID string) {
+func (m *EnvironmentMiddleware) proxyWebSocket(c echo.Context, target string, accessToken *string, envID string) error {
if isEdgeEnvironmentURLInternal(target) {
- slog.WarnContext(c.Request.Context(), "Refusing direct websocket proxy to edge environment without active tunnel", "environment_id", envID, "target", target)
- m.abortEdgeTunnelUnavailable(c)
- return
+ slog.WarnContext(c.Request().Context(), "Refusing direct websocket proxy to edge environment without active tunnel", "environment_id", envID, "target", target)
+ return m.abortEdgeTunnelUnavailable(c)
}
wsTarget := edge.HTTPToWebSocketURL(target)
headers := edge.BuildWebSocketHeaders(c, accessToken)
- if err := wsutil.ProxyHTTP(c.Writer, c.Request, wsTarget, headers); err != nil {
+ if err := wsutil.ProxyHTTP(c.Response().Writer, c.Request(), wsTarget, headers); err != nil {
slog.Error("websocket proxy failed", "err", err)
}
- c.Abort()
+ return nil
}
// proxyHTTP handles standard HTTP proxy requests.
-func (m *EnvironmentMiddleware) proxyHTTP(c *gin.Context, target string, accessToken *string) {
+func (m *EnvironmentMiddleware) proxyHTTP(c echo.Context, target string, accessToken *string) error {
if isEdgeEnvironmentURLInternal(target) {
- slog.WarnContext(c.Request.Context(), "Refusing direct HTTP proxy to edge environment without active tunnel", "target", target)
- m.abortEdgeTunnelUnavailable(c)
- return
+ slog.WarnContext(c.Request().Context(), "Refusing direct HTTP proxy to edge environment without active tunnel", "target", target)
+ return m.abortEdgeTunnelUnavailable(c)
}
req, err := m.createProxyRequest(c, target, accessToken)
if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
+ return c.JSON(http.StatusInternalServerError, map[string]any{
"success": false,
- "data": gin.H{"error": errFailedCreateProxyRequest},
+ "data": map[string]any{"error": errFailedCreateProxyRequest},
})
- c.Abort()
- return
}
resp, err := m.httpClient.Do(req) //nolint:gosec // intentional proxy request to resolved remote environment URL
if err != nil {
- c.JSON(http.StatusBadGateway, gin.H{
+ return c.JSON(http.StatusBadGateway, map[string]any{
"success": false,
- "data": gin.H{"error": fmt.Sprintf("%s %v", errProxyRequestFailedPrefix, err)},
+ "data": map[string]any{"error": fmt.Sprintf("%s %v", errProxyRequestFailedPrefix, err)},
})
- c.Abort()
- return
}
defer func() { _ = resp.Body.Close() }()
m.writeProxyResponse(c, resp)
- c.Abort()
+ return nil
}
// createProxyRequest builds the HTTP request to forward to the remote environment.
-func (m *EnvironmentMiddleware) createProxyRequest(c *gin.Context, target string, accessToken *string) (*http.Request, error) {
+func (m *EnvironmentMiddleware) createProxyRequest(c echo.Context, target string, accessToken *string) (*http.Request, error) {
+ srcReq := c.Request()
var bodyBytes []byte
- if c.Request.Body != nil {
+ if srcReq.Body != nil {
var err error
- bodyBytes, err = io.ReadAll(c.Request.Body)
- _ = c.Request.Body.Close()
+ bodyBytes, err = io.ReadAll(srcReq.Body)
+ _ = srcReq.Body.Close()
if err != nil {
return nil, fmt.Errorf("failed to read request body: %w", err)
}
}
- slog.DebugContext(c.Request.Context(), "Creating proxy request", "method", c.Request.Method, "target", target, "contentLength", c.Request.ContentLength, "contentType", c.GetHeader("Content-Type"), "bodyLength", len(bodyBytes), "body", string(bodyBytes))
+ slog.DebugContext(srcReq.Context(), "Creating proxy request", "method", srcReq.Method, "target", target, "contentLength", srcReq.ContentLength, "contentType", srcReq.Header.Get("Content-Type"), "bodyLength", len(bodyBytes), "body", string(bodyBytes))
- // bytes.NewReader is preferred over bytes.NewBuffer: it implements io.ReadSeeker
- // and avoids the internal grow-buffer logic that NewBuffer carries.
var body io.Reader
if len(bodyBytes) > 0 {
body = bytes.NewReader(bodyBytes)
}
- req, err := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, target, body)
+ req, err := http.NewRequestWithContext(srcReq.Context(), srcReq.Method, target, body)
if err != nil {
return nil, err
}
skip := edge.GetSkipHeaders()
- edge.CopyRequestHeaders(c.Request.Header, req.Header, skip)
+ edge.CopyRequestHeaders(srcReq.Header, req.Header, skip)
edge.SetAuthHeader(req, c)
edge.SetAgentToken(req, accessToken)
- edge.SetForwardedHeaders(req, c.ClientIP(), c.Request.Host)
+ edge.SetForwardedHeaders(req, c.RealIP(), srcReq.Host)
- // Set Content-Length based on actual body size
if len(bodyBytes) > 0 {
req.ContentLength = int64(len(bodyBytes))
}
@@ -446,16 +401,13 @@ func (m *EnvironmentMiddleware) createProxyRequest(c *gin.Context, target string
}
// writeProxyResponse copies the proxy response back to the client.
-func (m *EnvironmentMiddleware) writeProxyResponse(c *gin.Context, resp *http.Response) {
+func (m *EnvironmentMiddleware) writeProxyResponse(c echo.Context, resp *http.Response) {
+ w := c.Response().Writer
hopByHop := edge.BuildHopByHopHeaders(resp.Header)
- edge.CopyResponseHeaders(resp.Header, c.Writer.Header(), hopByHop)
-
- c.Status(resp.StatusCode)
- if c.Request.Method != http.MethodHead {
- // Ensure headers are sent before streaming the body.
- // This is critical for streaming responses (e.g., JSON line streams) where
- // clients expect incremental updates.
- c.Writer.WriteHeaderNow()
- edge.CopyBodyWithFlush(c.Writer, resp.Body)
+ edge.CopyResponseHeaders(resp.Header, w.Header(), hopByHop)
+
+ w.WriteHeader(resp.StatusCode)
+ if c.Request().Method != http.MethodHead {
+ edge.CopyBodyWithFlush(w, resp.Body)
}
}
diff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.go
index fc24c65a0..a069985ac 100644
--- a/backend/internal/middleware/environment_middleware_test.go
+++ b/backend/internal/middleware/environment_middleware_test.go
@@ -7,7 +7,7 @@ import (
"testing"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
@@ -19,7 +19,7 @@ func newTestEnvironmentMiddleware() *EnvironmentMiddleware {
_ = ctx
return "edge://oracle-1", nil, true, nil
},
- authValidator: func(ctx context.Context, c *gin.Context) bool {
+ authValidator: func(ctx context.Context, c echo.Context) bool {
_ = ctx
_ = c
return true
@@ -29,18 +29,25 @@ func newTestEnvironmentMiddleware() *EnvironmentMiddleware {
}
}
-func TestEnvironmentMiddleware_ReturnsBadGatewayForEdgeResourcesWithoutTunnel(t *testing.T) {
- gin.SetMode(gin.TestMode)
+func attachMiddleware(router *echo.Echo, mw *EnvironmentMiddleware) *echo.Group {
+ api := router.Group("/api")
+ api.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ return mw.Handle(c, next)
+ }
+ })
+ return api
+}
+func TestEnvironmentMiddleware_ReturnsBadGatewayForEdgeResourcesWithoutTunnel(t *testing.T) {
middleware := newTestEnvironmentMiddleware()
- router := gin.New()
- api := router.Group("/api")
- api.Use(middleware.Handle)
+ router := echo.New()
+ api := attachMiddleware(router, middleware)
localHandlerHit := false
- api.GET("/environments/:id/containers", func(c *gin.Context) {
+ api.GET("/environments/:id/containers", func(c echo.Context) error {
localHandlerHit = true
- c.JSON(http.StatusOK, gin.H{"success": true})
+ return c.JSON(http.StatusOK, map[string]any{"success": true})
})
req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", nil)
@@ -54,17 +61,14 @@ func TestEnvironmentMiddleware_ReturnsBadGatewayForEdgeResourcesWithoutTunnel(t
}
func TestEnvironmentMiddleware_ProxiesDashboardResourcesForRemoteEnvironments(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
middleware := newTestEnvironmentMiddleware()
- router := gin.New()
- api := router.Group("/api")
- api.Use(middleware.Handle)
+ router := echo.New()
+ api := attachMiddleware(router, middleware)
localHandlerHit := false
- api.GET("/environments/:id/dashboard", func(c *gin.Context) {
+ api.GET("/environments/:id/dashboard", func(c echo.Context) error {
localHandlerHit = true
- c.JSON(http.StatusOK, gin.H{"success": true})
+ return c.JSON(http.StatusOK, map[string]any{"success": true})
})
req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/dashboard", nil)
@@ -78,17 +82,14 @@ func TestEnvironmentMiddleware_ProxiesDashboardResourcesForRemoteEnvironments(t
}
func TestEnvironmentMiddleware_KeepsEdgeManagementEndpointsLocal(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
middleware := newTestEnvironmentMiddleware()
- router := gin.New()
- api := router.Group("/api")
- api.Use(middleware.Handle)
+ router := echo.New()
+ api := attachMiddleware(router, middleware)
localHandlerHit := false
- api.GET("/environments/:id/settings", func(c *gin.Context) {
+ api.GET("/environments/:id/settings", func(c echo.Context) error {
localHandlerHit = true
- c.JSON(http.StatusOK, gin.H{"success": true})
+ return c.JSON(http.StatusOK, map[string]any{"success": true})
})
req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/settings", nil)
@@ -102,17 +103,14 @@ func TestEnvironmentMiddleware_KeepsEdgeManagementEndpointsLocal(t *testing.T) {
}
func TestEnvironmentMiddleware_KeepsEdgeMTLSDownloadEndpointsLocal(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
middleware := newTestEnvironmentMiddleware()
- router := gin.New()
- api := router.Group("/api")
- api.Use(middleware.Handle)
+ router := echo.New()
+ api := attachMiddleware(router, middleware)
localHandlerHit := false
- api.GET("/environments/:id/deployment/mtls/bundle", func(c *gin.Context) {
+ api.GET("/environments/:id/deployment/mtls/bundle", func(c echo.Context) error {
localHandlerHit = true
- c.JSON(http.StatusOK, gin.H{"success": true})
+ return c.JSON(http.StatusOK, map[string]any{"success": true})
})
req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/deployment/mtls/bundle", nil)
@@ -126,17 +124,14 @@ func TestEnvironmentMiddleware_KeepsEdgeMTLSDownloadEndpointsLocal(t *testing.T)
}
func TestEnvironmentMiddleware_KeepsNotificationEndpointsLocal(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
middleware := newTestEnvironmentMiddleware()
- router := gin.New()
- api := router.Group("/api")
- api.Use(middleware.Handle)
+ router := echo.New()
+ api := attachMiddleware(router, middleware)
localHandlerHit := false
- api.GET("/environments/:id/notifications/settings", func(c *gin.Context) {
+ api.GET("/environments/:id/notifications/settings", func(c echo.Context) error {
localHandlerHit = true
- c.JSON(http.StatusOK, gin.H{"success": true})
+ return c.JSON(http.StatusOK, map[string]any{"success": true})
})
req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/notifications/settings", nil)
@@ -150,28 +145,26 @@ func TestEnvironmentMiddleware_KeepsNotificationEndpointsLocal(t *testing.T) {
}
func TestEnvironmentMiddleware_ProxyWebSocketRejectsEdgeTargetsWithoutTunnel(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
middleware := newTestEnvironmentMiddleware()
+ e := echo.New()
recorder := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(recorder)
- c.Request = httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/ws/system/stats", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/ws/system/stats", nil)
+ c := e.NewContext(req, recorder)
- middleware.proxyWebSocket(c, "edge://oracle-1/api/environments/0/ws/system/stats", nil, "env-edge")
+ _ = middleware.proxyWebSocket(c, "edge://oracle-1/api/environments/0/ws/system/stats", nil, "env-edge")
assert.Equal(t, http.StatusBadGateway, recorder.Code)
assert.Contains(t, recorder.Body.String(), "Edge agent is not connected")
}
func TestEnvironmentMiddleware_ProxyHTTPRejectsEdgeTargetsWithoutTunnel(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
middleware := newTestEnvironmentMiddleware()
+ e := echo.New()
recorder := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(recorder)
- c.Request = httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", nil)
+ c := e.NewContext(req, recorder)
- middleware.proxyHTTP(c, "edge://oracle-1/api/environments/0/containers", nil)
+ _ = middleware.proxyHTTP(c, "edge://oracle-1/api/environments/0/containers", nil)
assert.Equal(t, http.StatusBadGateway, recorder.Code)
assert.Contains(t, recorder.Body.String(), "Edge agent is not connected")
@@ -224,13 +217,13 @@ func TestIsWebSocketUpgrade(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
+ e := echo.New()
recorder := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(recorder)
req := httptest.NewRequest(http.MethodGet, "/api/environments/env-1/containers", nil)
for k, v := range tt.headers {
req.Header.Set(k, v)
}
- c.Request = req
+ c := e.NewContext(req, recorder)
result := middleware.isWebSocketUpgrade(c)
assert.Equal(t, tt.expected, result, "headers: %v", tt.headers)
diff --git a/backend/internal/middleware/rate_limit_middleware.go b/backend/internal/middleware/rate_limit_middleware.go
index a11eb628e..464eb5270 100644
--- a/backend/internal/middleware/rate_limit_middleware.go
+++ b/backend/internal/middleware/rate_limit_middleware.go
@@ -10,7 +10,7 @@ import (
"sync"
"time"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
"golang.org/x/time/rate"
)
@@ -107,11 +107,9 @@ func (l *ipRateLimiter) evictOldestEntriesInternal(count int, protectedKey strin
}
}
-// PerIPRateLimit returns a Gin middleware that limits requests per client IP
-// to the given rate and burst. It responds with 429 when the limit is
-// exceeded. It is intended for public unauthenticated or weakly-authenticated
-// endpoints such as agent mTLS enrollment.
-func PerIPRateLimit(perMinute int, burst int) gin.HandlerFunc {
+// PerIPRateLimit returns an Echo middleware that limits requests per client IP
+// to the given rate and burst. It responds with 429 when the limit is exceeded.
+func PerIPRateLimit(perMinute int, burst int) echo.MiddlewareFunc {
if perMinute <= 0 {
perMinute = 10
}
@@ -120,24 +118,21 @@ func PerIPRateLimit(perMinute int, burst int) gin.HandlerFunc {
}
limiter := newIPRateLimiterInternal(rate.Every(time.Minute/time.Duration(perMinute)), burst)
- return func(c *gin.Context) {
- key := clientIPForRateLimitInternal(c)
- if !limiter.allow(key) {
- c.Header("Retry-After", "60")
- c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit exceeded"})
- return
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ key := clientIPForRateLimitInternal(c)
+ if !limiter.allow(key) {
+ c.Response().Header().Set("Retry-After", "60")
+ return c.JSON(http.StatusTooManyRequests, map[string]any{"error": "rate limit exceeded"})
+ }
+ return next(c)
}
- c.Next()
}
}
-// PerAgentTokenRateLimit returns a Gin middleware that limits requests per
-// edge agent token to the given rate and burst. Requests without a token pass
-// through so endpoint authentication can return the canonical auth error.
-// This is a token-scoped limiter only; enrollment and tunnel routes must also
-// stack PerIPRateLimit before it to provide IP-level back-pressure when tokens
-// are missing, invalid, rotated, or stolen.
-func PerAgentTokenRateLimit(perMinute int, burst int) gin.HandlerFunc {
+// PerAgentTokenRateLimit returns an Echo middleware that limits requests per
+// edge agent token to the given rate and burst.
+func PerAgentTokenRateLimit(perMinute int, burst int) echo.MiddlewareFunc {
if perMinute <= 0 {
perMinute = 10
}
@@ -146,21 +141,22 @@ func PerAgentTokenRateLimit(perMinute int, burst int) gin.HandlerFunc {
}
limiter := newIPRateLimiterInternal(rate.Every(time.Minute/time.Duration(perMinute)), burst)
- return func(c *gin.Context) {
- key := strings.TrimSpace(c.GetHeader("X-Arcane-Agent-Token"))
- if key == "" {
- key = strings.TrimSpace(c.GetHeader("X-API-Key"))
- }
- if key == "" {
- c.Next()
- return
- }
- if !limiter.allow(agentTokenRateLimitKeyInternal(key)) {
- c.Header("Retry-After", "60")
- c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit exceeded"})
- return
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ req := c.Request()
+ key := strings.TrimSpace(req.Header.Get("X-Arcane-Agent-Token"))
+ if key == "" {
+ key = strings.TrimSpace(req.Header.Get("X-API-Key"))
+ }
+ if key == "" {
+ return next(c)
+ }
+ if !limiter.allow(agentTokenRateLimitKeyInternal(key)) {
+ c.Response().Header().Set("Retry-After", "60")
+ return c.JSON(http.StatusTooManyRequests, map[string]any{"error": "rate limit exceeded"})
+ }
+ return next(c)
}
- c.Next()
}
}
@@ -169,14 +165,13 @@ func agentTokenRateLimitKeyInternal(token string) string {
return hex.EncodeToString(sum[:])
}
-func clientIPForRateLimitInternal(c *gin.Context) string {
- // Prefer the Gin-resolved client IP, which respects trusted proxy config.
- if ip := strings.TrimSpace(c.ClientIP()); ip != "" {
+func clientIPForRateLimitInternal(c echo.Context) string {
+ if ip := strings.TrimSpace(c.RealIP()); ip != "" {
return ip
}
- host, _, err := net.SplitHostPort(c.Request.RemoteAddr)
+ host, _, err := net.SplitHostPort(c.Request().RemoteAddr)
if err != nil {
- return c.Request.RemoteAddr
+ return c.Request().RemoteAddr
}
return host
}
diff --git a/backend/internal/middleware/rate_limit_middleware_test.go b/backend/internal/middleware/rate_limit_middleware_test.go
index 565e661b9..a4f80c3aa 100644
--- a/backend/internal/middleware/rate_limit_middleware_test.go
+++ b/backend/internal/middleware/rate_limit_middleware_test.go
@@ -6,17 +6,16 @@ import (
"testing"
"time"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
"golang.org/x/time/rate"
)
func TestPerIPRateLimit_AllowsUnderBurstAndBlocksOver(t *testing.T) {
- gin.SetMode(gin.TestMode)
- router := gin.New()
- router.POST("/t", PerIPRateLimit(60, 2), func(c *gin.Context) {
- c.Status(http.StatusOK)
- })
+ router := echo.New()
+ router.POST("/t", func(c echo.Context) error {
+ return c.NoContent(http.StatusOK)
+ }, PerIPRateLimit(60, 2))
doReq := func() int {
req := httptest.NewRequest(http.MethodPost, "/t", nil)
@@ -26,18 +25,16 @@ func TestPerIPRateLimit_AllowsUnderBurstAndBlocksOver(t *testing.T) {
return rec.Code
}
- // Burst of 2 must succeed, the third immediate request must be throttled.
require.Equal(t, http.StatusOK, doReq())
require.Equal(t, http.StatusOK, doReq())
require.Equal(t, http.StatusTooManyRequests, doReq())
}
func TestPerIPRateLimit_TracksDistinctClients(t *testing.T) {
- gin.SetMode(gin.TestMode)
- router := gin.New()
- router.POST("/t", PerIPRateLimit(60, 1), func(c *gin.Context) {
- c.Status(http.StatusOK)
- })
+ router := echo.New()
+ router.POST("/t", func(c echo.Context) error {
+ return c.NoContent(http.StatusOK)
+ }, PerIPRateLimit(60, 1))
doReqFrom := func(addr string) int {
req := httptest.NewRequest(http.MethodPost, "/t", nil)
@@ -49,16 +46,14 @@ func TestPerIPRateLimit_TracksDistinctClients(t *testing.T) {
require.Equal(t, http.StatusOK, doReqFrom("192.0.2.10:1000"))
require.Equal(t, http.StatusTooManyRequests, doReqFrom("192.0.2.10:1000"))
- // Distinct client must not be affected by the first client's throttling.
require.Equal(t, http.StatusOK, doReqFrom("192.0.2.11:1000"))
}
func TestStackedAgentEnrollmentRateLimits_KeepIPBackPressure(t *testing.T) {
- gin.SetMode(gin.TestMode)
- router := gin.New()
- router.POST("/t", PerIPRateLimit(60, 1), PerAgentTokenRateLimit(60, 10), func(c *gin.Context) {
- c.Status(http.StatusOK)
- })
+ router := echo.New()
+ router.POST("/t", func(c echo.Context) error {
+ return c.NoContent(http.StatusOK)
+ }, PerIPRateLimit(60, 1), PerAgentTokenRateLimit(60, 10))
doReq := func(token string) int {
req := httptest.NewRequest(http.MethodPost, "/t", nil)
diff --git a/backend/pkg/libarcane/edge/client_grpc_test.go b/backend/pkg/libarcane/edge/client_grpc_test.go
index 485b5a7bf..94c4fa671 100644
--- a/backend/pkg/libarcane/edge/client_grpc_test.go
+++ b/backend/pkg/libarcane/edge/client_grpc_test.go
@@ -14,8 +14,8 @@ import (
"time"
tunnelpb "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge/proto/tunnel/v1"
- "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/http2"
@@ -463,15 +463,13 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
return ok && tunnel != nil && !tunnel.Conn.IsClosed()
}, 5*time.Second, 20*time.Millisecond)
- gin.SetMode(gin.TestMode)
- router := gin.New()
- router.GET("/proxy-ws", func(c *gin.Context) {
+ router := echo.New()
+ router.GET("/proxy-ws", func(c echo.Context) error {
tunnel, ok := GetRegistry().Get(envID)
if !ok || tunnel == nil {
- c.AbortWithStatus(http.StatusServiceUnavailable)
- return
+ return c.NoContent(http.StatusServiceUnavailable)
}
- ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
+ return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
})
proxyServer := httptest.NewServer(router)
diff --git a/backend/pkg/libarcane/edge/internal_tunnel_request_test.go b/backend/pkg/libarcane/edge/internal_tunnel_request_test.go
index 13fd0afc0..9f95bee1c 100644
--- a/backend/pkg/libarcane/edge/internal_tunnel_request_test.go
+++ b/backend/pkg/libarcane/edge/internal_tunnel_request_test.go
@@ -6,15 +6,13 @@ import (
"net/http"
"testing"
- "github.com/gin-gonic/gin"
- sloggin "github.com/samber/slog-gin"
+ "github.com/labstack/echo/v4"
+ slogecho "github.com/samber/slog-echo"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
-func TestTunnelClient_InternalRequestSkipsSlogGin(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
+func TestTunnelClient_InternalRequestSkipsSlogEcho(t *testing.T) {
tests := []struct {
name string
run func(t *testing.T, client *TunnelClient)
@@ -64,19 +62,20 @@ func TestTunnelClient_InternalRequestSkipsSlogGin(t *testing.T) {
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
var sawInternalTunnelRequest bool
- loggerMiddleware := sloggin.NewWithConfig(slog.Default(), sloggin.Config{})
+ loggerMiddleware := slogecho.New(slog.Default())
- router := gin.New()
- router.Use(func(c *gin.Context) {
- if IsInternalTunnelRequest(c.Request.Context()) {
- sawInternalTunnelRequest = true
- c.Next()
- return
+ router := echo.New()
+ router.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ if IsInternalTunnelRequest(c.Request().Context()) {
+ sawInternalTunnelRequest = true
+ return next(c)
+ }
+ return loggerMiddleware(next)(c)
}
- loggerMiddleware(c)
})
- router.GET("/local/api", func(c *gin.Context) {
- c.String(http.StatusOK, "local response")
+ router.GET("/local/api", func(c echo.Context) error {
+ return c.String(http.StatusOK, "local response")
})
client := NewTunnelClient(&Config{}, router)
diff --git a/backend/pkg/libarcane/edge/poll_control.go b/backend/pkg/libarcane/edge/poll_control.go
index b9a22b1ca..3bc5b973e 100644
--- a/backend/pkg/libarcane/edge/poll_control.go
+++ b/backend/pkg/libarcane/edge/poll_control.go
@@ -11,7 +11,7 @@ import (
"time"
"github.com/getarcaneapp/arcane/backend/pkg/remenv"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
)
const (
@@ -219,15 +219,16 @@ func (r *PollRuntimeRegistry) Get(envID string, now time.Time) (PollRuntimeState
return state, true
}
-func decodeTunnelPollRequestInternal(c *gin.Context) (*TunnelPollRequest, error) {
- if c == nil || c.Request == nil || c.Request.Body == nil {
+func decodeTunnelPollRequestInternal(c echo.Context) (*TunnelPollRequest, error) {
+ if c == nil || c.Request() == nil || c.Request().Body == nil {
return &TunnelPollRequest{}, nil
}
- defer func() { _ = c.Request.Body.Close() }()
+ req := c.Request()
+ defer func() { _ = req.Body.Close() }()
- var req TunnelPollRequest
- if err := json.NewDecoder(c.Request.Body).Decode(&req); err != nil {
+ var pollReq TunnelPollRequest
+ if err := json.NewDecoder(req.Body).Decode(&pollReq); err != nil {
if errors.Is(err, http.ErrBodyReadAfterClose) {
return &TunnelPollRequest{}, nil
}
@@ -237,7 +238,7 @@ func decodeTunnelPollRequestInternal(c *gin.Context) (*TunnelPollRequest, error)
return nil, err
}
- return &req, nil
+ return &pollReq, nil
}
func (s *TunnelServer) pollStatusInternal(envID string) TunnelPollResponse {
@@ -264,22 +265,21 @@ func (s *TunnelServer) pollStatusInternal(envID string) TunnelPollResponse {
}
// HandlePoll is the HTTP control-plane endpoint used by poll-mode agents.
-func (s *TunnelServer) HandlePoll(c *gin.Context) {
- ctx := c.Request.Context()
+func (s *TunnelServer) HandlePoll(c echo.Context) error {
+ req := c.Request()
+ ctx := req.Context()
if _, err := decodeTunnelPollRequestInternal(c); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid poll payload"})
- return
+ return c.JSON(http.StatusBadRequest, map[string]any{"error": "invalid poll payload"})
}
// In proxy-terminated mTLS deployments, the client certificate is consumed
// by the TLS terminator before this request reaches Arcane. The token is
// still needed as the poll protocol's environment lookup claim.
- token, source := tokenFromHeadersWithSourceInternal(c.Request)
+ token, source := tokenFromHeadersWithSourceInternal(req)
if token == "" {
slog.WarnContext(ctx, "Edge poll request without token")
- c.JSON(http.StatusUnauthorized, gin.H{"error": "agent token required"})
- return
+ return c.JSON(http.StatusUnauthorized, map[string]any{"error": "agent token required"})
}
if source != HeaderAgentToken {
slog.DebugContext(ctx, "Edge poll request authenticated via fallback header",
@@ -296,13 +296,11 @@ func (s *TunnelServer) HandlePoll(c *gin.Context) {
"token_length", len(token),
"token_fingerprint", remenv.RedactedTokenFingerprint(token),
)
- c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid agent token"})
- return
+ return c.JSON(http.StatusUnauthorized, map[string]any{"error": "invalid agent token"})
}
- if err := s.requireRequestCertificateIdentityInternal(c.Request, envID); err != nil {
+ if err := s.requireRequestCertificateIdentityInternal(req, envID); err != nil {
slog.WarnContext(ctx, "Rejected edge poll request with mismatched client certificate", "environment_id", envID, "error", err)
- c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
- return
+ return c.JSON(http.StatusUnauthorized, map[string]any{"error": err.Error()})
}
pollInterval := DefaultTunnelPollInterval
@@ -310,5 +308,5 @@ func (s *TunnelServer) HandlePoll(c *gin.Context) {
resp := s.pollStatusInternal(envID)
resp.PollIntervalSeconds = int(pollInterval / time.Second)
- c.JSON(http.StatusOK, resp)
+ return c.JSON(http.StatusOK, resp)
}
diff --git a/backend/pkg/libarcane/edge/poll_control_test.go b/backend/pkg/libarcane/edge/poll_control_test.go
index a05633b1d..83d4dc68f 100644
--- a/backend/pkg/libarcane/edge/poll_control_test.go
+++ b/backend/pkg/libarcane/edge/poll_control_test.go
@@ -10,7 +10,7 @@ import (
"testing"
"time"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -28,8 +28,6 @@ func TestTunnelDemandRegistryDesiredStatus(t *testing.T) {
}
func TestTunnelServer_HandlePoll(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
registry := NewTunnelRegistry()
server := NewTunnelServerWithRegistry(registry, func(ctx context.Context, token string) (string, error) {
if token != "valid-token" {
@@ -38,7 +36,7 @@ func TestTunnelServer_HandlePoll(t *testing.T) {
return "env-poll-1", nil
}, nil)
- router := gin.New()
+ router := echo.New()
router.POST("/api/tunnel/poll", server.HandlePoll)
TouchTunnelDemand("env-poll-1", time.Minute)
@@ -82,8 +80,6 @@ func TestTunnelServer_HandlePoll(t *testing.T) {
// access policies) that strip non-standard X- headers; without it, agents
// behind such proxies log "invalid agent token" indefinitely.
func TestTunnelServer_HandlePoll_AcceptsTokenFromAllSupportedHeaders(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
cases := []struct {
name string
setHeader func(req *http.Request)
@@ -160,7 +156,7 @@ func TestTunnelServer_HandlePoll_AcceptsTokenFromAllSupportedHeaders(t *testing.
return "env-headers", nil
}, nil)
- router := gin.New()
+ router := echo.New()
router.POST("/api/tunnel/poll", server.HandlePoll)
req := httptest.NewRequest(http.MethodPost, "/api/tunnel/poll", bytes.NewBufferString(`{"transport":"poll"}`))
@@ -177,8 +173,6 @@ func TestTunnelServer_HandlePoll_AcceptsTokenFromAllSupportedHeaders(t *testing.
}
func TestTunnelServer_HandlePoll_AcceptsTokenAfterProxyTerminatedMTLS(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
server := NewTunnelServerWithRegistry(NewTunnelRegistry(), func(ctx context.Context, token string) (string, error) {
if token != "valid-token" {
return "", errors.New("invalid token")
@@ -190,7 +184,7 @@ func TestTunnelServer_HandlePoll_AcceptsTokenAfterProxyTerminatedMTLS(t *testing
AppURL: "https://manager.example.com",
})
- router := gin.New()
+ router := echo.New()
router.POST("/api/tunnel/poll", server.HandlePoll)
req := httptest.NewRequest(http.MethodPost, "/api/tunnel/poll", bytes.NewBufferString(`{"transport":"poll"}`))
diff --git a/backend/pkg/libarcane/edge/proxy.go b/backend/pkg/libarcane/edge/proxy.go
index a50f1199f..c2e006d7b 100644
--- a/backend/pkg/libarcane/edge/proxy.go
+++ b/backend/pkg/libarcane/edge/proxy.go
@@ -10,7 +10,7 @@ import (
"net/http"
"time"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
)
const (
@@ -166,34 +166,27 @@ func (s *grpcResponseState) handleCommandComplete(incoming *TunnelMessage) (bool
return true, incoming.Status, stripInternalTunnelHeaders(s.respHeaders), s.respBody.Bytes(), nil
}
-// ProxyHTTPRequest is a helper that proxies a gin context through a tunnel
-func ProxyHTTPRequest(c *gin.Context, tunnel *AgentTunnel, targetPath string) {
- ctx := c.Request.Context()
+// ProxyHTTPRequest is a helper that proxies an echo context through a tunnel
+func ProxyHTTPRequest(c echo.Context, tunnel *AgentTunnel, targetPath string) error {
+ req := c.Request()
+ ctx := req.Context()
- // Set a reasonable timeout
proxyCtx, cancel := context.WithTimeout(ctx, DefaultProxyTimeout)
defer cancel()
- // Read request body
var body []byte
- if c.Request.Body != nil {
+ if req.Body != nil {
var err error
- body, err = io.ReadAll(c.Request.Body)
+ body, err = io.ReadAll(req.Body)
if err != nil {
slog.ErrorContext(ctx, "Failed to read request body for tunnel proxy", "error", err)
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read request body"})
- return
+ return c.JSON(http.StatusInternalServerError, map[string]any{"error": "failed to read request body"})
}
- // Restore body for potential retry
- c.Request.Body = io.NopCloser(bytes.NewReader(body))
+ req.Body = io.NopCloser(bytes.NewReader(body))
}
- // Build headers map, stripping hop-by-hop and browser-security headers.
- // Browser-security headers (Origin, Referer, Cookie, etc.) must not be forwarded
- // because gin-contrib/cors on the agent side will reject requests whose Origin
- // doesn't match the agent's allowed origins, causing a 403 Forbidden.
headers := make(map[string]string)
- for k, v := range c.Request.Header {
+ for k, v := range req.Header {
if len(v) > 0 {
if isHopByHopHeader(k) || isBrowserSecurityHeader(k) {
continue
@@ -204,37 +197,32 @@ func ProxyHTTPRequest(c *gin.Context, tunnel *AgentTunnel, targetPath string) {
slog.DebugContext(ctx, "Proxying request through edge tunnel",
"environment_id", tunnel.EnvironmentID,
- "method", c.Request.Method,
+ "method", req.Method,
"path", targetPath,
"bodyLength", len(body),
)
- status, respHeaders, respBody, err := ProxyRequest(proxyCtx, tunnel, c.Request.Method, targetPath, c.Request.URL.RawQuery, headers, body)
+ status, respHeaders, respBody, err := ProxyRequest(proxyCtx, tunnel, req.Method, targetPath, req.URL.RawQuery, headers, body)
if err != nil {
slog.ErrorContext(ctx, "Edge tunnel proxy failed",
"environment_id", tunnel.EnvironmentID,
"error", err,
)
- // Check if it's a context timeout/cancel
if proxyCtx.Err() != nil {
- c.JSON(http.StatusGatewayTimeout, gin.H{"error": "request timed out"})
- return
+ return c.JSON(http.StatusGatewayTimeout, map[string]any{"error": "request timed out"})
}
- c.JSON(http.StatusBadGateway, gin.H{"error": "failed to proxy request through tunnel"})
- return
+ return c.JSON(http.StatusBadGateway, map[string]any{"error": "failed to proxy request through tunnel"})
}
- // Copy response headers
for k, v := range respHeaders {
if !isHopByHopHeader(k) {
- c.Header(k, v)
+ c.Response().Header().Set(k, v)
}
}
- // Write response
- c.Data(status, respHeaders["Content-Type"], respBody)
+ return c.Blob(status, respHeaders["Content-Type"], respBody)
}
// isHopByHopHeader returns true if the header should not be forwarded
@@ -254,9 +242,9 @@ func isHopByHopHeader(header string) bool {
// isBrowserSecurityHeader returns true for headers that are browser-enforced
// security headers. These must NOT be forwarded through the edge tunnel because
-// gin-contrib/cors will reject requests whose Origin does not match the agent's
-// allowed origins, returning 403. The agent authenticates via X-Arcane-Agent-Token
-// instead of browser cookies/origin checks.
+// the agent's CORS middleware will reject requests whose Origin does not match
+// its allowed origins, returning 403. The agent authenticates via
+// X-Arcane-Agent-Token instead of browser cookies/origin checks.
func isBrowserSecurityHeader(header string) bool {
browserHeaders := map[string]bool{
"Origin": true,
diff --git a/backend/pkg/libarcane/edge/proxy_headers_test.go b/backend/pkg/libarcane/edge/proxy_headers_test.go
index b84aa8f87..b4e961ecd 100644
--- a/backend/pkg/libarcane/edge/proxy_headers_test.go
+++ b/backend/pkg/libarcane/edge/proxy_headers_test.go
@@ -8,8 +8,8 @@ import (
"net/http/httptest"
"testing"
- "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -45,9 +45,6 @@ func TestIsBrowserSecurityHeader(t *testing.T) {
}
func TestProxyHTTPRequest_StripsBrowserHeaders(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
- // Track what headers the agent receives
var receivedHeaders map[string]string
server, tunnel := setupMockAgentServer(t, func(msg *TunnelMessage) *TunnelMessage {
@@ -63,27 +60,26 @@ func TestProxyHTTPRequest_StripsBrowserHeaders(t *testing.T) {
defer server.Close()
defer func() { _ = tunnel.Close() }()
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodPost, "/test", bytes.NewBufferString(`{"name":"test"}`))
-
- // Set headers that browsers add
- c.Request.Header.Set("Origin", "http://192.168.1.42:30258")
- c.Request.Header.Set("Referer", "http://192.168.1.42:30258/projects/new")
- c.Request.Header.Set("Cookie", "token=some-jwt-token")
- c.Request.Header.Set("Sec-Fetch-Mode", "cors")
- c.Request.Header.Set("Sec-Fetch-Site", "same-origin")
- c.Request.Header.Set("Sec-Fetch-Dest", "empty")
- c.Request.Header.Set("Access-Control-Request-Method", "POST")
- c.Request.Header.Set("Access-Control-Request-Headers", "Content-Type")
-
- // Set headers that SHOULD be forwarded
- c.Request.Header.Set("Content-Type", "application/json")
- c.Request.Header.Set("X-Arcane-Agent-Token", "agent-tok-123")
- c.Request.Header.Set("X-API-Key", "agent-tok-123")
- c.Request.Header.Set("Authorization", "Bearer jwt-token")
-
- ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
+ req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewBufferString(`{"name":"test"}`))
+
+ req.Header.Set("Origin", "http://192.168.1.42:30258")
+ req.Header.Set("Referer", "http://192.168.1.42:30258/projects/new")
+ req.Header.Set("Cookie", "token=some-jwt-token")
+ req.Header.Set("Sec-Fetch-Mode", "cors")
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ req.Header.Set("Sec-Fetch-Dest", "empty")
+ req.Header.Set("Access-Control-Request-Method", "POST")
+ req.Header.Set("Access-Control-Request-Headers", "Content-Type")
+
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Arcane-Agent-Token", "agent-tok-123")
+ req.Header.Set("X-API-Key", "agent-tok-123")
+ req.Header.Set("Authorization", "Bearer jwt-token")
+ c := e.NewContext(req, w)
+
+ _ = ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
assert.Equal(t, http.StatusOK, w.Code)
@@ -105,8 +101,6 @@ func TestProxyHTTPRequest_StripsBrowserHeaders(t *testing.T) {
}
func TestProxyHTTPRequest_ForwardsBodyCorrectly(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
var receivedBody []byte
var receivedMethod string
@@ -126,13 +120,14 @@ func TestProxyHTTPRequest_ForwardsBodyCorrectly(t *testing.T) {
requestBody := `{"name":"My Project"}`
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodPost, "/api/environments/abc/projects", bytes.NewBufferString(requestBody))
- c.Request.Header.Set("Content-Type", "application/json")
- c.Request.Header.Set("X-Arcane-Agent-Token", "tok")
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/abc/projects", bytes.NewBufferString(requestBody))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Arcane-Agent-Token", "tok")
+ c := e.NewContext(req, w)
- ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
+ _ = ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, http.MethodPost, receivedMethod)
@@ -234,11 +229,10 @@ func TestHandleRequest_NoBrowserHeadersInTunnelMessage(t *testing.T) {
func TestProxyHTTPRequest_EndToEnd_BrowserOriginStripped(t *testing.T) {
// Full end-to-end test: browser sends POST with Origin header via edge tunnel.
// The agent should NOT receive the Origin header.
- gin.SetMode(gin.TestMode)
- // This handler simulates what the agent's Gin handler would do.
+ // This handler simulates what the agent's handler would do.
// In a real scenario, if Origin is present and doesn't match allowed origins,
- // gin-contrib/cors would return 403 before this handler runs.
+ // CORS middleware would return 403 before this handler runs.
agentHandlerCalled := false
agentHandler := func(msg *TunnelMessage) *TunnelMessage {
agentHandlerCalled = true
@@ -264,17 +258,17 @@ func TestProxyHTTPRequest_EndToEnd_BrowserOriginStripped(t *testing.T) {
defer server.Close()
defer func() { _ = tunnel.Close() }()
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
-
body := `{"name":"New Project"}`
- c.Request = httptest.NewRequest(http.MethodPost, "/api/environments/env-123/projects", bytes.NewBufferString(body))
- c.Request.Header.Set("Origin", "http://192.168.1.42:30258")
- c.Request.Header.Set("Referer", "http://192.168.1.42:30258/projects/new")
- c.Request.Header.Set("Content-Type", "application/json")
- c.Request.Header.Set("X-Arcane-Agent-Token", "agent-tok")
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-123/projects", bytes.NewBufferString(body))
+ req.Header.Set("Origin", "http://192.168.1.42:30258")
+ req.Header.Set("Referer", "http://192.168.1.42:30258/projects/new")
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Arcane-Agent-Token", "agent-tok")
+ c := e.NewContext(req, w)
- ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
+ _ = ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
assert.True(t, agentHandlerCalled, "Agent handler should have been called")
assert.Equal(t, http.StatusCreated, w.Code, "Request should succeed because Origin was stripped")
@@ -282,8 +276,6 @@ func TestProxyHTTPRequest_EndToEnd_BrowserOriginStripped(t *testing.T) {
}
func TestProxyHTTPRequest_BodyPreservation_WebSocket(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
// Test that a POST body survives WebSocket JSON serialization round-trip
var receivedBody string
@@ -345,12 +337,13 @@ func TestProxyHTTPRequest_BodyPreservation_WebSocket(t *testing.T) {
requestBody := `{"name":"My Project","description":"A test project with special chars: <>&\""}`
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodPost, "/test", bytes.NewBufferString(requestBody))
- c.Request.Header.Set("Content-Type", "application/json")
+ req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewBufferString(requestBody))
+ req.Header.Set("Content-Type", "application/json")
+ c := e.NewContext(req, w)
- ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
+ _ = ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, requestBody, receivedBody, "Request body should survive WebSocket JSON serialization round-trip")
diff --git a/backend/pkg/libarcane/edge/proxy_test.go b/backend/pkg/libarcane/edge/proxy_test.go
index 2142513a0..df6aeb8e7 100644
--- a/backend/pkg/libarcane/edge/proxy_test.go
+++ b/backend/pkg/libarcane/edge/proxy_test.go
@@ -13,8 +13,8 @@ import (
"time"
tunnelpb "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge/proto/tunnel/v1"
- "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
@@ -100,8 +100,6 @@ func TestProxyRequest(t *testing.T) {
}
func TestProxyHTTPRequest(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
server, tunnel := setupMockAgentServer(t, func(msg *TunnelMessage) *TunnelMessage {
return &TunnelMessage{
ID: msg.ID,
@@ -114,13 +112,13 @@ func TestProxyHTTPRequest(t *testing.T) {
defer server.Close()
defer func() { _ = tunnel.Close() }()
- // Mock Gin context
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodPost, "/test", bytes.NewBufferString("request body"))
- c.Request.Header.Set("X-Custom", "header")
+ req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewBufferString("request body"))
+ req.Header.Set("X-Custom", "header")
+ c := e.NewContext(req, w)
- ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
+ _ = ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
@@ -128,8 +126,6 @@ func TestProxyHTTPRequest(t *testing.T) {
}
func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
envID := "env-grpc-proxy-http-1"
@@ -229,13 +225,14 @@ func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
return ok && tunnel != nil && !tunnel.Conn.IsClosed()
}, time.Second, 10*time.Millisecond)
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodPost, "/test?from=test", bytes.NewBufferString("request body"))
- c.Request.Header.Set("X-Custom", "header")
- c.Request.Header.Set("Connection", "keep-alive")
+ req := httptest.NewRequest(http.MethodPost, "/test?from=test", bytes.NewBufferString("request body"))
+ req.Header.Set("X-Custom", "header")
+ req.Header.Set("Connection", "keep-alive")
+ c := e.NewContext(req, w)
- ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
+ _ = ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
diff --git a/backend/pkg/libarcane/edge/remenv.go b/backend/pkg/libarcane/edge/remenv.go
index ead5f1fb8..102f1c542 100644
--- a/backend/pkg/libarcane/edge/remenv.go
+++ b/backend/pkg/libarcane/edge/remenv.go
@@ -6,7 +6,7 @@ import (
"strings"
"github.com/getarcaneapp/arcane/backend/pkg/remenv"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
)
const (
@@ -32,17 +32,17 @@ func CopyRequestHeaders(from http.Header, to http.Header, skip map[string]struct
}
}
-func SetAuthHeader(req *http.Request, c *gin.Context) {
+func SetAuthHeader(req *http.Request, c echo.Context) {
// Forward API key header if present
- if apiKey := c.GetHeader(HeaderAPIKey); apiKey != "" {
+ if apiKey := c.Request().Header.Get(HeaderAPIKey); apiKey != "" {
req.Header.Set(HeaderAPIKey, apiKey)
}
// Forward Authorization header or cookie token
- if auth := c.GetHeader(HeaderAuthorization); auth != "" {
+ if auth := c.Request().Header.Get(HeaderAuthorization); auth != "" {
req.Header.Set(HeaderAuthorization, auth)
- } else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {
- req.Header.Set(HeaderAuthorization, "Bearer "+cookieToken)
+ } else if ck, err := c.Cookie("token"); err == nil && ck != nil && ck.Value != "" {
+ req.Header.Set(HeaderAuthorization, "Bearer "+ck.Value)
}
}
@@ -52,24 +52,25 @@ func SetAgentToken(req *http.Request, accessToken *string) {
// BuildWebSocketHeaders constructs a header set for proxying WebSocket requests
// to a remote environment, forwarding authentication in the same way as HTTP proxying.
-func BuildWebSocketHeaders(c *gin.Context, accessToken *string) http.Header {
+func BuildWebSocketHeaders(c echo.Context, accessToken *string) http.Header {
headers := http.Header{}
+ req := c.Request()
// Forward API key if present
- if apiKey := c.GetHeader(HeaderAPIKey); apiKey != "" {
+ if apiKey := req.Header.Get(HeaderAPIKey); apiKey != "" {
headers.Set(HeaderAPIKey, apiKey)
}
// Forward authorization (header or cookie)
- if auth := c.GetHeader(HeaderAuthorization); auth != "" {
+ if auth := req.Header.Get(HeaderAuthorization); auth != "" {
headers.Set(HeaderAuthorization, auth)
- } else if token, err := c.Cookie("token"); err == nil && token != "" {
- headers.Set(HeaderAuthorization, "Bearer "+token)
+ } else if ck, err := c.Cookie("token"); err == nil && ck != nil && ck.Value != "" {
+ headers.Set(HeaderAuthorization, "Bearer "+ck.Value)
}
// Forward cookies if no other auth is present
if headers.Get(HeaderAuthorization) == "" && headers.Get(HeaderAPIKey) == "" {
- if cookies := c.Request.Header.Get(HeaderCookie); cookies != "" {
+ if cookies := req.Header.Get(HeaderCookie); cookies != "" {
headers.Set(HeaderCookie, cookies)
}
}
diff --git a/backend/pkg/libarcane/edge/remenv_test.go b/backend/pkg/libarcane/edge/remenv_test.go
index 44316d78c..da6235062 100644
--- a/backend/pkg/libarcane/edge/remenv_test.go
+++ b/backend/pkg/libarcane/edge/remenv_test.go
@@ -8,7 +8,7 @@ import (
"net/http/httptest"
"testing"
- "github.com/gin-gonic/gin"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
)
@@ -88,12 +88,12 @@ func TestCopyRequestHeaders_SkipsExpectedHeaders(t *testing.T) {
}
func TestSetAuthHeader_ForwardsAPIKeyAndAuthorization(t *testing.T) {
- gin.SetMode(gin.TestMode)
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodGet, "http://example.com", nil)
- c.Request.Header.Set(HeaderAPIKey, "api-token")
- c.Request.Header.Set(HeaderAuthorization, "Bearer auth")
+ req0 := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req0.Header.Set(HeaderAPIKey, "api-token")
+ req0.Header.Set(HeaderAuthorization, "Bearer auth")
+ c := e.NewContext(req0, w)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://remote", nil)
require.NoError(t, err)
@@ -104,11 +104,11 @@ func TestSetAuthHeader_ForwardsAPIKeyAndAuthorization(t *testing.T) {
}
func TestSetAuthHeader_UsesCookieTokenWhenNoAuthorization(t *testing.T) {
- gin.SetMode(gin.TestMode)
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodGet, "http://example.com", nil)
- c.Request.AddCookie(&http.Cookie{Name: "token", Value: "cookie-token"})
+ req0 := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req0.AddCookie(&http.Cookie{Name: "token", Value: "cookie-token"})
+ c := e.NewContext(req0, w)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://remote", nil)
require.NoError(t, err)
@@ -191,13 +191,13 @@ func TestGetSkipHeaders_ContainsExpectedEntries(t *testing.T) {
}
func TestBuildWebSocketHeaders_UsesAuthorizationHeaderAndAddsAgentToken(t *testing.T) {
- gin.SetMode(gin.TestMode)
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodGet, "http://example.com", nil)
- c.Request.Header.Set(HeaderAPIKey, "api-key")
- c.Request.Header.Set(HeaderAuthorization, "Bearer auth")
- c.Request.Header.Set(HeaderCookie, "session=abc")
+ req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req.Header.Set(HeaderAPIKey, "api-key")
+ req.Header.Set(HeaderAuthorization, "Bearer auth")
+ req.Header.Set(HeaderCookie, "session=abc")
+ c := e.NewContext(req, w)
agent := "agent-token"
headers := BuildWebSocketHeaders(c, &agent)
@@ -209,22 +209,22 @@ func TestBuildWebSocketHeaders_UsesAuthorizationHeaderAndAddsAgentToken(t *testi
}
func TestBuildWebSocketHeaders_UsesCookieTokenAsBearer(t *testing.T) {
- gin.SetMode(gin.TestMode)
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodGet, "http://example.com", nil)
- c.Request.AddCookie(&http.Cookie{Name: "token", Value: "cookie-token"})
+ req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req.AddCookie(&http.Cookie{Name: "token", Value: "cookie-token"})
+ c := e.NewContext(req, w)
headers := BuildWebSocketHeaders(c, nil)
require.Equal(t, "Bearer cookie-token", headers.Get(HeaderAuthorization))
}
func TestBuildWebSocketHeaders_ForwardsCookieHeaderWhenNoAuthPresent(t *testing.T) {
- gin.SetMode(gin.TestMode)
+ e := echo.New()
w := httptest.NewRecorder()
- c, _ := gin.CreateTestContext(w)
- c.Request = httptest.NewRequest(http.MethodGet, "http://example.com", nil)
- c.Request.Header.Set(HeaderCookie, "session=abc")
+ req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req.Header.Set(HeaderCookie, "session=abc")
+ c := e.NewContext(req, w)
headers := BuildWebSocketHeaders(c, nil)
require.Equal(t, "session=abc", headers.Get(HeaderCookie))
diff --git a/backend/pkg/libarcane/edge/server.go b/backend/pkg/libarcane/edge/server.go
index 256ebb871..3cc46b9a4 100644
--- a/backend/pkg/libarcane/edge/server.go
+++ b/backend/pkg/libarcane/edge/server.go
@@ -13,9 +13,9 @@ import (
tunnelpb "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge/proto/tunnel/v1"
"github.com/getarcaneapp/arcane/backend/pkg/remenv"
- "github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
@@ -133,15 +133,16 @@ func (s *TunnelServer) SetConfig(cfg *Config) {
// HandleConnect is the WebSocket handler for edge agent connections.
// This is registered at /api/tunnel/connect.
-func (s *TunnelServer) HandleConnect(c *gin.Context) {
- ctx := c.Request.Context()
+func (s *TunnelServer) HandleConnect(c echo.Context) error {
+ req := c.Request()
+ ctx := req.Context()
callbackCtx := context.WithoutCancel(ctx)
// Upgrade to WebSocket.
- conn, err := tunnelUpgrader.Upgrade(c.Writer, c.Request, nil)
+ conn, err := tunnelUpgrader.Upgrade(c.Response().Writer, req, nil)
if err != nil {
slog.ErrorContext(ctx, "Failed to upgrade edge tunnel connection", "error", err)
- return
+ return nil
}
tunnelConn := NewTunnelConn(conn)
@@ -149,15 +150,15 @@ func (s *TunnelServer) HandleConnect(c *gin.Context) {
if err != nil {
slog.WarnContext(ctx, "Failed to receive websocket edge tunnel registration", "error", err)
_ = tunnelConn.Close()
- return
+ return nil
}
if firstMsg == nil || firstMsg.Type != MessageTypeRegister {
slog.WarnContext(ctx, "Websocket edge tunnel missing register message")
_ = tunnelConn.Close()
- return
+ return nil
}
- token := tokenFromHeadersInternal(c.Request)
+ token := tokenFromHeadersInternal(req)
if token == "" {
// Header auth can be unavailable after the WebSocket upgrade path, so
// the register message remains a fallback environment lookup claim.
@@ -169,7 +170,7 @@ func (s *TunnelServer) HandleConnect(c *gin.Context) {
slog.WarnContext(ctx, "Edge tunnel connection attempt without token")
_ = tunnelConn.Send(&TunnelMessage{Type: MessageTypeRegisterResponse, Accepted: false, Error: "agent token required"})
_ = tunnelConn.Close()
- return
+ return nil
}
envID, err := s.resolveEnvironment(ctx, token)
@@ -177,44 +178,43 @@ func (s *TunnelServer) HandleConnect(c *gin.Context) {
slog.WarnContext(ctx, "Failed to resolve agent token", "error", err)
_ = tunnelConn.Send(&TunnelMessage{Type: MessageTypeRegisterResponse, Accepted: false, Error: "invalid agent token"})
_ = tunnelConn.Close()
- return
+ return nil
}
- if err := s.requireRequestCertificateIdentityInternal(c.Request, envID); err != nil {
+ if err := s.requireRequestCertificateIdentityInternal(req, envID); err != nil {
slog.WarnContext(ctx, "Rejected websocket edge tunnel with mismatched client certificate", "environment_id", envID, "error", err)
_ = tunnelConn.Send(&TunnelMessage{Type: MessageTypeRegisterResponse, Accepted: false, Error: "client certificate does not match environment"})
_ = tunnelConn.Close()
- return
+ return nil
}
tunnel := NewAgentTunnelWithConn(envID, tunnelConn)
- s.populateSessionMetadata(tunnel, firstMsg, requestSecurityModeInternal(c.Request))
+ s.populateSessionMetadata(tunnel, firstMsg, requestSecurityModeInternal(req))
s.manageConnectedTunnel(ctx, callbackCtx, tunnel)
+ return nil
}
// HandleMTLSEnroll returns manager-generated edge client certificates for the
// calling environment when generated edge mTLS is enabled. The response includes
// private key material, so response-body logging must not be enabled here.
-func (s *TunnelServer) HandleMTLSEnroll(c *gin.Context) {
- ctx := c.Request.Context()
- c.Header("Cache-Control", "no-store")
- c.Header("Pragma", "no-cache")
+func (s *TunnelServer) HandleMTLSEnroll(c echo.Context) error {
+ req := c.Request()
+ ctx := req.Context()
+ c.Response().Header().Set("Cache-Control", "no-store")
+ c.Response().Header().Set("Pragma", "no-cache")
if s == nil || s.cfg == nil || !shouldUseGeneratedManagerCAInternal(s.cfg) {
- c.JSON(http.StatusNotFound, gin.H{"error": "edge mTLS enrollment is not available"})
- return
+ return c.JSON(http.StatusNotFound, map[string]any{"error": "edge mTLS enrollment is not available"})
}
- token := tokenFromHeadersInternal(c.Request)
+ token := tokenFromHeadersInternal(req)
if token == "" {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "agent token required"})
- return
+ return c.JSON(http.StatusUnauthorized, map[string]any{"error": "agent token required"})
}
envID, err := s.resolveEnvironment(ctx, token)
if err != nil {
slog.WarnContext(ctx, "Failed to resolve edge token for mTLS enrollment", "error", err)
- c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid agent token"})
- return
+ return c.JSON(http.StatusUnauthorized, map[string]any{"error": "invalid agent token"})
}
envName := ""
@@ -231,51 +231,45 @@ func (s *TunnelServer) HandleMTLSEnroll(c *gin.Context) {
previouslyEnrolled, enrollmentLimited, err := managerMTLSEnrollmentStateInternal(s.cfg, envID, now)
if err != nil {
slog.ErrorContext(ctx, "Failed to read edge mTLS enrollment state", "environment_id", envID, "error", err)
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read edge mTLS enrollment state"})
- return
+ return c.JSON(http.StatusInternalServerError, map[string]any{"error": "failed to read edge mTLS enrollment state"})
}
if enrollmentLimited {
cachedAssets, cacheErr := GenerateManagerClientMTLSAssetsWithContext(ctx, s.cfg, envID, envName)
if cacheErr == nil && cachedAssets != nil {
- slog.InfoContext(ctx, "Served cached edge mTLS enrollment during cooldown", "environment_id", envID, "remote_addr", c.ClientIP())
- c.JSON(http.StatusOK, enrollMTLSResponse{Files: cachedAssets.Files})
- return
+ slog.InfoContext(ctx, "Served cached edge mTLS enrollment during cooldown", "environment_id", envID, "remote_addr", c.RealIP())
+ return c.JSON(http.StatusOK, enrollMTLSResponse{Files: cachedAssets.Files})
}
if cacheErr != nil {
slog.WarnContext(ctx, "Failed to re-serve cached edge mTLS enrollment during cooldown", "environment_id", envID, "error", cacheErr)
}
- slog.WarnContext(ctx, "Rejected repeated edge mTLS enrollment during cooldown", "environment_id", envID, "remote_addr", c.ClientIP())
- c.JSON(http.StatusTooManyRequests, gin.H{"error": "edge mTLS enrollment was recently completed; retry later"})
- return
+ slog.WarnContext(ctx, "Rejected repeated edge mTLS enrollment during cooldown", "environment_id", envID, "remote_addr", c.RealIP())
+ return c.JSON(http.StatusTooManyRequests, map[string]any{"error": "edge mTLS enrollment was recently completed; retry later"})
}
assets, err := GenerateManagerClientMTLSAssetsWithContext(ctx, s.cfg, envID, envName)
if err != nil {
slog.ErrorContext(ctx, "Failed to generate edge mTLS enrollment assets", "environment_id", envID, "error", err)
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate edge mTLS assets"})
- return
+ return c.JSON(http.StatusInternalServerError, map[string]any{"error": "failed to generate edge mTLS assets"})
}
if assets == nil {
- c.JSON(http.StatusNotFound, gin.H{"error": "edge mTLS enrollment assets unavailable"})
- return
+ return c.JSON(http.StatusNotFound, map[string]any{"error": "edge mTLS enrollment assets unavailable"})
}
assets.Reenrolled = previouslyEnrolled
if err := recordManagerMTLSEnrollmentInternal(s.cfg, envID, now); err != nil {
slog.ErrorContext(ctx, "Failed to record edge mTLS enrollment state", "environment_id", envID, "error", err)
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to record edge mTLS enrollment state"})
- return
+ return c.JSON(http.StatusInternalServerError, map[string]any{"error": "failed to record edge mTLS enrollment state"})
}
if assets.Reenrolled {
- slog.WarnContext(ctx, "Edge mTLS certificate assets re-enrolled", "environment_id", envID, "remote_addr", c.ClientIP(), "cert_issued", assets.CertIssued)
+ slog.WarnContext(ctx, "Edge mTLS certificate assets re-enrolled", "environment_id", envID, "remote_addr", c.RealIP(), "cert_issued", assets.CertIssued)
} else {
- slog.InfoContext(ctx, "Edge mTLS certificate assets enrolled", "environment_id", envID, "remote_addr", c.ClientIP(), "cert_issued", assets.CertIssued)
+ slog.InfoContext(ctx, "Edge mTLS certificate assets enrolled", "environment_id", envID, "remote_addr", c.RealIP(), "cert_issued", assets.CertIssued)
}
if s.enrollmentCallback != nil {
- s.enrollmentCallback(context.WithoutCancel(ctx), envID, c.ClientIP(), assets.CertIssued, assets.CAGenerated, assets.Reenrolled)
+ s.enrollmentCallback(context.WithoutCancel(ctx), envID, c.RealIP(), assets.CertIssued, assets.CAGenerated, assets.Reenrolled)
}
- c.JSON(http.StatusOK, enrollMTLSResponse{Files: assets.Files})
+ return c.JSON(http.StatusOK, enrollMTLSResponse{Files: assets.Files})
}
// Connect is the gRPC bidi stream handler for edge agent connections.
diff --git a/backend/pkg/libarcane/edge/server_test.go b/backend/pkg/libarcane/edge/server_test.go
index da25d028c..fb40a7bf0 100644
--- a/backend/pkg/libarcane/edge/server_test.go
+++ b/backend/pkg/libarcane/edge/server_test.go
@@ -15,8 +15,8 @@ import (
"testing"
"time"
- "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
@@ -25,8 +25,6 @@ import (
)
func TestTunnelServer_HandleConnect(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
resolver := func(ctx context.Context, token string) (string, error) {
if token == "valid-token" {
return "env-connected", nil
@@ -46,7 +44,7 @@ func TestTunnelServer_HandleConnect(t *testing.T) {
server := NewTunnelServer(resolver, callback)
- router := gin.New()
+ router := echo.New()
router.GET("/connect", server.HandleConnect)
ts := httptest.NewServer(router)
@@ -171,8 +169,6 @@ func TestTunnelServer_HandleConnect(t *testing.T) {
}
func TestTunnelServer_HandleConnect_AcceptsTokenAfterProxyTerminatedMTLS(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
server := NewTunnelServer(func(ctx context.Context, token string) (string, error) {
if token == "valid-token" {
return "env-proxy-mtls", nil
@@ -184,7 +180,7 @@ func TestTunnelServer_HandleConnect_AcceptsTokenAfterProxyTerminatedMTLS(t *test
AppURL: "https://manager.example.com",
})
- router := gin.New()
+ router := echo.New()
router.GET("/connect", server.HandleConnect)
ts := httptest.NewServer(router)
@@ -220,14 +216,12 @@ func TestTunnelServer_HandleConnect_AcceptsTokenAfterProxyTerminatedMTLS(t *test
}
func TestTunnelServer_HandleConnect_InvalidToken(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
resolver := func(ctx context.Context, token string) (string, error) {
return "", errors.New("invalid")
}
server := NewTunnelServer(resolver, nil)
- router := gin.New()
+ router := echo.New()
router.GET("/connect", server.HandleConnect)
ts := httptest.NewServer(router)
@@ -257,8 +251,6 @@ func TestTunnelServer_HandleConnect_InvalidToken(t *testing.T) {
}
func TestTunnelServer_HandleConnect_PrefersHeaderTokenOverRegisterMessage(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
var resolvedToken string
resolver := func(ctx context.Context, token string) (string, error) {
resolvedToken = token
@@ -269,7 +261,7 @@ func TestTunnelServer_HandleConnect_PrefersHeaderTokenOverRegisterMessage(t *tes
}
server := NewTunnelServer(resolver, nil)
- router := gin.New()
+ router := echo.New()
router.GET("/connect", server.HandleConnect)
ts := httptest.NewServer(router)
@@ -302,7 +294,7 @@ func TestTunnelServer_HandleConnect_PrefersHeaderTokenOverRegisterMessage(t *tes
func TestTunnelServer_HandleConnect_NoToken(t *testing.T) {
server := NewTunnelServer(nil, nil)
- router := gin.New()
+ router := echo.New()
router.GET("/connect", server.HandleConnect)
ts := httptest.NewServer(router)
@@ -330,8 +322,7 @@ func TestTunnelServer_HandleConnect_NoToken(t *testing.T) {
}
func TestTunnelConnectRouteRegistration(t *testing.T) {
- gin.SetMode(gin.TestMode)
- router := gin.New()
+ router := echo.New()
group := router.Group("/api")
server := NewTunnelServer(nil, nil)
@@ -347,8 +338,6 @@ func TestTunnelConnectRouteRegistration(t *testing.T) {
}
func TestTunnelServer_HandleMTLSEnroll(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
server := NewTunnelServer(func(ctx context.Context, token string) (string, error) {
if token != "valid-token" {
return "", errors.New("invalid token")
@@ -364,7 +353,7 @@ func TestTunnelServer_HandleMTLSEnroll(t *testing.T) {
EdgeMTLSAssetsDir: t.TempDir(),
})
- router := gin.New()
+ router := echo.New()
router.POST("/enroll", server.HandleMTLSEnroll)
req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
@@ -393,8 +382,6 @@ func TestTunnelServer_HandleMTLSEnroll(t *testing.T) {
}
func TestTunnelServer_HandleMTLSEnroll_ServesCachedAssetsDuringCooldown(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
server := NewTunnelServer(func(ctx context.Context, token string) (string, error) {
if token != "valid-token" {
return "", errors.New("invalid token")
@@ -406,7 +393,7 @@ func TestTunnelServer_HandleMTLSEnroll_ServesCachedAssetsDuringCooldown(t *testi
EdgeMTLSAssetsDir: t.TempDir(),
})
- router := gin.New()
+ router := echo.New()
router.POST("/enroll", server.HandleMTLSEnroll)
req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
@@ -431,8 +418,6 @@ func TestTunnelServer_HandleMTLSEnroll_ServesCachedAssetsDuringCooldown(t *testi
}
func TestTunnelServer_HandleMTLSEnroll_AllowsRepeatAfterCooldownAndMarksReenrollment(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
cfg := &Config{
EdgeMTLSMode: EdgeMTLSModeRequired,
EdgeMTLSAssetsDir: t.TempDir(),
@@ -451,7 +436,7 @@ func TestTunnelServer_HandleMTLSEnroll_AllowsRepeatAfterCooldownAndMarksReenroll
reenrolled <- wasReenrolled
})
- router := gin.New()
+ router := echo.New()
router.POST("/enroll", server.HandleMTLSEnroll)
req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
diff --git a/backend/pkg/libarcane/edge/ws_proxy.go b/backend/pkg/libarcane/edge/ws_proxy.go
index 1c6af8c98..0301562af 100644
--- a/backend/pkg/libarcane/edge/ws_proxy.go
+++ b/backend/pkg/libarcane/edge/ws_proxy.go
@@ -5,9 +5,9 @@ import (
"log/slog"
"net/http"
- "github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
)
var wsUpgraderForProxy = websocket.Upgrader{
@@ -19,14 +19,14 @@ var wsUpgraderForProxy = websocket.Upgrader{
// ProxyWebSocketRequest proxies a WebSocket upgrade through an edge tunnel.
// This handles logs, stats, and other streaming endpoints.
-func ProxyWebSocketRequest(c *gin.Context, tunnel *AgentTunnel, targetPath string) {
- ctx := c.Request.Context()
+func ProxyWebSocketRequest(c echo.Context, tunnel *AgentTunnel, targetPath string) error {
+ req := c.Request()
+ ctx := req.Context()
- // Upgrade the client connection to WebSocket
- clientWS, err := wsUpgraderForProxy.Upgrade(c.Writer, c.Request, nil)
+ clientWS, err := wsUpgraderForProxy.Upgrade(c.Response().Writer, req, nil)
if err != nil {
slog.ErrorContext(ctx, "Failed to upgrade WebSocket for edge proxy", "error", err)
- return
+ return nil
}
defer func() { _ = clientWS.Close() }()
@@ -44,16 +44,16 @@ func ProxyWebSocketRequest(c *gin.Context, tunnel *AgentTunnel, targetPath strin
})
defer tunnel.Pending.Delete(streamID)
- headers := buildWebSocketHeaders(c.Request)
+ headers := buildWebSocketHeaders(req)
if err := DefaultCommandClient.OpenStream(streamCtx, tunnel, &CommandRequest{
ID: streamID,
Method: http.MethodGet,
Path: targetPath,
- Query: c.Request.URL.RawQuery,
+ Query: req.URL.RawQuery,
Headers: headers,
}); err != nil {
slog.ErrorContext(ctx, "Failed to send WebSocket start to agent", "error", err)
- return
+ return nil
}
slog.DebugContext(ctx, "Started WebSocket stream through edge tunnel",
@@ -66,6 +66,7 @@ func ProxyWebSocketRequest(c *gin.Context, tunnel *AgentTunnel, targetPath strin
go forwardClientToAgent(ctx, streamCtx, clientWS, tunnel, streamID, clientDoneCh)
forwardAgentToClient(ctx, streamCtx, clientWS, agentDataCh, streamID, clientDoneCh)
+ return nil
}
func buildWebSocketHeaders(req *http.Request) map[string]string {
diff --git a/backend/pkg/libarcane/edge/ws_proxy_test.go b/backend/pkg/libarcane/edge/ws_proxy_test.go
index 9fb091ad8..d3e077197 100644
--- a/backend/pkg/libarcane/edge/ws_proxy_test.go
+++ b/backend/pkg/libarcane/edge/ws_proxy_test.go
@@ -8,15 +8,13 @@ import (
"testing"
"time"
- "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestProxyWebSocketRequest(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
// Custom Mock Agent Server
agentServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{}
@@ -93,12 +91,12 @@ func TestProxyWebSocketRequest(t *testing.T) {
}()
// Setup Manager
- ginRouter := gin.New()
- ginRouter.GET("/proxy-ws", func(c *gin.Context) {
- ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
+ router := echo.New()
+ router.GET("/proxy-ws", func(c echo.Context) error {
+ return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
})
- proxyServer := httptest.NewServer(ginRouter)
+ proxyServer := httptest.NewServer(router)
defer proxyServer.Close()
// Client Connect
@@ -129,8 +127,6 @@ func TestProxyWebSocketRequest(t *testing.T) {
}
func TestProxyWebSocketRequest_ClientClose(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
// Setup simple agent that just reads
agentServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{}
@@ -162,11 +158,11 @@ func TestProxyWebSocketRequest_ClientClose(t *testing.T) {
}
}()
- ginRouter := gin.New()
- ginRouter.GET("/proxy-ws", func(c *gin.Context) {
- ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
+ router := echo.New()
+ router.GET("/proxy-ws", func(c echo.Context) error {
+ return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
})
- proxyServer := httptest.NewServer(ginRouter)
+ proxyServer := httptest.NewServer(router)
defer proxyServer.Close()
proxyURL := "ws" + strings.TrimPrefix(proxyServer.URL, "http") + "/proxy-ws"
@@ -264,8 +260,6 @@ func TestSendWebSocketClose(t *testing.T) {
}
func TestHandleAgentMessage_StreamDataPreservesTextFrame(t *testing.T) {
- gin.SetMode(gin.TestMode)
-
serverConnCh := make(chan *websocket.Conn, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{}
diff --git a/backend/pkg/utils/auth.go b/backend/pkg/utils/auth.go
index e82a69c96..7a60a6a6b 100644
--- a/backend/pkg/utils/auth.go
+++ b/backend/pkg/utils/auth.go
@@ -2,6 +2,16 @@ package utils
import "slices"
+// Auth header names and path prefixes shared between the Echo middleware
+// (WebSocket/diagnostics) and the Huma auth bridge (REST). Keep these in one
+// place so a change to a header name applies to every route type at once.
+const (
+ HeaderAgentBootstrap = "X-Arcane-Agent-Bootstrap"
+ HeaderAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
+ HeaderApiKey = "X-API-Key" // #nosec G101: header name, not a credential
+ AgentPairingPrefix = "/api/environments/0/agent/pair"
+)
+
// UserHasRole reports whether the user's roles contains the given role.
func UserHasRole(roles []string, role string) bool {
return slices.Contains(roles, role)
diff --git a/backend/pkg/utils/cookie/cookie_util.go b/backend/pkg/utils/cookie/cookie_util.go
index 0778b045f..8deab1c7c 100644
--- a/backend/pkg/utils/cookie/cookie_util.go
+++ b/backend/pkg/utils/cookie/cookie_util.go
@@ -2,8 +2,6 @@ package cookie
import (
"net/http"
-
- "github.com/gin-gonic/gin"
)
var (
@@ -12,28 +10,39 @@ var (
OidcStateCookieName = "oidc_state"
)
-func isSecure(c *gin.Context) bool {
- return c.Request.TLS != nil
+func isSecure(r *http.Request) bool {
+ return r.TLS != nil
}
-func tokenCookieName(c *gin.Context) string {
- if isSecure(c) {
+func tokenCookieName(r *http.Request) string {
+ if isSecure(r) {
return TokenCookieName
}
return InsecureTokenCookieName
}
-func ClearTokenCookie(c *gin.Context) {
- name := tokenCookieName(c)
- c.SetCookie(name, "", -1, "/", "", isSecure(c), true)
+func ClearTokenCookie(w http.ResponseWriter, r *http.Request) {
+ name := tokenCookieName(r)
+ http.SetCookie(w, &http.Cookie{ // #nosec G124: Secure mirrors the request's TLS state so the clear directive matches whichever cookie variant (__Host-token vs. token) was originally set.
+ Name: name,
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
+ HttpOnly: true,
+ Secure: isSecure(r),
+ SameSite: http.SameSiteLaxMode,
+ })
}
-func GetTokenCookie(c *gin.Context) (string, error) {
- // Try secure name first, then fallback to insecure
- if v, err := c.Cookie(TokenCookieName); err == nil {
- return v, nil
+func GetTokenCookie(r *http.Request) (string, error) {
+ if c, err := r.Cookie(TokenCookieName); err == nil {
+ return c.Value, nil
+ }
+ c, err := r.Cookie(InsecureTokenCookieName)
+ if err != nil {
+ return "", err
}
- return c.Cookie(InsecureTokenCookieName)
+ return c.Value, nil
}
// BuildTokenCookieString builds a Set-Cookie header string for Huma handlers.
@@ -67,6 +76,27 @@ func BuildClearTokenCookieString() string {
return cookie.String()
}
+// BuildClearTokenCookieStringFor builds a Set-Cookie header string to clear the
+// token cookie variant matching the connection's TLS state — `__Host-token` for
+// TLS, `token` otherwise — mirroring ClearTokenCookie for callers that have no
+// http.ResponseWriter (e.g. Huma middleware).
+func BuildClearTokenCookieStringFor(secure bool) string {
+ name := InsecureTokenCookieName
+ if secure {
+ name = TokenCookieName
+ }
+ cookie := &http.Cookie{ // #nosec G124: Secure mirrors the caller-provided TLS state so the clear directive matches whichever cookie variant (__Host-token vs. token) was originally set.
+ Name: name,
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
+ HttpOnly: true,
+ Secure: secure,
+ SameSite: http.SameSiteLaxMode,
+ }
+ return cookie.String()
+}
+
// BuildOidcStateCookieString builds a Set-Cookie header string for the OIDC state cookie.
func BuildOidcStateCookieString(value string, maxAgeInSeconds int, secure bool) string {
if maxAgeInSeconds < 0 {
diff --git a/backend/pkg/utils/httpx/request.go b/backend/pkg/utils/httpx/request.go
index 9d2f386f0..4d179f08b 100644
--- a/backend/pkg/utils/httpx/request.go
+++ b/backend/pkg/utils/httpx/request.go
@@ -6,8 +6,6 @@ import (
"net/url"
"strconv"
"strings"
-
- "github.com/gin-gonic/gin"
)
// ValidateWebSocketOrigin validates the Origin header for WebSocket connections
@@ -61,30 +59,30 @@ func isLocalhost(host string) bool {
hostOnly == "[::1]"
}
-// GetQueryParam reads a string query parameter from the Gin context.
+// GetQueryParam reads a string query parameter from the request URL.
// If `required` is true and the parameter is missing or empty, an error is returned.
-func GetQueryParam(c *gin.Context, name string, required bool) (string, error) {
- v, ok := c.GetQuery(name)
- if !ok || v == "" {
+func GetQueryParam(r *http.Request, name string, required bool) (string, error) {
+ q := r.URL.Query()
+ if !q.Has(name) || q.Get(name) == "" {
if required {
return "", fmt.Errorf("missing query parameter %s", name)
}
return "", nil
}
- return v, nil
+ return q.Get(name), nil
}
-// GetIntQueryParam reads and parses an integer query parameter from the Gin context.
+// GetIntQueryParam reads and parses an integer query parameter from the request URL.
// If `required` is true and the parameter is missing, or if parsing fails, an error is returned.
-func GetIntQueryParam(c *gin.Context, name string, required bool) (int, error) {
- v, ok := c.GetQuery(name)
- if !ok || v == "" {
+func GetIntQueryParam(r *http.Request, name string, required bool) (int, error) {
+ q := r.URL.Query()
+ if !q.Has(name) || q.Get(name) == "" {
if required {
return 0, fmt.Errorf("missing numeric query parameter %s", name)
}
return 0, nil
}
- n, err := strconv.Atoi(v)
+ n, err := strconv.Atoi(q.Get(name))
if err != nil {
return 0, fmt.Errorf("invalid numeric query parameter %s: %w", name, err)
}
diff --git a/go.work.sum b/go.work.sum
index 6e656bfac..c81e45bd2 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -247,6 +247,9 @@ github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0 h1:nvj0OLI3YqYXe
github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3kj0zr8ZAKg1AQ6crr+5VwKN5eIywRkfhyM/+dE=
github.com/bwesterb/go-ristretto v1.2.3 h1:1w53tCkGhCQ5djbat3+MH0BAQ5Kfgbt56UZQ/JMzngw=
github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
+github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
+github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
+github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
@@ -280,6 +283,7 @@ github.com/cloudflare/circl v1.6.0 h1:cr5JKic4HI+LkINy2lg3W2jF8sHCVTBncJr5gIIq7q
github.com/cloudflare/circl v1.6.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 h1:F1EaeKL/ta07PY/k9Os/UFtwERei2/XzGemhpGnBKNg=
github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80=
+github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
@@ -425,9 +429,17 @@ github.com/francoispqt/gojay v1.2.13 h1:d2m3sFjloqoIUQU3TsHBgj6qg/BVGlTBeHDUmyJn
github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY=
github.com/fsouza/fake-gcs-server v1.17.0 h1:OeH75kBZcZa3ZE+zz/mFdJ2btt9FgqfjI7gIh9+5fvk=
github.com/fsouza/fake-gcs-server v1.17.0/go.mod h1:D1rTE4YCyHFNa99oyJJ5HyclvN/0uQR+pM/VdlL83bw=
+github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
+github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/getarcaneapp/arcane/types v0.0.0-20251219045603-8a9960a2bf04/go.mod h1:7Wj+0JnpYq4RQS+otyM6e4zkyJKDC01wxkWPyFCHwZA=
github.com/getsentry/raven-go v0.2.0 h1:no+xWJRb5ZI7eE8TWgIq1jLulQiIoLG0IfYxv5JYMGs=
github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ=
+github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE=
+github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
+github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
+github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
+github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
+github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-chi/chi/v5 v5.2.2 h1:CMwsvRVTbXVytCk1Wd72Zy1LAsAh9GxMmSNWLHCG618=
github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
@@ -450,6 +462,12 @@ github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2Kv
github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
+github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
+github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-rod/rod v0.116.2 h1:A5t2Ky2A+5eD/ZJQr1EfsQSe5rms5Xof/qj296e+ZqA=
github.com/go-rod/rod v0.116.2/go.mod h1:H+CMO9SCNc2TJ2WfrG+pKhITz57uGNYU43qYHh438Mg=
github.com/go-sql-driver/mysql v1.3.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
@@ -463,6 +481,7 @@ github.com/gobuffalo/here v0.6.0 h1:hYrd0a6gDmWxBM4TnrGw8mQg24iSVoIkHEk7FodQcBI=
github.com/gobuffalo/here v0.6.0/go.mod h1:wAG085dHOYqUpf+Ap+WOdrPTp5IYcDAs/x7PLa8Y5fM=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
+github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/gocql/gocql v0.0.0-20210515062232-b7ef815b4556 h1:N/MD/sr6o61X+iZBAT2qEUF023s4KbA8RWfKzl0L6MQ=
github.com/gocql/gocql v0.0.0-20210515062232-b7ef815b4556/go.mod h1:DL0ekTmBSTdlNF25Orwt/JMzqIq3EJ4MVa/J/uK64OY=
@@ -533,6 +552,7 @@ github.com/google/go-dap v0.12.1-0.20250904181021-d7a2259b058b/go.mod h1:tNjCASC
github.com/google/go-intervals v0.0.2 h1:FGrVEiUnTRKR8yE04qzXYaJMtnIYqobR5QbblK3ixcM=
github.com/google/go-intervals v0.0.2/go.mod h1:MkaR3LNRfeKLPmqgJYs4E66z5InYjmCjbbr4TQlcT6Y=
github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg=
github.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=
@@ -628,6 +648,8 @@ github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2E
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8 h1:UUHMLvzt/31azWTN/ifGWef4WUqvXk0iRqdhdy/2uzI=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
@@ -669,6 +691,8 @@ github.com/labstack/echo/v4 v4.15.0 h1:hoRTKWcnR5STXZFe9BmYun9AMTNeSbjHi2vtDuADJ
github.com/labstack/echo/v4 v4.15.0/go.mod h1:xmw1clThob0BSVRX1CRQkGQ/vjwcpOMjQZSZa9fKA/c=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
+github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
+github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA=
github.com/lestrrat-go/blackmagic v1.0.4/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
github.com/lestrrat-go/dsig v1.0.0 h1:OE09s2r9Z81kxzJYRn07TFM9XA4akrUdoMwr0L8xj38=
@@ -760,6 +784,12 @@ github.com/moby/sys/mount v0.3.4 h1:yn5jq4STPztkkzSKpZkLcmjue+bZJ0u2AuQY1iNI1Ww=
github.com/moby/sys/mount v0.3.4/go.mod h1:KcQJMbQdJHPlq5lcYT+/CjatWM4PuxKe+XLSVS4J6Os=
github.com/moby/sys/reexec v0.1.0 h1:RrBi8e0EBTLEgfruBOFcxtElzRGTEUkeIFaVXgU7wok=
github.com/moby/sys/reexec v0.1.0/go.mod h1:EqjBg8F3X7iZe5pU6nRZnYCMUTXoxsjiIfHup5wYIN8=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=
+github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs=
github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns=
@@ -827,6 +857,10 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:
github.com/prometheus/otlptranslator v0.0.2 h1:+1CdeLVrRQ6Psmhnobldo0kTp96Rj80DRXRd5OSnMEQ=
github.com/prometheus/otlptranslator v0.0.2/go.mod h1:P8AwMgdD7XEr6QRUJ2QWLpiAZTgTE2UYgjlu3svompI=
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
+github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
+github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
+github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
+github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
@@ -841,6 +875,7 @@ github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNl
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
+github.com/samber/slog-gin v1.21.1/go.mod h1:7R4VMQGENllRLLnwGyoB5nUSB+qzxThpGe5G02xla6o=
github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 h1:lZUw3E0/J3roVtGQ+SCrUrg3ON6NgVqpn3+iol9aGu4=
github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
@@ -881,11 +916,18 @@ github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xI
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 h1:pnnLyeX7o/5aX8qUQ69P/mLojDqwda8hFOCBTmP/6hw=
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6/go.mod h1:39R/xuhNgVhi+K0/zst4TLrJrVmbm6LVgl4A0+ZFS5M=
github.com/stoewer/go-strcase v1.3.0/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/sylabs/sif/v2 v2.22.0 h1:Y+xXufp4RdgZe02SR3nWEg7S6q4tPWN237WHYzkDSKA=
github.com/sylabs/sif/v2 v2.22.0/go.mod h1:W1XhWTmG1KcG7j5a3KSYdMcUIFvbs240w/MMVW627hs=
github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 h1:kdXcSzyDtseVEc4yCz2qF8ZrQvIDBJLl4S1c3GCXmoI=
@@ -913,6 +955,9 @@ github.com/tonistiigi/go-archvariant v1.0.0 h1:5LC1eDWiBNflnTF1prCiX09yfNHIxDC/a
github.com/tonistiigi/go-archvariant v1.0.0/go.mod h1:TxFmO5VS6vMq2kvs3ht04iPXtu2rUT/erOnGFYfk5Ho=
github.com/tonistiigi/jaeger-ui-rest v0.0.0-20250408171107-3dd17559e117 h1:XFwyh2JZwR5aiKLXHX2C1n0v5F11dCJpyGL1W/Cpl3U=
github.com/tonistiigi/jaeger-ui-rest v0.0.0-20250408171107-3dd17559e117/go.mod h1:3Ez1Paeg+0Ghu3KwpEGC1HgZ4CHDlg+Ez/5Baeomk54=
+github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
+github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
+github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/uptrace/bunrouter v1.0.23 h1:Bi7NKw3uCQkcA/GUCtDNPq5LE5UdR9pe+UyWbjHB/wU=
@@ -921,16 +966,12 @@ github.com/urfave/cli v1.22.17 h1:SYzXoiPfQjHBbkYxbew5prZHS1TOLT3ierW8SYLqtVQ=
github.com/urfave/cli v1.22.17/go.mod h1:b0ht0aqgH/6pBYzzxURyrM4xXNgsoT/n2ZzwQiEhNVo=
github.com/urfave/cli/v2 v2.27.7 h1:bH59vdhbjLv3LAvIu6gd0usJHgoTTPhCFib8qqOwXYU=
github.com/urfave/cli/v2 v2.27.7/go.mod h1:CyNAG/xg+iAOg0N4MPGZqVmv2rCoP267496AOXUZjA4=
-github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
-github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.62.0 h1:8dKRBX/y2rCzyc6903Zu1+3qN0H/d2MsxPPmVNamiH0=
github.com/valyala/fasthttp v1.62.0/go.mod h1:FCINgr4GKdKqV8Q0xv8b+UxPV+H/O5nNFo3D+r54Htg=
github.com/valyala/fasthttp v1.69.0 h1:fNLLESD2SooWeh2cidsuFtOcrEi4uB4m1mPrkJMZyVI=
github.com/valyala/fasthttp v1.69.0/go.mod h1:4wA4PfAraPlAsJ5jMSqCE2ug5tqUPwKXxVj8oNECGcw=
github.com/valyala/fastjson v1.6.4 h1:uAUNq9Z6ymTgGhcm0UynUAB6tlbakBrz6CQFax3BXVQ=
github.com/valyala/fastjson v1.6.4/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
-github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
-github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/vbauerster/mpb/v8 v8.10.2 h1:2uBykSHAYHekE11YvJhKxYmLATKHAGorZwFlyNw4hHM=
github.com/vbauerster/mpb/v8 v8.10.2/go.mod h1:+Ja4P92E3/CorSZgfDtK46D7AVbDqmBQRTmyTqPElo0=
github.com/vektah/gqlparser/v2 v2.5.30 h1:EqLwGAFLIzt1wpx1IPpY67DwUujF1OfzgEyDsLrN6kE=
@@ -1004,6 +1045,7 @@ go.mongodb.org/mongo-driver v1.7.5 h1:ny3p0reEpgsR2cfA5cjgwFZg3Cv/ofFh/8jbhGtz9V
go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng=
go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=
go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
+go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/contrib/detectors/gcp v1.38.0 h1:ZoYbqX7OaA/TAikspPl3ozPI6iY6LiIY9I8cUfm+pJs=
go.opentelemetry.io/contrib/detectors/gcp v1.38.0/go.mod h1:SU+iU7nu5ud4oCb3LQOhIZ3nRLj6FNVrKgtflbaf2ts=
@@ -1054,6 +1096,7 @@ go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTV
go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8=
go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
+golang.org/x/arch v0.24.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=