diff --git a/backend/cmd/api/main.go b/backend/cmd/api/main.go index 2ded462..df1713b 100644 --- a/backend/cmd/api/main.go +++ b/backend/cmd/api/main.go @@ -578,6 +578,9 @@ func main() { // Initialize auth service authService := auth.NewService(userRepo) + // Launcher credential checks may hold a quarter of the pool at once, so requests with unknown + // credentials on the runner routes cannot take the connections other requests need. + authService.LimitRunnerLookups(auth.RunnerLookupCap(config.Database.MaxOpenConns)) // Initialize Zitadel verifier // Prefer environment variables over config file values diff --git a/backend/internal/api/v2/routes/anonymous_body_caps_integration_test.go b/backend/internal/api/v2/routes/anonymous_body_caps_integration_test.go new file mode 100644 index 0000000..9a41e67 --- /dev/null +++ b/backend/internal/api/v2/routes/anonymous_body_caps_integration_test.go @@ -0,0 +1,95 @@ +// Copyright (c) 2025 VH & Co BV. Licensed under the Business Source License 1.1. See LICENSE for details. + +//go:build integration + +package routes_test + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + v2routes "github.com/michielvha/stackweaver/backend/internal/api/v2/routes" + "github.com/michielvha/stackweaver/core/dbtest" + "github.com/michielvha/stackweaver/core/services/vcs" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +// TestAnonymousBodyCaps: the two routes a caller reaches without a credential and that read a body +// before checking anything refuse an oversized body first, on the production router. +func TestAnonymousBodyCaps(t *testing.T) { + dbURL := os.Getenv("TEST_DATABASE_URL") + if dbURL == "" { + t.Skip("TEST_DATABASE_URL not set - skipping integration test") + } + t.Setenv("DEV_INSECURE_KEY", "1") + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + t.Setenv("GITHUB_APP_ID", "1") + t.Setenv("GITHUB_APP_NAME", "body-cap-test") + t.Setenv("GITHUB_APP_PRIVATE_KEY", string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}))) + t.Setenv("GITHUB_WEBHOOK_SECRET", "body-cap-test-secret") + manager, err := vcs.NewGitHubAppManager() + if err != nil || !manager.IsEnabled() { + t.Fatalf("an enabled GitHub App manager is needed for the webhook route: %v", err) + } + db, err := dbtest.Open(t, dbURL, &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + if err != nil { + t.Fatalf("connect test db: %v", err) + } + gin.SetMode(gin.TestMode) + r := gin.New() + v2routes.SetupV2Routes(r, db, nil, manager) + + send := func(path string, body io.Reader, length int64) int { + req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, path, body) + req.Header.Set("Content-Type", "application/json") + req.ContentLength = length + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w.Code + } + padded := func(size int) []byte { + head := `{"host_config_key":"k","pad":"` + return []byte(head + strings.Repeat("a", size-len(head)-2) + `"}`) + } + callback := "/api/v2/ansible/job-templates/" + uuid.NewString() + "/callback" + webhook := "/api/v2/vcs-connections/github/webhook" + + const callbackCap, webhookCap = 64 << 10, 25 << 20 + big := padded(callbackCap + 1) + if got := send(callback, bytes.NewReader(big), int64(len(big))); got != http.StatusRequestEntityTooLarge { + t.Errorf("callback with a %d byte body answered %d, want 413", len(big), got) + } + // A chunked body declares no length; it must still be cut off before the template lookup, + // which would answer 404 for this unknown template. + if got := send(callback, bytes.NewReader(big), -1); got == http.StatusNotFound { + t.Errorf("chunked oversized callback reached the template lookup (404)") + } + small := padded(256) + if got := send(callback, bytes.NewReader(small), int64(len(small))); got != http.StatusNotFound { + t.Errorf("callback with a small body answered %d, want 404 for the unknown template", got) + } + + huge := bytes.Repeat([]byte("a"), webhookCap+1) + if got := send(webhook, bytes.NewReader(huge), int64(len(huge))); got != http.StatusRequestEntityTooLarge { + t.Errorf("webhook with a %d byte body answered %d, want 413", len(huge), got) + } + if got := send(webhook, bytes.NewReader([]byte(`{}`)), 2); got != http.StatusUnauthorized { + t.Errorf("unsigned webhook with a small body answered %d, want 401 from the signature check", got) + } +} diff --git a/backend/internal/api/v2/routes/routes.go b/backend/internal/api/v2/routes/routes.go index bd1614a..d007482 100644 --- a/backend/internal/api/v2/routes/routes.go +++ b/backend/internal/api/v2/routes/routes.go @@ -1111,7 +1111,9 @@ func SetupV2Routes( repository.NewAnsibleJobTemplateRepository(db), newWebhookTemplateLaunchService(db, ansibleQueueForWebhook, vcsRegistry, vcsConnectionRepo), ) - vcsWebhook.POST("/webhook", appHandler.HandleInstallationWebhook) + // GitHub sends no delivery above 25 MB, so a larger body is refused before it is read + // and before the signature check. + vcsWebhook.POST("/webhook", middleware.MaxBodyBytes(25<<20), appHandler.HandleInstallationWebhook) } } @@ -1460,7 +1462,8 @@ func SetupV2Routes( repository.NewAnsibleInventoryRepository(db), ansibleServices.JobService, ) - r.POST("/api/v2/ansible/job-templates/:id/callback", provisioningCallbackHandler.Handle) + // The body is one short key, so anything past 64 KiB is refused before it is read. + r.POST("/api/v2/ansible/job-templates/:id/callback", middleware.MaxBodyBytes(64<<10), provisioningCallbackHandler.Handle) // ========================================== // Runner Agent API (for self-hosted runners) diff --git a/backend/internal/services/auth/runner_lookup_cap_test.go b/backend/internal/services/auth/runner_lookup_cap_test.go new file mode 100644 index 0000000..6859696 --- /dev/null +++ b/backend/internal/services/auth/runner_lookup_cap_test.go @@ -0,0 +1,160 @@ +// Copyright (c) 2026 VH & Co BV. Licensed under the Business Source License 1.1. See LICENSE for details. + +package auth + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/michielvha/logger" + "github.com/michielvha/stackweaver/core/models" +) + +// gatedVerifier holds every credential lookup until gate closes, and records how many ran at once. +type gatedVerifier struct { + gate chan struct{} + key *models.APIKey // returned once the gate opens; nil means the token is unknown + running, most atomic.Int64 +} + +func (v *gatedVerifier) VerifyAPIKey(string) (*models.APIKey, error) { + n := v.running.Add(1) + for { + m := v.most.Load() + if n <= m || v.most.CompareAndSwap(m, n) { + break + } + } + <-v.gate + v.running.Add(-1) + if v.key == nil { + return nil, errors.New("invalid api key") + } + return v.key, nil +} +func (*gatedVerifier) UpdateLastUsed(uuid.UUID) error { return nil } +func (*gatedVerifier) IsTeamMember(uuid.UUID, uuid.UUID) (bool, error) { return false, nil } +func (*gatedVerifier) ActiveAPIKey(uuid.UUID) (*models.APIKey, error) { return nil, errors.New("none") } + +func capRouter(s *Service, handler gin.HandlerFunc) *gin.Engine { + // The API initializes its logger at startup; do the same before requests run concurrently, since + // the logger's lazy initialization on first use is not safe for concurrent callers. + logger.Get() + gin.SetMode(gin.TestMode) + r := gin.New() + r.Use(s.AuthenticateMiddleware()) + r.GET("/api/v2/runner/heartbeat", handler) + r.GET("/api/v2/organizations", handler) + return r +} + +func bearer(r *gin.Engine, path string) *httptest.ResponseRecorder { + req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, path, http.NoBody) + req.Header.Set("Authorization", "Bearer tfe-unknown-token") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w +} + +// burst sends n concurrent requests to path, opens the gate after hold, and returns the status codes. +func burst(r *gin.Engine, v *gatedVerifier, path string, n int, hold time.Duration) map[int]int { + var mu sync.Mutex + codes := map[int]int{} + var wg sync.WaitGroup + for range n { + wg.Add(1) + go func() { + defer wg.Done() + w := bearer(r, path) + mu.Lock() + codes[w.Code]++ + mu.Unlock() + }() + } + time.Sleep(hold) + close(v.gate) + wg.Wait() + return codes +} + +func TestRunnerCredentialLookupsAreCapped(t *testing.T) { + v := &gatedVerifier{gate: make(chan struct{})} + s := &Service{apiKeyService: v} + s.LimitRunnerLookups(2) + codes := burst(capRouter(s, func(c *gin.Context) { c.Status(http.StatusOK) }), v, "/api/v2/runner/heartbeat", 10, RunnerLookupWait+500*time.Millisecond) + if got := v.most.Load(); got != 2 { + t.Errorf("%d runner credential lookups ran at once with a cap of 2", got) + } + if codes[http.StatusUnauthorized] != 2 || codes[http.StatusServiceUnavailable] != 8 { + t.Errorf("answers %v, want 2 unknown-token 401s and 8 503s for the requests that found no free slot", codes) + } +} + +func TestRunnerLookupCapAnswersRetryAfter(t *testing.T) { + v := &gatedVerifier{gate: make(chan struct{})} + s := &Service{apiKeyService: v} + s.LimitRunnerLookups(1) + r := capRouter(s, func(c *gin.Context) { c.Status(http.StatusOK) }) + go bearer(r, "/api/v2/runner/heartbeat") // holds the only slot until the gate opens + time.Sleep(50 * time.Millisecond) + done := make(chan *httptest.ResponseRecorder, 1) + go func() { done <- bearer(r, "/api/v2/runner/heartbeat") }() + var w *httptest.ResponseRecorder + select { + case w = <-done: + case <-time.After(RunnerLookupWait + time.Second): + } + close(v.gate) + if w == nil { + t.Fatal("a request with no free slot did not answer within the wait") + } + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "1" { + t.Errorf("a request with no free slot got %d with Retry-After %q, want 503 with Retry-After 1", w.Code, w.Header().Get("Retry-After")) + } +} + +func TestOtherPathsAreNotCapped(t *testing.T) { + v := &gatedVerifier{gate: make(chan struct{})} + s := &Service{apiKeyService: v} + s.LimitRunnerLookups(2) + codes := burst(capRouter(s, func(c *gin.Context) { c.Status(http.StatusOK) }), v, "/api/v2/organizations", 10, 300*time.Millisecond) + if got := v.most.Load(); got != 10 { + t.Errorf("%d lookups ran at once outside /api/v2/runner/, want all 10", got) + } + if codes[http.StatusUnauthorized] != 10 { + t.Errorf("answers %v, want 10 unknown-token 401s", codes) + } +} + +// A handler that holds its request, as a long-polled heartbeat does, keeps no lookup slot. +func TestRunnerLookupSlotIsReleasedBeforeTheHandler(t *testing.T) { + userID, orgID := uuid.New(), uuid.New() + key := &models.APIKey{ID: uuid.New(), UserID: &userID, Kind: models.APIKeyKindOrg, OrganizationID: &orgID} + v := &gatedVerifier{gate: make(chan struct{}), key: key} + close(v.gate) + s := NewServiceWithLookups(&mockUserRepo{getByIDFn: func(uuid.UUID) (*models.User, error) { + return &models.User{ID: userID, Email: "runner@example.com"}, nil + }}) + s.SetAPIKeyService(v) + s.LimitRunnerLookups(1) + release := make(chan struct{}) + r := capRouter(s, func(c *gin.Context) { <-release; c.Status(http.StatusOK) }) + held := make(chan int, 1) + go func() { held <- bearer(r, "/api/v2/runner/heartbeat").Code }() + time.Sleep(100 * time.Millisecond) + second := make(chan int, 1) + go func() { second <- bearer(r, "/api/v2/runner/heartbeat").Code }() + time.Sleep(100 * time.Millisecond) + close(release) + if a, b := <-held, <-second; a != http.StatusOK || b != http.StatusOK { + t.Errorf("two authenticated requests whose handlers overlap got %d and %d, want both 200 with a cap of 1", a, b) + } +} diff --git a/backend/internal/services/auth/service.go b/backend/internal/services/auth/service.go index 29c9416..1bbb552 100644 --- a/backend/internal/services/auth/service.go +++ b/backend/internal/services/auth/service.go @@ -10,6 +10,7 @@ import ( "fmt" "net/http" "strings" + "time" "github.com/gin-gonic/gin" "github.com/google/uuid" @@ -101,6 +102,7 @@ type Service struct { clientID string sessions *Sessions sessionCheck func(*http.Request) error + runnerLookups chan struct{} // slots for /api/v2/runner/ credential checks; nil means uncapped } // CodeAuthenticationRequired is the JSON:API error `code` of a 401 that means the browser has no @@ -450,6 +452,46 @@ func logTokenFromPath(path string) string { return parts[3] } +// RunnerLookupWait is how long a /api/v2/runner/ request waits for a free credential lookup slot +// before it is answered 503. +const RunnerLookupWait = time.Second + +// LimitRunnerLookups caps the credential lookups that /api/v2/runner/ requests run at once, so +// requests with unknown credentials cannot hold more database connections than the cap however many +// addresses send them. A slot is held only while the credential is checked, never while the handler +// runs, so a long-polled heartbeat keeps none. A non-positive n leaves the lookups uncapped. +func (s *Service) LimitRunnerLookups(n int) { + if n > 0 { + s.runnerLookups = make(chan struct{}, n) + } +} + +// RunnerLookupCap is the cap for a database pool of maxOpen connections: a quarter of the pool, at +// least one, so runner credential checks leave most connections to other requests. +func RunnerLookupCap(maxOpen int) int { + return max(1, maxOpen/4) +} + +// acquireRunnerLookup takes a credential lookup slot for a /api/v2/runner/ request. It waits up to +// RunnerLookupWait; with no free slot it answers 503 with Retry-After and reports false. +func (s *Service) acquireRunnerLookup(c *gin.Context) (release func(), ok bool) { + if s.runnerLookups == nil || !strings.HasPrefix(c.Request.URL.Path, "/api/v2/runner/") { + return func() {}, true + } + t := time.NewTimer(RunnerLookupWait) + defer t.Stop() + select { + case s.runnerLookups <- struct{}{}: + return func() { <-s.runnerLookups }, true + case <-t.C: + case <-c.Request.Context().Done(): + } + c.Header("Retry-After", "1") + jsonapi.WriteError(c, http.StatusServiceUnavailable, "Service Unavailable", "too many credential checks in progress; retry shortly") + c.Abort() + return nil, false +} + func (s *Service) AuthenticateMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // Skip authentication for OPTIONS requests (CORS preflight) @@ -457,82 +499,92 @@ func (s *Service) AuthenticateMiddleware() gin.HandlerFunc { c.Next() return } - - // TFE-compatible: the run log routes also take a credential in ?token=, either a credential - // itself or the run-bound log token of a log-read-url. Both are authenticated here exactly as - // a header credential is, so the org wall and every permission check judge them the same - // way; a log token re-establishes the credential it was minted for, as that credential - // stands now. - // The log-read-url's own form carries the log token in its path. Only a log token is - // accepted there, never a credential itself. - if pathToken := logTokenFromPath(c.Request.URL.Path); pathToken != "" { - err := error(&AuthError{Status: http.StatusUnauthorized, Title: "Unauthorized", Detail: "invalid or revoked log token"}) - if cred, ok := logtoken.Verify(pathToken, runIDFromLogPath(c.Request.URL.Path)); ok { - err = s.authenticateLogToken(c, cred) - } - if err != nil { - writeAuthError(c, err) - c.Abort() - return - } - c.Next() + release, ok := s.acquireRunnerLookup(c) + if !ok { return } + ok = s.authenticate(c) + release() + if ok { + c.Next() + } + } +} - if isRunLogPath(c.Request.URL.Path) && c.Query("token") != "" { - tokenFromQuery := c.Query("token") - err := s.Authenticate(c, tokenFromQuery) - if err != nil { - if cred, ok := logtoken.Verify(tokenFromQuery, runIDFromLogPath(c.Request.URL.Path)); ok { - err = s.authenticateLogToken(c, cred) - } - } - if err == nil { - c.Next() - return - } - if c.GetHeader("Authorization") == "" { - writeAuthError(c, err) - c.Abort() - return - } +// authenticate checks the request's credential and reports whether it may proceed; on false it has +// written the refusal and aborted. +func (s *Service) authenticate(c *gin.Context) bool { + // TFE-compatible: the run log routes also take a credential in ?token=, either a credential + // itself or the run-bound log token of a log-read-url. Both are authenticated here exactly as + // a header credential is, so the org wall and every permission check judge them the same + // way; a log token re-establishes the credential it was minted for, as that credential + // stands now. + // The log-read-url's own form carries the log token in its path. Only a log token is + // accepted there, never a credential itself. + if pathToken := logTokenFromPath(c.Request.URL.Path); pathToken != "" { + err := error(&AuthError{Status: http.StatusUnauthorized, Title: "Unauthorized", Detail: "invalid or revoked log token"}) + if cred, ok := logtoken.Verify(pathToken, runIDFromLogPath(c.Request.URL.Path)); ok { + err = s.authenticateLogToken(c, cred) } + if err != nil { + writeAuthError(c, err) + c.Abort() + return false + } + return true + } - // Extract token from Authorization header (standard TFE authentication) - authHeader := c.GetHeader("Authorization") - if authHeader == "" { - // A request with no Authorization header is the browser's: its credential is the session - // cookie, and with none it has no credential at all. Both refusals carry the code the - // SPA signs out on. A request that does carry a header is judged by that header alone, - // so a valid cookie never rescues an invalid bearer token. - if err := s.authenticateSession(c); err != nil { - var authErr *AuthError - if !errors.As(err, &authErr) { - authErr = &AuthError{Status: http.StatusUnauthorized, Title: "Unauthorized", Detail: "not signed in"} - } - jsonapi.WriteCodedError(c, authErr.Status, authErr.Code, authErr.Title, authErr.Detail) - c.Abort() - return + if isRunLogPath(c.Request.URL.Path) && c.Query("token") != "" { + tokenFromQuery := c.Query("token") + err := s.Authenticate(c, tokenFromQuery) + if err != nil { + if cred, ok := logtoken.Verify(tokenFromQuery, runIDFromLogPath(c.Request.URL.Path)); ok { + err = s.authenticateLogToken(c, cred) } - c.Next() - return } - - // Check for Bearer token - parts := strings.SplitN(authHeader, " ", 2) - if len(parts) != 2 || parts[0] != "Bearer" { - jsonapi.WriteError(c, http.StatusUnauthorized, "Unauthorized", "invalid authorization header format") + if err == nil { + return true + } + if c.GetHeader("Authorization") == "" { + writeAuthError(c, err) c.Abort() - return + return false } + } - if err := s.Authenticate(c, parts[1]); err != nil { - writeAuthError(c, err) + // Extract token from Authorization header (standard TFE authentication) + authHeader := c.GetHeader("Authorization") + if authHeader == "" { + // A request with no Authorization header is the browser's: its credential is the session + // cookie, and with none it has no credential at all. Both refusals carry the code the + // SPA signs out on. A request that does carry a header is judged by that header alone, + // so a valid cookie never rescues an invalid bearer token. + if err := s.authenticateSession(c); err != nil { + var authErr *AuthError + if !errors.As(err, &authErr) { + authErr = &AuthError{Status: http.StatusUnauthorized, Title: "Unauthorized", Detail: "not signed in"} + } + jsonapi.WriteCodedError(c, authErr.Status, authErr.Code, authErr.Title, authErr.Detail) c.Abort() - return + return false } - c.Next() + return true + } + + // Check for Bearer token + parts := strings.SplitN(authHeader, " ", 2) + if len(parts) != 2 || parts[0] != "Bearer" { + jsonapi.WriteError(c, http.StatusUnauthorized, "Unauthorized", "invalid authorization header format") + c.Abort() + return false + } + + if err := s.Authenticate(c, parts[1]); err != nil { + writeAuthError(c, err) + c.Abort() + return false } + return true } func (s *Service) GetUserID(ctx context.Context) (uuid.UUID, error) {