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
2 changes: 1 addition & 1 deletion backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}
}
10 changes: 10 additions & 0 deletions backend/internal/api/v2/handlers/identity_bindings_org_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ package handlers
import (
"encoding/json"
"fmt"
"math"
"net/http"
"testing"

Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}
})
}
}
49 changes: 14 additions & 35 deletions backend/internal/api/v2/handlers/projects.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
}
Expand Down Expand Up @@ -762,27 +749,23 @@ 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
activityCtx.ProjectID = &project.ID
_ = 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)
}

Expand Down Expand Up @@ -925,26 +908,22 @@ 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
activityCtx.ProjectID = &project.ID
_ = 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)
}
Loading
Loading