Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: add global csrf middleware (#2780)
Kyle Mendellc922327c21f8
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex 3f2fc05fe..829a82235 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -144,6 +144,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *di.ServicauthMiddleware := appServices.AuthMiddlewaree.Use(middleware.NewCORSMiddleware(cfg).Add())+ e.Use(middleware.NewCSRFMiddleware(cfg).Add()) //nolint:contextcheck // Echo middleware uses request context from echo.Context, not the app lifecycle context.apiGroup := e.Group("/api")diff --git a/backend/internal/middleware/csrf_middleware.go b/backend/internal/middleware/csrf_middleware.gonew file mode 100644index 000000000..6707e9eb2--- /dev/null+++ b/backend/internal/middleware/csrf_middleware.go@@ -0,0 +1,91 @@+package middleware++import (+ "log/slog"+ "net/http"+ "strings"++ "github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/models"+ pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"+ "github.com/labstack/echo/v4"+)++// publicCrossOriginBypassPaths are endpoints intentionally reachable cross-origin+// by non-browser callers that authenticate with their OWN token carried in the+// path or request body (not the session cookie). Cross-origin protection must not+// block them, since a legitimate external caller (CI, webhook source) may attach+// an Origin header. Patterns use net/http ServeMux syntax, matched against URL path.+var publicCrossOriginBypassPaths = []string{+ "/api/webhooks/trigger/{token}",+ "/api/auth/federated/token",+}++// CSRFMiddleware rejects cross-origin state-changing requests to the cookie-backed+// API. It complements the SameSite=Lax session cookie with server-side origin+// verification (Sec-Fetch-Site, with an Origin/Host fallback) via the standard+// library's net/http.CrossOriginProtection.+//+// Header-credentialed requests (Bearer / X-API-Key / agent token) are not CSRF-able+// — a browser cannot attach those headers to a forged cross-origin request — so they+// are left untouched, as are non-browser clients that send no Origin header.+type CSRFMiddleware struct {+ cfg *config.Config+}++func NewCSRFMiddleware(cfg *config.Config) *CSRFMiddleware {+ return &CSRFMiddleware{cfg: cfg}+}++func (m *CSRFMiddleware) Add() echo.MiddlewareFunc {+ // Edge Agent mode: skip. The agent only receives server-to-server requests+ // through the edge tunnel from the manager — never from browsers. Mirrors CORSMiddleware.+ if m.cfg != nil && m.cfg.EdgeAgent {+ return func(next echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error { return next(c) }+ }+ }++ cop := http.NewCrossOriginProtection()+ for _, origin := range deriveAllowedOriginsInternal(m.cfg, nil) {+ // AddTrustedOrigin expects scheme://host[:port]; deriveAllowedOriginsInternal+ // already produces that form (shared with CORS). Skip anything malformed.+ if err := cop.AddTrustedOrigin(origin); err != nil {+ slog.Warn("CSRF: ignoring invalid trusted origin", "origin", origin, "error", err)+ }+ }+ for _, pattern := range publicCrossOriginBypassPaths {+ cop.AddInsecureBypassPattern(pattern)+ }++ return func(next echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ req := c.Request()+ if hasHeaderCredentialInternal(req) {+ return next(c)+ }+ if err := cop.Check(req); err != nil {+ slog.WarnContext(req.Context(), "CSRF: cross-origin request blocked",+ "path", req.URL.Path,+ "method", req.Method,+ "origin", req.Header.Get("Origin"),+ "sec_fetch_site", req.Header.Get("Sec-Fetch-Site"),+ )+ return c.JSON(http.StatusForbidden, models.APIError{+ Code: models.APIErrorCodeForbidden,+ Message: "Cross-origin request blocked",+ })+ }+ return next(c)+ }+ }+}++// hasHeaderCredentialInternal reports whether the request carries a credential in a+// header that a browser cannot forge on a cross-origin request, meaning it is not+// susceptible to CSRF and should bypass the cross-origin check.+func hasHeaderCredentialInternal(req *http.Request) bool {+ return strings.HasPrefix(req.Header.Get("Authorization"), "Bearer ") ||+ req.Header.Get(pkgutils.HeaderApiKey) != "" ||+ req.Header.Get(pkgutils.HeaderAgentToken) != ""+}diff --git a/backend/internal/middleware/csrf_middleware_test.go b/backend/internal/middleware/csrf_middleware_test.gonew file mode 100644index 000000000..c66fc0a70--- /dev/null+++ b/backend/internal/middleware/csrf_middleware_test.go@@ -0,0 +1,74 @@+package middleware++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/labstack/echo/v4"+ "github.com/stretchr/testify/require"+)++func newCSRFTestRouterInternal() *echo.Echo {+ cfg := &config.Config{Environment: "production", AppUrl: "https://arcane.example.com"}+ router := echo.New()+ router.Use(NewCSRFMiddleware(cfg).Add())+ router.POST("/api/test", func(c echo.Context) error { return c.NoContent(http.StatusOK) })+ router.POST("/api/webhooks/trigger/:token", func(c echo.Context) error { return c.NoContent(http.StatusOK) })+ return router+}++func TestCSRF_BlocksCrossSiteStateChange(t *testing.T) {+ router := newCSRFTestRouterInternal()+ req := httptest.NewRequest(http.MethodPost, "/api/test", nil)+ req.Header.Set("Sec-Fetch-Site", "cross-site")+ req.Header.Set("Origin", "https://evil.example.com")+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusForbidden, rec.Code)+}++func TestCSRF_AllowsSameOrigin(t *testing.T) {+ router := newCSRFTestRouterInternal()+ req := httptest.NewRequest(http.MethodPost, "/api/test", nil)+ req.Header.Set("Sec-Fetch-Site", "same-origin")+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+}++// Non-browser clients (curl, CLI, CI, the report's Python PoC) send no Origin or+// Sec-Fetch-Site header and must not be blocked.+func TestCSRF_AllowsNonBrowserClient(t *testing.T) {+ router := newCSRFTestRouterInternal()+ req := httptest.NewRequest(http.MethodPost, "/api/test", nil)+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+}++// A header credential cannot be forged cross-origin by a browser, so even a+// cross-site Origin must not block such a request.+func TestCSRF_SkipsHeaderCredentialedRequests(t *testing.T) {+ router := newCSRFTestRouterInternal()+ req := httptest.NewRequest(http.MethodPost, "/api/test", nil)+ req.Header.Set("Sec-Fetch-Site", "cross-site")+ req.Header.Set("Origin", "https://evil.example.com")+ req.Header.Set("X-Api-Key", "some-key")+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+}++// Public webhook trigger authenticates via its path token, not the session cookie,+// and may receive an Origin header from an external caller; it must be bypassed.+func TestCSRF_AllowsPublicBypassPaths(t *testing.T) {+ router := newCSRFTestRouterInternal()+ req := httptest.NewRequest(http.MethodPost, "/api/webhooks/trigger/abc", nil)+ req.Header.Set("Sec-Fetch-Site", "cross-site")+ req.Header.Set("Origin", "https://ci.example.com")+ rec := httptest.NewRecorder()+ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+}diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.tsindex ca60ffa01..76e39d993 100644--- a/tests/spec/project.spec.ts+++ b/tests/spec/project.spec.ts@@ -562,6 +562,8 @@ test.describe('New Compose Project Page', () => {});test('should create a new project successfully', async ({ page }) => {+ test.slow();+const projectName = `test-project-${Date.now()}`;const containerName = `test-nginx-container-${Date.now()}`;const envFile = TEST_ENV_FILE.replace(/CONTAINER_NAME=.*/m, `CONTAINER_NAME=${containerName}`);@@ -654,10 +656,24 @@ test.describe('New Compose Project Page', () => {.getByRole('button', { name: 'Up', exact: true }).filter({ hasText: 'Up' }).last();+ const deployResponsePromise = page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ /\/api\/environments\/[^/]+\/projects\/[^/]+\/up$/.test(getPathname(response.url()))+ );await deployButton.click();- await page.waitForTimeout(5000);- await page.waitForLoadState('load');+ const deployResponse = await deployResponsePromise;+ expect(deployResponse.ok()).toBe(true);+ expect(await deployResponse.finished()).toBeNull();++ const projectId = createdProjectId ?? getProjectIdFromPageUrl(page.url());+ await expect+ .poll(async () => (await fetchProjectDetail(page, projectId))?.status, {+ message: 'Expected project to be running after deploy',+ timeout: 60000+ })+ .toBe('running');expect(projectPullRequestCount).toBe(0);await expect(page.getByText('Running', { exact: true }).first()).toBeVisible({