From c6b529da8ad3ac840210a518ad4af3485e13122f Mon Sep 17 00:00:00 2001 From: "stackweaver-release-bot[bot]" <287320289+stackweaver-release-bot@users.noreply.github.com> Date: Fri, 4 Dec 2026 18:12:32 +0000 Subject: [PATCH] chore(deps): bump core module to v0.631.4 --- backend/go.mod | 2 +- backend/go.sum | 4 +- .../handlers/ansible/inventories_sync_test.go | 47 +++++++++++ .../v2/handlers/identity_bindings_org_test.go | 10 +++ .../project_delete_inventories_test.go | 75 ++++++++++++++++++ backend/internal/api/v2/handlers/projects.go | 49 ++++-------- ...t_work_items_artifacts_integration_test.go | 77 +++++++++++++++++-- .../internal/api/v2/jsonapi/page_params.go | 7 +- .../api/v2/jsonapi/pagination_test.go | 15 ++++ 9 files changed, 241 insertions(+), 45 deletions(-) diff --git a/backend/go.mod b/backend/go.mod index 1b601a2a..093393a4 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.631.3 + github.com/michielvha/stackweaver/core v0.631.4 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 b73f0299..1ca409db 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.631.3 h1:G91gL57c6wMYDP5PdAv9LxQL+z8h/yGnIvgy15sNH/A= -github.com/michielvha/stackweaver/core v0.631.3/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI= +github.com/michielvha/stackweaver/core v0.631.4 h1:UJ9fJ5l0h0K0wXZJZDmmFJ7vtjciB9Qn8e4zo84F/Ic= +github.com/michielvha/stackweaver/core v0.631.4/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/v2/handlers/ansible/inventories_sync_test.go b/backend/internal/api/v2/handlers/ansible/inventories_sync_test.go index a3c63a42..e28fc9c6 100644 --- a/backend/internal/api/v2/handlers/ansible/inventories_sync_test.go +++ b/backend/internal/api/v2/handlers/ansible/inventories_sync_test.go @@ -539,3 +539,50 @@ func TestInventorySyncEntry_StoredCredentialRefusalForEachConnectionType(t *test } } } + +// Every inventory with a VCS source syncs as a file sync, whatever its type says: an inherited +// customer-pool binding places it there under the same pool and credential rules. +func TestInventorySyncEntry_OtherTypesWithAVCSSource(t *testing.T) { + for _, typ := range []models.InventoryType{models.InventoryTypeStatic, models.InventoryTypeDynamic} { + for name, tc := range map[string]struct { + restricted, allowStored bool + want int + }{ + "pool does not allow the project": {restricted: true, allowStored: true, want: http.StatusUnprocessableEntity}, + "stored credential not allowed": {want: http.StatusUnprocessableEntity}, + "allowed": {allowStored: true, want: http.StatusAccepted}, + } { + t.Run(string(typ)+", "+name, func(t *testing.T) { + f := setupSyncEntry(t) + f.allowStored(t, tc.allowStored) + if tc.restricted { + f.selectOnProject(t, &f.onRestricted.ID) + } else { + f.selectOnProject(t, &f.onOpen.ID) + } + inv := f.inventory(t, f.gitlab.ID, nil) + if err := f.db.Model(&models.AnsibleInventory{}).Where("id = ?", inv.ID).Update("type", typ).Error; err != nil { + t.Fatal(err) + } + code, body := f.sync(t, inv.ID) + status, _, n := f.state(t, inv.ID) + if code != tc.want { + t.Fatalf("manual sync = %d (%s), want %d", code, body, tc.want) + } + if tc.want != http.StatusAccepted { + if n != 0 || status != "completed" { + t.Errorf("a refused sync left %d work items and status %q", n, status) + } + return + } + var item models.WorkItem + if err := f.db.First(&item, "inventory_id = ?", inv.ID).Error; err != nil { + t.Fatal(err) + } + if item.Kind != models.WorkItemInventoryFileSync || item.AgentPoolID == nil || *item.AgentPoolID != f.open.ID { + t.Errorf("queued %s on %v, want a file sync on the binding's pool %s", item.Kind, item.AgentPoolID, f.open.ID) + } + }) + } + } +} diff --git a/backend/internal/api/v2/handlers/identity_bindings_org_test.go b/backend/internal/api/v2/handlers/identity_bindings_org_test.go index 4b4be0ad..7b5f9103 100644 --- a/backend/internal/api/v2/handlers/identity_bindings_org_test.go +++ b/backend/internal/api/v2/handlers/identity_bindings_org_test.go @@ -14,6 +14,7 @@ package handlers import ( "encoding/json" "fmt" + "math" "net/http" "testing" @@ -260,6 +261,15 @@ func TestOrganizationIdentityBindings_PagingPoolNameAndInventoryFilter(t *testin } } + // A page far beyond the list is an empty page, filtered or not. + for _, q := range []string{"", "&filter[inventory]=" + inX.ID.String()} { + for _, page := range []int{math.MaxInt, math.MaxInt/100 + 2} { + if code, p := get(f.owner, fmt.Sprintf("?page[size]=100&page[number]=%d%s", page, q)); code != http.StatusOK || len(p.Data) != 0 { + t.Errorf("page %d%s = %d with %d rows, want 200 and none", page, q, code, len(p.Data)) + } + } + } + // filter[inventory]: the hosted binding and the bindings of pools the inventory may use. for _, tc := range []struct { inv *models.AnsibleInventory diff --git a/backend/internal/api/v2/handlers/project_delete_inventories_test.go b/backend/internal/api/v2/handlers/project_delete_inventories_test.go index c7bbf17e..52a856b1 100644 --- a/backend/internal/api/v2/handlers/project_delete_inventories_test.go +++ b/backend/internal/api/v2/handlers/project_delete_inventories_test.go @@ -11,13 +11,16 @@ package handlers import ( "net/http" "strings" + "sync" "testing" "github.com/google/uuid" + "github.com/michielvha/stackweaver/backend/internal/services/activity" "github.com/michielvha/stackweaver/backend/internal/services/auth" "github.com/michielvha/stackweaver/backend/internal/services/rbac" "github.com/michielvha/stackweaver/core/models" "github.com/michielvha/stackweaver/core/repository" + "gorm.io/gorm" ) func TestProjectDelete_WithInventories(t *testing.T) { @@ -70,3 +73,75 @@ func TestProjectDelete_WithInventories(t *testing.T) { }) } } + +// An inventory created between the first check and the locked one refuses the delete, and only a +// delete that happened is recorded. +func TestProjectDelete_WithInventories_RecordsOnlyADelete(t *testing.T) { + f := setupOrgVersionFixture(t) + org := f.createOrg(t, "projdel-"+f.sfx) + orgRepo, teamRepo, projectRepo := repository.NewOrganizationRepository(f.db), repository.NewTeamRepository(f.db), repository.NewProjectRepository(f.db) + h := NewProjectHandlerV2(projectRepo, orgRepo, teamRepo, repository.NewAgentPoolRepository(f.db), repository.NewTagBindingRepository(f.db), + auth.NewService(repository.NewUserRepository(f.db)), activity.NewService(repository.NewAuditLogRepository(f.db)), rbac.NewServiceWithTeams(orgRepo, teamRepo, projectRepo)) + router := storedAsSentRouter() + router.DELETE("/api/v2/organizations/:name/projects/:project_name", h.Delete) + router.DELETE("/api/v2/projects/:id", h.DeleteByID) + + for name, path := range map[string]func(models.Project) string{ + "by name": func(p models.Project) string { return "/api/v2/organizations/" + org.Name + "/projects/" + p.Name }, + "by ID": func(p models.Project) string { return "/api/v2/projects/" + p.ID.String() }, + } { + t.Run(name, func(t *testing.T) { + project := models.Project{ID: uuid.New(), OrganizationID: org.ID, Name: "projdel-" + uuid.NewString()[:8]} + if err := f.db.Create(&project).Error; err != nil { + t.Fatal(err) + } + inv := models.AnsibleInventory{ID: uuid.New(), OrganizationID: org.ID, ProjectID: &project.ID, Name: "projdel-" + uuid.NewString()[:8], Type: models.InventoryTypeStatic} + t.Cleanup(func() { + f.db.Where("project_id = ?", project.ID).Delete(&models.AuditLog{}) + f.db.Where("id = ?", inv.ID).Delete(&models.AnsibleInventory{}) + f.db.Where("id = ?", project.ID).Delete(&models.Project{}) + }) + recorded := func() int64 { + var n int64 + if err := f.db.Model(&models.AuditLog{}).Where("project_id = ? AND action = ?", project.ID, "delete").Count(&n).Error; err != nil { + t.Fatal(err) + } + return n + } + var once sync.Once + cb := "test:create-before-project-lock-" + uuid.NewString()[:8] + if err := f.db.Callback().Query().Before("gorm:query").Register(cb, func(tx *gorm.DB) { + if _, locking := tx.Statement.Clauses["FOR"]; locking && tx.Statement.Table == "projects" { + once.Do(func() { + if err := f.db.Session(&gorm.Session{NewDB: true}).Create(&inv).Error; err != nil { + t.Error(err) + } + }) + } + }); err != nil { + t.Fatal(err) + } + code, body := storedAsSentCall(t, router, http.MethodDelete, path(project), f.creator.ID, "") + _ = f.db.Callback().Query().Remove(cb) + if code != http.StatusConflict { + t.Errorf("delete = %d (%s), want 409", code, body) + } + if err := f.db.First(&models.Project{}, "id = ?", project.ID).Error; err != nil { + t.Errorf("the refused delete removed the project: %v", err) + } + if n := recorded(); n != 0 { + t.Errorf("the refused delete recorded %d deletions", n) + } + + if err := f.db.Where("id = ?", inv.ID).Delete(&models.AnsibleInventory{}).Error; err != nil { + t.Fatal(err) + } + if code, body := storedAsSentCall(t, router, http.MethodDelete, path(project), f.creator.ID, ""); code != http.StatusNoContent { + t.Errorf("delete = %d (%s), want 204", code, body) + } + if n := recorded(); n != 1 { + t.Errorf("the delete recorded %d deletions, want 1", n) + } + }) + } +} diff --git a/backend/internal/api/v2/handlers/projects.go b/backend/internal/api/v2/handlers/projects.go index e5404e6d..b1c289d6 100644 --- a/backend/internal/api/v2/handlers/projects.go +++ b/backend/internal/api/v2/handlers/projects.go @@ -708,19 +708,6 @@ func (h *ProjectHandlerV2) Update(c *gin.Context) { jsonapi.WriteDocument(c, http.StatusOK, formatProjectResponse(project, org.Name)) } -// refuseWithInventories answers 409 and returns true when the project still has inventories. -func (h *ProjectHandlerV2) refuseWithInventories(c *gin.Context, projectID uuid.UUID) bool { - has, err := h.projectRepo.HasInventories(projectID) - if err != nil { - jsonapi.WriteError(c, http.StatusInternalServerError, "Internal Server Error", "Failed to read the project's inventories") - return true - } - if has { - writeProjectHasInventories(c) - } - return has -} - func writeProjectHasInventories(c *gin.Context) { jsonapi.WriteError(c, http.StatusConflict, "Conflict", "The project still has Ansible inventories. Delete them before deleting the project; an inventory cannot be moved to another project.") } @@ -762,11 +749,16 @@ func (h *ProjectHandlerV2) Delete(c *gin.Context) { return } - if h.refuseWithInventories(c, project.ID) { + if err := h.projectRepo.Delete(project.ID); err != nil { + if errors.Is(err, repository.ErrProjectHasInventories) { + writeProjectHasInventories(c) + return + } + jsonapi.WriteError(c, http.StatusInternalServerError, "Internal Server Error", "Failed to delete project") return } - // Log activity before deletion (non-blocking) + // Log the deletion once it happened (non-blocking) if h.activityService != nil { activityCtx := helpers.GetActivityContext(c) activityCtx.OrganizationID = &org.ID @@ -774,15 +766,6 @@ func (h *ProjectHandlerV2) Delete(c *gin.Context) { _ = h.activityService.LogDelete(c.Request.Context(), "project", project.ID.String(), project.Name, activityCtx) } - if err := h.projectRepo.Delete(project.ID); err != nil { - if errors.Is(err, repository.ErrProjectHasInventories) { - writeProjectHasInventories(c) - return - } - jsonapi.WriteError(c, http.StatusInternalServerError, "Internal Server Error", "Failed to delete project") - return - } - c.Status(http.StatusNoContent) } @@ -925,11 +908,16 @@ func (h *ProjectHandlerV2) DeleteByID(c *gin.Context) { return } - if h.refuseWithInventories(c, project.ID) { + if err := h.projectRepo.Delete(project.ID); err != nil { + if errors.Is(err, repository.ErrProjectHasInventories) { + writeProjectHasInventories(c) + return + } + jsonapi.WriteError(c, http.StatusInternalServerError, "Internal Server Error", "Failed to delete project") return } - // Log activity before deletion (non-blocking) + // Log the deletion once it happened (non-blocking) if h.activityService != nil && org != nil { activityCtx := helpers.GetActivityContext(c) activityCtx.OrganizationID = &org.ID @@ -937,14 +925,5 @@ func (h *ProjectHandlerV2) DeleteByID(c *gin.Context) { _ = h.activityService.LogDelete(c.Request.Context(), "project", project.ID.String(), project.Name, activityCtx) } - if err := h.projectRepo.Delete(project.ID); err != nil { - if errors.Is(err, repository.ErrProjectHasInventories) { - writeProjectHasInventories(c) - return - } - jsonapi.WriteError(c, http.StatusInternalServerError, "Internal Server Error", "Failed to delete project") - return - } - c.Status(http.StatusNoContent) } diff --git a/backend/internal/api/v2/handlers/runner_agent_work_items_artifacts_integration_test.go b/backend/internal/api/v2/handlers/runner_agent_work_items_artifacts_integration_test.go index 74c3ad10..4b7adeae 100644 --- a/backend/internal/api/v2/handlers/runner_agent_work_items_artifacts_integration_test.go +++ b/backend/internal/api/v2/handlers/runner_agent_work_items_artifacts_integration_test.go @@ -19,6 +19,7 @@ import ( "crypto/x509" "encoding/json" "encoding/pem" + "fmt" "io" "net/http" "net/http/httptest" @@ -40,7 +41,10 @@ import ( type fakeTokenGitHub struct { mu sync.Mutex status int - bodies []map[string]any + // repositories is the JSON value of a 201 answer's list; empty lists the requested repository of + // the account acme, and "absent" leaves the list out. + repositories string + bodies []map[string]any } func (g *fakeTokenGitHub) serve(w http.ResponseWriter, r *http.Request) { @@ -49,14 +53,25 @@ func (g *fakeTokenGitHub) serve(w http.ResponseWriter, r *http.Request) { _ = json.Unmarshal(raw, &body) g.mu.Lock() g.bodies = append(g.bodies, body) - status := g.status + status, list, minted := g.status, g.repositories, len(g.bodies) g.mu.Unlock() if status == 0 { status = http.StatusCreated } w.WriteHeader(status) if status == http.StatusCreated { - _, _ = io.WriteString(w, `{"token":"ghs_narrowed","expires_at":"`+time.Now().Add(time.Hour).UTC().Format(time.RFC3339)+`"}`) + if list == "" { + names, _ := body["repositories"].([]any) + if len(names) == 1 { + name, _ := names[0].(string) + list = `[{"id":1,"full_name":"acme/` + name + `"}]` + } + } + field := `,"repositories":` + list + if list == "absent" || list == "" { + field = "" + } + _, _ = fmt.Fprintf(w, `{"token":"ghs_narrowed_%d","expires_at":"%s"%s}`, minted, time.Now().Add(time.Hour).UTC().Format(time.RFC3339), field) return } _, _ = io.WriteString(w, `{"message":"no access to that repository"}`) @@ -133,7 +148,7 @@ func TestFileSyncArtifacts_NarrowedGitHubAppToken(t *testing.T) { g, conn := f.githubApp(t) _, item := f.syncOnPoolA(t, conn.ID, "fs-customer") rec, art := f.artifacts(t, "fs-customer", item.ID) - if rec.Code != http.StatusOK || art.Clone == nil || art.Clone.Token != "ghs_narrowed" { + if rec.Code != http.StatusOK || art.Clone == nil || art.Clone.Token != "ghs_narrowed_1" { t.Fatalf("customer-pool artifacts = %d %s, want the narrowed token", rec.Code, rec.Body.String()) } reqs := g.requests() @@ -166,8 +181,11 @@ func TestFileSyncArtifacts_NarrowedGitHubAppToken(t *testing.T) { if code != http.StatusOK || tok.Token == "" { t.Fatalf("hosted token = %d", code) } - if rec, art := f.artifacts(t, "fs-hosted", hosted.ID); rec.Code != http.StatusOK || art.Clone == nil || art.Clone.Token != "ghs_narrowed" { - t.Errorf("hosted artifacts = %d %s, want the narrowed token", rec.Code, rec.Body.String()) + // A second artifacts request of the same work item mints its own token. + for minted := 2; minted <= 3; minted++ { + if rec, art := f.artifacts(t, "fs-hosted", hosted.ID); rec.Code != http.StatusOK || art.Clone == nil || art.Clone.Token != fmt.Sprintf("ghs_narrowed_%d", minted) { + t.Errorf("hosted artifacts = %d %s, want narrowed token %d", rec.Code, rec.Body.String(), minted) + } } for _, body := range g.requests() { if body["repositories"] == nil { @@ -195,6 +213,53 @@ func TestFileSyncArtifacts_GitHubRefusalFailsTheWorkItem(t *testing.T) { } } +func TestFileSyncArtifacts_UnconfirmedRepositoryFailsTheWorkItem(t *testing.T) { + for name, list := range map[string]string{"another repository": `[{"id":1,"full_name":"renamed/inventories"}]`, "no list": "absent"} { + for _, onHosted := range []bool{false, true} { + t.Run(fmt.Sprintf("%s, hosted %t", name, onHosted), func(t *testing.T) { + f := setupWorkItemRunner(t) + g, conn := f.githubApp(t) + g.repositories = list + key := "fs-unconfirmed" + var item *models.WorkItem + if onHosted { + hostedPool, _, err := repository.HostedPoolOf(f.db, f.orgA) + if err != nil { + t.Fatal(err) + } + runner := f.hostedKubernetesRunner(t, hostedPool) + inv := f.fileSyncInventory(t, models.InventoryTypeVCS) + if err := f.db.Model(inv).Update("vcs_connection_id", conn.ID).Error; err != nil { + t.Fatal(err) + } + inv.VCSConnectionID = &conn.ID + if item, err = f.items.RequestInventorySync(t.Context(), inv, "manual"); err != nil { + t.Fatal(err) + } + f.startAs(t, runner, item.ID) + if code, _ := f.mintJobToken(t, f.r, f.svc, "hosted", item.ID, key); code != http.StatusOK { + t.Fatalf("hosted token = %d", code) + } + } else { + _, item = f.syncOnPoolA(t, conn.ID, key) + } + rec, art := f.artifacts(t, key, item.ID) + if rec.Code != http.StatusConflict || art.Clone != nil || strings.Contains(rec.Body.String(), "ghs_narrowed") { + t.Errorf("artifacts = %d %s, want 409 with no clone inputs and no credential", rec.Code, rec.Body.String()) + } + if got := f.reload(t, item.ID); got.Status != models.WorkItemStatusFailed { + t.Errorf("work item = %s, want failed", got.Status) + } + for _, body := range g.requests() { + if body["repositories"] == nil { + t.Errorf("a wider token was requested: %v", body) + } + } + }) + } + } +} + func TestFileSyncArtifacts_GitHubOutageIsLeftForARetry(t *testing.T) { f := setupWorkItemRunner(t) g, conn := f.githubApp(t) diff --git a/backend/internal/api/v2/jsonapi/page_params.go b/backend/internal/api/v2/jsonapi/page_params.go index fbc03906..3f2c9d6a 100644 --- a/backend/internal/api/v2/jsonapi/page_params.go +++ b/backend/internal/api/v2/jsonapi/page_params.go @@ -3,6 +3,7 @@ package jsonapi import ( + "math" "strconv" "github.com/gin-gonic/gin" @@ -42,7 +43,11 @@ func PageParams(c *gin.Context, defaultSize, maxSize int) (page, pageSize int) { return page, pageSize } -// Offset is the row offset for a 1-based page of the given size. +// Offset is the row offset for a 1-based page of the given size. A page whose offset does not fit an +// int is beyond any collection, so it is the largest int. func Offset(page, pageSize int) int { + if pageSize > 0 && page-1 > math.MaxInt/pageSize { + return math.MaxInt + } return (page - 1) * pageSize } diff --git a/backend/internal/api/v2/jsonapi/pagination_test.go b/backend/internal/api/v2/jsonapi/pagination_test.go index 479dd648..ad315631 100644 --- a/backend/internal/api/v2/jsonapi/pagination_test.go +++ b/backend/internal/api/v2/jsonapi/pagination_test.go @@ -12,6 +12,7 @@ package jsonapi import ( "context" "encoding/json" + "math" "net/http" "net/http/httptest" "testing" @@ -239,3 +240,17 @@ func TestNewProviderListMeta(t *testing.T) { } } } + +func TestOffset_PageBeyondAnyCollection(t *testing.T) { + for _, tc := range []struct{ page, size, want int }{ + {1, 20, 0}, + {3, 20, 40}, + {math.MaxInt, 1, math.MaxInt - 1}, + {math.MaxInt, 100, math.MaxInt}, + {math.MaxInt/100 + 2, 100, math.MaxInt}, + } { + if got := Offset(tc.page, tc.size); got != tc.want { + t.Errorf("Offset(%d, %d) = %d, want %d", tc.page, tc.size, got, tc.want) + } + } +}