diff --git a/backend/go.mod b/backend/go.mod index 233e071..bba6dc1 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -12,7 +12,7 @@ require ( github.com/hashicorp/hcl/v2 v2.25.0 github.com/jackc/pgx/v5 v5.10.0 github.com/michielvha/logger v0.0.5 - github.com/michielvha/stackweaver/core v0.630.20 + github.com/michielvha/stackweaver/core v0.631.0 github.com/redis/go-redis/v9 v9.23.0 github.com/robfig/cron/v3 v3.0.1 github.com/zclconf/go-cty v1.19.0 diff --git a/backend/go.sum b/backend/go.sum index e294023..3d83ee6 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -179,8 +179,8 @@ github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/michielvha/logger v0.0.5 h1:zcepKGWRMgo32j6nU++RBWtzzz2Q5txVquGDbaSlCro= github.com/michielvha/logger v0.0.5/go.mod h1:YJjpbm0AlPmmLBFO8tPyBAruWMJisu2sPo/DX9qxKJk= -github.com/michielvha/stackweaver/core v0.630.20 h1:b+kw8LSjJfYaxo2C2Equ5OVdKgxtaxqygTzCLhdGfk8= -github.com/michielvha/stackweaver/core v0.630.20/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI= +github.com/michielvha/stackweaver/core v0.631.0 h1:FRVmsagWVTnWtfkknnjyKtvGlFssft3QFv6S1vIPoO4= +github.com/michielvha/stackweaver/core v0.631.0/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI= github.com/microsoft/go-mssqldb v1.7.2 h1:CHkFJiObW7ItKTJfHo1QX7QBBD1iV+mn1eOyRP3b/PA= github.com/microsoft/go-mssqldb v1.7.2/go.mod h1:kOvZKUdrhhFQmxLZqbwUV0rHkNkZpthMITIb2Ko1IoA= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= diff --git a/backend/internal/api/health/readiness.go b/backend/internal/api/health/readiness.go index 7650644..6f899b3 100644 --- a/backend/internal/api/health/readiness.go +++ b/backend/internal/api/health/readiness.go @@ -3,18 +3,24 @@ // Package health serves the API's probe endpoints and the healthcheck command that probes them. // // /livez reports that the process answers. /readyz reports whether the API's own database pool can -// ping Postgres within ReadinessTimeout. Neither handler logs, and no error text reaches a response. +// ping Postgres within ReadinessTimeout. Concurrent /readyz requests share one ping, and a finished +// ping answers for ReadinessResultLifetime, so readiness holds at most one pool connection however +// many callers probe it. Neither handler logs, and no error text reaches a response. package health import ( "context" "net/http" + "sync" "time" ) -// ReadinessTimeout bounds the database ping of one /readyz request, counted from the request's arrival. +// ReadinessTimeout bounds a /readyz ping, counted from the arrival of the request that started it. const ReadinessTimeout = 2 * time.Second +// ReadinessResultLifetime is how long a finished ping answers later /readyz requests without a new one. +const ReadinessResultLifetime = time.Second + // Pinger is the one method readiness needs from the API's main pool; *sql.DB satisfies it. type Pinger interface { PingContext(ctx context.Context) error @@ -25,22 +31,71 @@ var ( unavailableBody = []byte(`{"status":"unavailable","failing":["postgres"]}`) ) -// Readiness answers /readyz with one PingContext call on the pool it holds. +// Readiness answers /readyz from one PingContext call on the pool it holds, shared by every request +// that arrives while it runs and reused for ReadinessResultLifetime after it ends. type Readiness struct { pool Pinger + now func() time.Time + + mu sync.Mutex + flight *check // the ping in progress, or nil + last error // the outcome of the last finished ping + lastAt time.Time // when it finished; zero before the first +} + +// check is one ping. It runs to its own deadline whatever its callers do, so callers that leave early +// cannot make readiness start pings faster than they finish. +type check struct { + done chan struct{} // closed when err is set + err error } // NewReadiness returns the /readyz handler for the API's main pool. It opens no pool of its own. func NewReadiness(pool Pinger) *Readiness { - return &Readiness{pool: pool} + return &Readiness{pool: pool, now: time.Now} } -// ServeHTTP pings the pool under a context that ends ReadinessTimeout after the request arrived, or -// when the request is cancelled, and answers 200 on success and 503 on any error. +// ServeHTTP answers 200 when the ping succeeded and 503 when it failed. A request that leaves before +// the ping ends stops waiting; the ping goes on for the requests that arrive after it. func (r *Readiness) ServeHTTP(w http.ResponseWriter, req *http.Request) { - ctx, cancel := context.WithTimeout(req.Context(), ReadinessTimeout) - defer cancel() - if err := r.pool.PingContext(ctx); err != nil { + r.mu.Lock() + if !r.lastAt.IsZero() && r.now().Sub(r.lastAt) < ReadinessResultLifetime { + err := r.last + r.mu.Unlock() + respond(w, req, err) + return + } + c := r.flight + if c == nil { + c = &check{done: make(chan struct{})} + r.flight = c + go r.ping(context.WithoutCancel(req.Context()), c) + } + r.mu.Unlock() + + select { + case <-c.done: + respond(w, req, c.err) + case <-req.Context().Done(): + respond(w, req, req.Context().Err()) + } +} + +// ping runs one check under ReadinessTimeout and records its outcome for later requests. +func (r *Readiness) ping(parent context.Context, c *check) { + ctx, cancel := context.WithTimeout(parent, ReadinessTimeout) + err := r.pool.PingContext(ctx) + cancel() + r.mu.Lock() + c.err = err + r.flight = nil + r.last, r.lastAt = err, r.now() + r.mu.Unlock() + close(c.done) +} + +func respond(w http.ResponseWriter, req *http.Request, err error) { + if err != nil { write(w, req, http.StatusServiceUnavailable, unavailableBody) return } diff --git a/backend/internal/api/health/readiness_integration_test.go b/backend/internal/api/health/readiness_integration_test.go index 5a5b473..1f41c7d 100644 --- a/backend/internal/api/health/readiness_integration_test.go +++ b/backend/internal/api/health/readiness_integration_test.go @@ -46,6 +46,10 @@ func withApplicationName(t *testing.T, dsn, name string) string { return u.String() } +// outliveResult waits until /readyz no longer reuses the outcome of its last ping, so the next request +// sees the state the test has just set up. +func outliveResult() { time.Sleep(ReadinessResultLifetime + 50*time.Millisecond) } + func readyzStatus(t *testing.T, srvURL string) (int, time.Duration) { t.Helper() start := time.Now() @@ -126,6 +130,7 @@ func TestReadinessOnTheMainPool(t *testing.T) { t.Errorf("pg_stat_activity shows %d sessions under the pool's name, want exactly 5", sessions) } + outliveResult() code, elapsed := readyzStatus(t, srv.URL) if code != http.StatusServiceUnavailable { t.Errorf("/readyz with every connection held answered %d, want 503", code) @@ -139,20 +144,33 @@ func TestReadinessOnTheMainPool(t *testing.T) { t.Fatal(err) } held = held[1:] + outliveResult() if code, _ := readyzStatus(t, srv.URL); code != http.StatusOK { t.Errorf("/readyz after releasing one connection answered %d, want 200", code) } } -// countingPinger counts PingContext calls. -type countingPinger struct{ calls atomic.Int64 } +// countingPinger counts PingContext calls and the most that ran at once. Each call takes long enough +// for concurrent requests to overlap it. +type countingPinger struct { + calls, running, most atomic.Int64 +} func (c *countingPinger) PingContext(context.Context) error { c.calls.Add(1) + n := c.running.Add(1) + for { + m := c.most.Load() + if n <= m || c.most.CompareAndSwap(m, n) { + break + } + } + time.Sleep(20 * time.Millisecond) + c.running.Add(-1) return nil } -func TestReadinessPingsOncePerRequest(t *testing.T) { +func TestReadinessRunsOnePingAtATime(t *testing.T) { p := &countingPinger{} srv := newServer(t, p) const requests = 100 @@ -165,8 +183,11 @@ func TestReadinessPingsOncePerRequest(t *testing.T) { }) } wg.Wait() - if got := p.calls.Load(); got != requests { - t.Errorf("%d requests made %d PingContext calls, want one each", requests, got) + if got := p.most.Load(); got != 1 { + t.Errorf("%d PingContext calls ran at once for %d concurrent requests, want 1", got, requests) + } + if got := p.calls.Load(); got < 1 || got >= requests { + t.Errorf("%d concurrent requests made %d PingContext calls, want at least 1 and fewer than one each", requests, got) } } @@ -283,6 +304,7 @@ func TestReadinessOnAOneConnectionPool(t *testing.T) { t.Errorf("/readyz under refuse-new with one idle healthy connection answered %d, want 200", code) } setMode("refuse") + outliveResult() code, elapsed := readyzStatus(t, srv.URL) if code != http.StatusServiceUnavailable { t.Errorf("/readyz under refuse answered %d, want 503", code) diff --git a/backend/internal/api/health/readiness_test.go b/backend/internal/api/health/readiness_test.go index d4c65b5..d99ffd4 100644 --- a/backend/internal/api/health/readiness_test.go +++ b/backend/internal/api/health/readiness_test.go @@ -17,7 +17,8 @@ import ( type fakePinger struct { mu sync.Mutex err error - block bool // wait until the context ends, then return its error + block bool // wait until the context ends, then return its error + gate chan struct{} // when set, wait until it is closed or the context ends gotCtx context.Context received time.Time calls int @@ -28,8 +29,15 @@ func (f *fakePinger) PingContext(ctx context.Context) error { f.gotCtx = ctx f.received = time.Now() f.calls++ - block, err := f.block, f.err + block, err, gate := f.block, f.err, f.gate f.mu.Unlock() + if gate != nil { + select { + case <-gate: + case <-ctx.Done(): + return ctx.Err() + } + } if block { <-ctx.Done() return ctx.Err() @@ -43,10 +51,20 @@ func (f *fakePinger) context() context.Context { return f.gotCtx } +func (f *fakePinger) callCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls +} + func newServer(t *testing.T, p Pinger) *httptest.Server { + t.Helper() + return newServerFor(t, NewReadiness(p)) +} + +func newServerFor(t *testing.T, r *Readiness) *httptest.Server { t.Helper() mux := http.NewServeMux() - r := NewReadiness(p) mux.Handle("/readyz", r) mux.Handle("/livez", Livez()) srv := httptest.NewServer(mux) @@ -150,36 +168,41 @@ func TestReadyzTimesOutAtTwoSeconds(t *testing.T) { } } -func TestReadyzCancelledRequestCancelsPing(t *testing.T) { - p := &fakePinger{block: true} +func TestReadyzLeavingDoesNotCancelTheCheck(t *testing.T) { + p := &fakePinger{gate: make(chan struct{})} srv := newServer(t, p) - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan struct{}) - go func() { - defer close(done) - req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/readyz", http.NoBody) - resp, err := http.DefaultClient.Do(req) - if err == nil { - _ = resp.Body.Close() - } - }() - deadline := time.Now().Add(time.Second) - for p.context() == nil && time.Now().Before(deadline) { - time.Sleep(5 * time.Millisecond) + // Callers that arrive and leave at once, one after another. + for range 5 { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/readyz", http.NoBody) + if resp, err := http.DefaultClient.Do(req); err == nil { + _ = resp.Body.Close() + } + }() + waitFor(t, "the check", func() bool { return p.context() != nil }) + time.Sleep(20 * time.Millisecond) + cancel() + <-done } - if p.context() == nil { - t.Fatal("the ping never started") + if err := p.context().Err(); err != nil { + t.Fatalf("the check ended with %v after its callers left", err) } - cancel() - select { - case <-p.context().Done(): - if !errors.Is(p.context().Err(), context.Canceled) { - t.Errorf("ping context ended with %v, want context.Canceled", p.context().Err()) - } - case <-time.After(1500 * time.Millisecond): - t.Error("cancelling the request did not cancel the ping") + if got := p.callCount(); got != 1 { + t.Fatalf("callers that left started %d checks, want 1", got) + } + staying := make(chan answer, 1) + go func() { staying <- do(t, context.Background(), http.MethodGet, srv.URL+"/readyz") }() + time.Sleep(50 * time.Millisecond) + close(p.gate) + if resp := <-staying; resp.code != http.StatusOK { + t.Errorf("a caller joining the running check got %d, want 200", resp.code) + } + if got := p.callCount(); got != 1 { + t.Errorf("%d checks, want 1", got) } - <-done } func TestLivez(t *testing.T) { @@ -195,3 +218,108 @@ func TestLivez(t *testing.T) { } assertHeaders(t, resp) } + +// waitFor polls cond until it holds or a second has passed. +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +func TestReadyzConcurrentRequestsShareOneCheck(t *testing.T) { + p := &fakePinger{gate: make(chan struct{})} + srv := newServer(t, p) + const callers = 20 + codes := make(chan int, callers) + var wg sync.WaitGroup + for range callers { + wg.Add(1) + go func() { + defer wg.Done() + codes <- do(t, context.Background(), http.MethodGet, srv.URL+"/readyz").code + }() + } + waitFor(t, "the first check", func() bool { return p.callCount() >= 1 }) + time.Sleep(100 * time.Millisecond) // give the other requests time to arrive + if got := p.callCount(); got != 1 { + t.Fatalf("%d checks in flight for %d concurrent requests, want 1", got, callers) + } + close(p.gate) + wg.Wait() + close(codes) + for code := range codes { + if code != http.StatusOK { + t.Errorf("a request sharing the check answered %d, want 200", code) + } + } + if got := p.callCount(); got != 1 { + t.Errorf("%d checks for one burst of requests, want 1", got) + } +} + +func TestReadyzReusesAResultForItsLifetime(t *testing.T) { + p := &fakePinger{} + r := NewReadiness(p) + var mu sync.Mutex + now := time.Unix(1_700_000_000, 0) + r.now = func() time.Time { mu.Lock(); defer mu.Unlock(); return now } + advance := func(d time.Duration) { mu.Lock(); now = now.Add(d); mu.Unlock() } + srv := newServerFor(t, r) + get := func() answer { return do(t, context.Background(), http.MethodGet, srv.URL+"/readyz") } + + if resp := get(); resp.code != http.StatusOK || p.callCount() != 1 { + t.Fatalf("first request: %d after %d checks, want 200 after 1", resp.code, p.callCount()) + } + p.mu.Lock() + p.err = errors.New("connection refused") + p.mu.Unlock() + advance(ReadinessResultLifetime - time.Millisecond) + if resp := get(); resp.code != http.StatusOK || resp.body != wantOK || p.callCount() != 1 { + t.Errorf("within the lifetime: %d %q after %d checks, want the reused 200 after 1", resp.code, resp.body, p.callCount()) + } + advance(time.Millisecond) + resp := get() + if resp.code != http.StatusServiceUnavailable || resp.body != wantUnavailable || p.callCount() != 2 { + t.Errorf("after the lifetime: %d %q after %d checks, want 503 after 2", resp.code, resp.body, p.callCount()) + } + assertHeaders(t, resp) + if head := do(t, context.Background(), http.MethodHead, srv.URL+"/readyz"); head.code != http.StatusServiceUnavailable || head.body != "" || p.callCount() != 2 { + t.Errorf("HEAD on the reused failure: %d %q after %d checks, want 503, no body, 2 checks", head.code, head.body, p.callCount()) + } +} + +func TestReadyzOneCallerLeavingKeepsTheSharedCheck(t *testing.T) { + p := &fakePinger{gate: make(chan struct{})} + srv := newServer(t, p) + leaving, leave := context.WithCancel(context.Background()) + left := make(chan struct{}) + go func() { + defer close(left) + req, _ := http.NewRequestWithContext(leaving, http.MethodGet, srv.URL+"/readyz", http.NoBody) + if resp, err := http.DefaultClient.Do(req); err == nil { + _ = resp.Body.Close() + } + }() + waitFor(t, "the shared check", func() bool { return p.context() != nil }) + staying := make(chan answer, 1) + go func() { staying <- do(t, context.Background(), http.MethodGet, srv.URL+"/readyz") }() + time.Sleep(100 * time.Millisecond) // let the second request join + leave() + <-left + time.Sleep(50 * time.Millisecond) + if err := p.context().Err(); err != nil { + t.Fatalf("the shared check ended with %v when one of two callers left", err) + } + close(p.gate) + if resp := <-staying; resp.code != http.StatusOK { + t.Errorf("the remaining caller got %d, want 200", resp.code) + } + if got := p.callCount(); got != 1 { + t.Errorf("%d checks, want 1", got) + } +} diff --git a/backend/internal/api/v2/handlers/registry_provider_list_bounds_test.go b/backend/internal/api/v2/handlers/registry_provider_list_bounds_test.go new file mode 100644 index 0000000..fb96ccf --- /dev/null +++ b/backend/internal/api/v2/handlers/registry_provider_list_bounds_test.go @@ -0,0 +1,163 @@ +// Copyright (c) 2025 VH & Co BV. Licensed under the Business Source License 1.1. See LICENSE for details. + +//go:build integration + +package handlers + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/michielvha/stackweaver/backend/internal/api/middleware" + "github.com/michielvha/stackweaver/backend/internal/services/auth" + "github.com/michielvha/stackweaver/backend/internal/services/registry" + "github.com/michielvha/stackweaver/core/models" + "github.com/michielvha/stackweaver/core/repository" + "github.com/michielvha/stackweaver/core/storage/storagetest" + "gorm.io/gorm" +) + +type providerListPage struct { + Meta struct { + Limit int `json:"limit"` + NextOffset int `json:"next_offset"` + } `json:"meta"` + Providers []struct { + Name string `json:"name"` + } `json:"providers"` +} + +// TestRegistryProviderListPageSize: a list or search asks for at most the default page when the +// requested limit is zero or negative, as module lists do. +func TestRegistryProviderListPageSize(t *testing.T) { + db := setupTestDBForProvider(t) + var org *models.Organization + t.Cleanup(func() { + if org == nil { + return + } + db.Exec("DELETE FROM provider_versions WHERE provider_id IN (SELECT id FROM providers WHERE organization_id = ?)", org.ID) + db.Exec("DELETE FROM providers WHERE organization_id = ?", org.ID) + db.Exec("DELETE FROM organizations WHERE id = ?", org.ID) + }) + org = setupTestOrgForProvider(t, db) + prefix := "pagesize" + uuid.NewString()[:8] + for i := range 20 { + p := &models.Provider{ID: uuid.New(), OrganizationID: org.ID, Name: fmt.Sprintf("%s-%02d", prefix, i), RegistryName: "public", Namespace: org.Name} + if err := db.Create(p).Error; err != nil { + t.Fatalf("create provider: %v", err) + } + if err := db.Create(&models.ProviderVersion{ProviderID: p.ID, Version: "1.0.0", Protocols: "5.0"}).Error; err != nil { + t.Fatalf("create provider version: %v", err) + } + } + router := providerListRouter(t, db) + + for _, path := range []string{ + fmt.Sprintf("/v1/providers/%s?limit=-1", org.Name), + fmt.Sprintf("/v1/providers/%s?limit=0", org.Name), + fmt.Sprintf("/v1/providers/search?q=%s&namespace=%s&limit=-1", prefix, org.Name), + } { + page := getProviderPage(t, router, path, "") + if len(page.Providers) != 15 || page.Meta.Limit != 15 { + t.Errorf("%s: %d providers with meta limit %d, want the default page of 15", path, len(page.Providers), page.Meta.Limit) + } + } +} + +func providerListRouter(t *testing.T, gdb *gorm.DB) *gin.Engine { + t.Helper() + orgRepo := repository.NewOrganizationRepository(gdb) + storageClient := storagetest.NewMemory() + providerService := registry.NewProviderService( + repository.NewProviderRepository(gdb), repository.NewProviderVersionRepository(gdb), + repository.NewProviderPlatformRepository(gdb), repository.NewProviderDownloadRepository(gdb), + orgRepo, storageClient) + h := NewRegistryProviderHandler(providerService, repository.NewGPGKeyRepository(gdb), auth.NewService(repository.NewUserRepository(gdb)), orgRepo, storageClient, middleware.NewDBOrgResolver(gdb)) + gin.SetMode(gin.TestMode) + r := gin.New() + r.Use(func(c *gin.Context) { + if id, err := uuid.Parse(c.GetHeader("X-Test-User")); err == nil { + c.Set("user_id", id) + } + c.Next() + }) + r.GET("/v1/providers/search", h.SearchProviders) + r.GET("/v1/providers/:namespace", h.ListProviders) + return r +} + +func getProviderPage(t *testing.T, r *gin.Engine, path, user string) providerListPage { + t.Helper() + req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, path, http.NoBody) + if user != "" { + req.Header.Set("X-Test-User", user) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("%s: status %d: %s", path, w.Code, w.Body.String()) + } + var page providerListPage + if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil { + t.Fatalf("%s: parsing: %v", path, err) + } + return page +} + +// TestRegistryProviderListPagingHidesPrivateProviders: the paging of a list or search counts only +// the providers the caller may see, so a page never points past them to private ones. +func TestRegistryProviderListPagingHidesPrivateProviders(t *testing.T) { + db := setupTestDBForProvider(t) + var org *models.Organization + var member *models.User + t.Cleanup(func() { + if org != nil { + db.Exec("DELETE FROM provider_versions WHERE provider_id IN (SELECT id FROM providers WHERE organization_id = ?)", org.ID) + db.Exec("DELETE FROM providers WHERE organization_id = ?", org.ID) + db.Exec("DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE organization_id = ?)", org.ID) + db.Exec("DELETE FROM team_organization_accesses WHERE team_id IN (SELECT id FROM teams WHERE organization_id = ?)", org.ID) + db.Exec("DELETE FROM teams WHERE organization_id = ?", org.ID) + db.Exec("DELETE FROM organizations WHERE id = ?", org.ID) + } + if member != nil { + db.Exec("DELETE FROM users WHERE id = ?", member.ID) + } + }) + org = setupTestOrgForProvider(t, db) + member = &models.User{ID: uuid.New(), Email: fmt.Sprintf("u-%s@example.com", uuid.NewString()[:8]), ZitadelSubject: uuid.NewString()} + if err := db.Create(member).Error; err != nil { + t.Fatalf("create user: %v", err) + } + makeUserOrgOwner(t, db, org, member) + prefix := "paging" + uuid.NewString()[:8] + for _, reg := range []string{"public", "private"} { + p := &models.Provider{ID: uuid.New(), OrganizationID: org.ID, Name: prefix + "-" + reg, RegistryName: reg, Namespace: org.Name} + if err := db.Create(p).Error; err != nil { + t.Fatalf("create provider: %v", err) + } + if err := db.Create(&models.ProviderVersion{ProviderID: p.ID, Version: "1.0.0", Protocols: "5.0"}).Error; err != nil { + t.Fatalf("create provider version: %v", err) + } + } + router := providerListRouter(t, db) + list := fmt.Sprintf("/v1/providers/%s?limit=1", org.Name) + search := fmt.Sprintf("/v1/providers/search?q=%s&namespace=%s&limit=1", prefix, org.Name) + + for _, path := range []string{list, search} { + page := getProviderPage(t, router, path, "") + if len(page.Providers) != 1 || page.Meta.NextOffset != 0 { + t.Errorf("anonymous %s: %d providers and next_offset %d, want the one public provider and no next page", path, len(page.Providers), page.Meta.NextOffset) + } + page = getProviderPage(t, router, path, member.ID.String()) + if len(page.Providers) != 1 || page.Meta.NextOffset != 1 { + t.Errorf("member %s: %d providers and next_offset %d, want one provider and a next page at 1", path, len(page.Providers), page.Meta.NextOffset) + } + } +} diff --git a/backend/internal/api/v2/handlers/registry_providers.go b/backend/internal/api/v2/handlers/registry_providers.go index 8a9a7b0..2efb32a 100644 --- a/backend/internal/api/v2/handlers/registry_providers.go +++ b/backend/internal/api/v2/handlers/registry_providers.go @@ -48,30 +48,24 @@ func NewRegistryProviderHandler( } } -// filterAccessibleProviders keeps every public provider but drops private providers whose org -// the caller is not a member of (AUD-123), so a list/search never leaks another org's private -// provider names. Pagination counts stay based on the unfiltered query. -func (h *RegistryProviderHandler) filterAccessibleProviders(c *gin.Context, providers []models.Provider) []models.Provider { - privateOrgIDs := make([]uuid.UUID, 0, len(providers)) - for i := range providers { - if providers[i].RegistryName != "public" { - privateOrgIDs = append(privateOrgIDs, providers[i].OrganizationID) - } +// listVisible lists the providers matching f that the caller may see: every public provider, and the +// private providers of the organizations registryAccessibleOrgs grants (AUD-123). The count and the +// page come from that same set, so paging never reveals a private provider the caller cannot see. +func (h *RegistryProviderHandler) listVisible(c *gin.Context, f repository.ProviderListFilter, limit, offset int) ([]models.Provider, int64, error) { + owners, err := h.providerService.PrivateProviderOwners(f) + if err != nil { + return nil, 0, err } - accessible := registryAccessibleOrgs(c, h.authService, h.orgRepo, h.orgResolver, privateOrgIDs) - kept := make([]models.Provider, 0, len(providers)) - for _, p := range providers { - if p.RegistryName == "public" || accessible[p.OrganizationID] { - kept = append(kept, p) + accessible := registryAccessibleOrgs(c, h.authService, h.orgRepo, h.orgResolver, owners) + visible := make([]uuid.UUID, 0, len(accessible)) + for id, ok := range accessible { + if ok { + visible = append(visible, id) } } - return kept + return h.providerService.ListVisibleProviders(f, visible, limit, offset) } -// authorizeProviderRead gates a registry-protocol read/download for a resolved provider: -// a `public` provider stays anonymously reachable; a `private` one requires a Bearer token -// whose user belongs to the provider's org (AUD-123). Writes the response and returns false -// on denial. func (h *RegistryProviderHandler) authorizeProviderRead(c *gin.Context, provider *models.Provider) bool { return authorizeRegistryRead(c, h.authService, h.orgRepo, h.orgResolver, provider.OrganizationID, provider.RegistryName == "public") } @@ -109,13 +103,20 @@ func (h *RegistryProviderHandler) ListProviders(c *gin.Context) { if limit > 100 { limit = 100 } + if limit < 1 { + limit = 15 + } - providers, total, err := h.providerService.ListProviders(namespace, verified, limit, offset) + f, err := h.providerService.ProviderFilter(namespace, "", verified) + var providers []models.Provider + var total int64 + if err == nil { + providers, total, err = h.listVisible(c, f, limit, offset) + } if err != nil { jsonapi.WriteRegistryError(c, http.StatusInternalServerError, "Failed to list providers") return } - providers = h.filterAccessibleProviders(c, providers) // Format response according to Terraform Registry API spec response := RegistryProviderListResponse{ @@ -157,13 +158,20 @@ func (h *RegistryProviderHandler) SearchProviders(c *gin.Context) { if limit > 100 { limit = 100 } + if limit < 1 { + limit = 15 + } - providers, total, err := h.providerService.SearchProviders(query, namespace, verified, limit, offset) + f, err := h.providerService.ProviderFilter(namespace, query, verified) + var providers []models.Provider + var total int64 + if err == nil { + providers, total, err = h.listVisible(c, f, limit, offset) + } if err != nil { jsonapi.WriteRegistryError(c, http.StatusInternalServerError, "Failed to search providers") return } - providers = h.filterAccessibleProviders(c, providers) response := RegistryProviderListResponse{ Meta: RegistryListMeta{Limit: limit, CurrentOffset: offset}, diff --git a/backend/internal/services/registry/provider_service.go b/backend/internal/services/registry/provider_service.go index 3300f0c..e232109 100644 --- a/backend/internal/services/registry/provider_service.go +++ b/backend/internal/services/registry/provider_service.go @@ -38,34 +38,29 @@ func NewProviderService( } } -// ListProviders lists providers with optional filters -func (s *ProviderService) ListProviders(namespace string, verified *bool, limit, offset int) ([]models.Provider, int64, error) { - var organizationID *uuid.UUID - +// ProviderFilter resolves a registry list or search request to its repository filter: the namespace, +// when given, names the one organization to list. +func (s *ProviderService) ProviderFilter(namespace, query string, verified *bool) (repository.ProviderListFilter, error) { + f := repository.ProviderListFilter{Verified: verified, Query: query} if namespace != "" { org, err := s.orgRepo.GetByName(namespace) if err != nil { - return nil, 0, err + return f, err } - organizationID = &org.ID + f.OrganizationID = &org.ID } - - return s.providerRepo.List(organizationID, verified, limit, offset) + return f, nil } -// SearchProviders searches providers by keyword -func (s *ProviderService) SearchProviders(query string, namespace string, verified *bool, limit, offset int) ([]models.Provider, int64, error) { - var organizationID *uuid.UUID - - if namespace != "" { - org, err := s.orgRepo.GetByName(namespace) - if err != nil { - return nil, 0, err - } - organizationID = &org.ID - } +// PrivateProviderOwners returns the organizations owning a non-public provider that matches f. +func (s *ProviderService) PrivateProviderOwners(f repository.ProviderListFilter) ([]uuid.UUID, error) { + return s.providerRepo.PrivateOwners(f) +} - return s.providerRepo.Search(query, organizationID, verified, limit, offset) +// ListVisibleProviders lists the providers matching f that are public or belong to privateOrgs, with +// the total of that set. +func (s *ProviderService) ListVisibleProviders(f repository.ProviderListFilter, privateOrgs []uuid.UUID, limit, offset int) ([]models.Provider, int64, error) { + return s.providerRepo.ListVisible(f, privateOrgs, limit, offset) } // GetProvider gets a provider by namespace and name