package equipotest import ( "net/http" "net/http/httptest" "strings" "testing" "amadan.net/oficina/equipo/internal/equipo" "github.com/go-chi/chi/v5" ) func TestRunnerAppCSRF(t *testing.T) { f := runnerFixtureNew(t, false) token := runnerBearerFor(t, f) cfg := testConfig(testOrigin) cfg.ExecutionEnabled = true app, err := equipo.AppWithExecution(f.d, cfg, &capturingMailer{}, nil, f.x) executionMust(t, err) request := func(path, body, bearer, cookie, origin string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") if bearer != "" { req.Header.Set("Authorization", "Bearer "+bearer) } if cookie != "" { req.Header.Set("Cookie", cookie) } if origin != "" { req.Header.Set("Origin", origin) } response := httptest.NewRecorder() app.ServeHTTP(response, req) return response } executionMust(t, chi.Walk(f.s.RunnerHandler().(chi.Routes), func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { if method != http.MethodPost { return nil } t.Run(route, func(t *testing.T) { response := request("/api/runner/v2"+route, "{", token, "", "") if response.Code != http.StatusUnprocessableEntity || !strings.Contains(response.Body.String(), "form.invalid") { t.Fatalf("bearer request blocked before runner body validation: %d %s", response.Code, response.Body) } for _, bearer := range []string{"", token} { response = request("/api/runner/v2"+route, "{}", bearer, "rastrillo_session=browser", "") if response.Code != http.StatusForbidden || !strings.Contains(response.Body.String(), "form.forbidden") { t.Fatalf("cookie request bypassed runner authentication: %d %s", response.Code, response.Body) } } }) return nil })) t.Run("heartbeat", func(t *testing.T) { response := request("/api/runner/v2/heartbeat", `{"version":2,"request_id":"csrf-heartbeat"}`, token, "", "") if response.Code != http.StatusOK { t.Fatalf("heartbeat: %d %s", response.Code, response.Body) } }) for _, path := range []string{"/projects", "/auth/begin", "/runners/enrol", "/api/runner/v2/poll/extra"} { t.Run("browser"+path, func(t *testing.T) { response := request(path, "{}", "", "rastrillo_session=browser", "https://other.example") if response.Code != http.StatusForbidden || !strings.Contains(response.Body.String(), "cross-origin form submission refused") { t.Fatalf("cross-origin form accepted: %d %s", response.Code, response.Body) } }) } for _, path := range []string{"/api/enrolments", "/api/enrolments/token"} { t.Run(path, func(t *testing.T) { response := request(path, "{", "", "", "") if response.Code != http.StatusUnprocessableEntity { t.Fatalf("device client blocked: %d %s", response.Code, response.Body) } }) } }