Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions backend/cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
}
7 changes: 5 additions & 2 deletions backend/internal/api/v2/routes/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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)
Expand Down
160 changes: 160 additions & 0 deletions backend/internal/services/auth/runner_lookup_cap_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading