fix(packages): generic package deletion ignores terraform state lock and latest version (#40302)

`IsLocked` and `IsLatest` in `services/packages/terraform/state.go`
return early when the package **is** a terraform state (`==` instead of
`!=`), so the `OnBeforeRemovePackageAll` /
`OnBeforeRemovePackageVersion` guards never fire. As a result, deleting
through the generic package API (`DELETE
/api/v1/packages/{owner}/terraform/{name}[/{version}]`) or the web UI
ignores the state lock and allows removing the latest state version,
while the terraform state endpoints reject both.

Changes:

- Flip the type check in `IsLocked` and `IsLatest`.
- `DeleteState` (terraform state `DELETE` endpoint) relied on the bug:
after checking the lock it removed every version one by one with
`RemovePackageVersion`, including the latest. With the guard fixed, it
failed with 500 partway through and left a half-deleted state (the
existing `TestPackageTerraform` subtests catch this). It now calls
`RemovePackage`, which checks the lock and deletes everything in one
transaction.
- The generic package delete API used `APIErrorInternal` for every
error, so the guard errors became 500. It now uses `APIErrorAuto`, which
returns 422 for these.
- Added a `GenericPackageAPI` subtest to `TestPackageTerraform`:
deleting an older version works, deleting the latest version or a locked
state returns 422, and deleting an unlocked state works. It fails on
current `main`.

Tested locally with `go test -run '^TestPackage' ./tests/integration`
(SQLite): all pass.

AI disclosure: I used an AI assistant (Claude) to find the bug, trace
the code paths, and draft the change and this description. I reviewed
the change and ran the tests myself.

Signed-off-by: choam2426 <choam2426@gmail.com>
This commit is contained in:
Yonghun Shin authored and GitHub committed 2026-11-10 17:10:59 +00:00
1 parent 1fcb6b4cd6
commit 2ef5b7623b
4 files changed
+50 -27

No files matched your search

+1 -23
View File
@@ -269,29 +269,7 @@ func DeleteState(ctx *context.Context) {
return
}
pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{
PackageID: p.ID,
IsInternal: optional.None[bool](),
})
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
err = packages_model.DeleteAllProperties(ctx, packages_model.PropertyTypePackage, p.ID)
if err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
for _, pv := range pvs {
if err := packages_service.RemovePackageVersion(ctx, ctx.Doer, pv); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
}
if err := packages_model.DeletePackageByID(ctx, p.ID); err != nil {
if err := packages_service.RemovePackage(ctx, ctx.Doer, p); err != nil {
apiError(ctx, http.StatusInternalServerError, err)
return
}
+2 -2
View File
@@ -145,7 +145,7 @@ func DeletePackage(ctx *context.APIContext) {
err := packages_service.RemovePackage(ctx, ctx.Doer, ctx.Package.Descriptor.Package)
if err != nil {
ctx.APIErrorInternal(err)
ctx.APIErrorAuto(err)
return
}
ctx.Status(http.StatusNoContent)
@@ -185,7 +185,7 @@ func DeletePackageVersion(ctx *context.APIContext) {
err := packages_service.RemovePackageVersion(ctx, ctx.Doer, ctx.Package.Descriptor.Version)
if err != nil {
ctx.APIErrorInternal(err)
ctx.APIErrorAuto(err)
return
}
ctx.Status(http.StatusNoContent)
+2 -2
View File
@@ -14,7 +14,7 @@ import (
// IsLocked is a helper function to check if the terraform state is locked
func IsLocked(ctx context.Context, pkg *packages_model.Package) (bool, error) {
// Non terraform state packages aren't handled here
if pkg.Type == packages_model.TypeTerraformState {
if pkg.Type != packages_model.TypeTerraformState {
return false, nil
}
@@ -27,7 +27,7 @@ func IsLocked(ctx context.Context, pkg *packages_model.Package) (bool, error) {
// IsLatest is a helper function to check if the terraform state is the latest version
func IsLatest(ctx context.Context, pd *packages_model.PackageDescriptor) (bool, error) {
if pd.Package.Type == packages_model.TypeTerraformState {
if pd.Package.Type != packages_model.TypeTerraformState {
return false, nil
}
latestPvs, _, err := packages_model.SearchLatestVersions(ctx, &packages_model.PackageSearchOptions{
@@ -10,6 +10,7 @@ import (
"testing"
"uuid"
auth_model "gitea.dev/models/auth"
"gitea.dev/models/packages"
"gitea.dev/models/unittest"
user_model "gitea.dev/models/user"
@@ -299,4 +300,48 @@ func TestPackageTerraform(t *testing.T) {
MakeRequest(t, req, http.StatusBadRequest)
})
})
// The generic package API must enforce the same rules as the terraform state API
t.Run("GenericPackageAPI", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
token := getUserToken(t, user.Name, auth_model.AccessTokenScopeWritePackage)
packageURL := fmt.Sprintf("/api/v1/packages/%s/terraform/%s", user.Name, packageName)
for i := range 3 {
req := NewRequestWithBody(t, "POST", url, strings.NewReader(genState(i+1))).AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusCreated)
}
// Deleting an older version is allowed
req := NewRequest(t, "DELETE", packageURL+"/2").AddTokenAuth(token)
MakeRequest(t, req, http.StatusNoContent)
_, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeTerraformState, packageName, "2")
assert.ErrorIs(t, err, packages.ErrPackageNotExist)
// Deleting the latest version is forbidden
req = NewRequest(t, "DELETE", packageURL+"/3").AddTokenAuth(token)
MakeRequest(t, req, http.StatusUnprocessableEntity)
_, err = packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeTerraformState, packageName, "3")
require.NoError(t, err)
lockInfo := genLock(uuid.New().String())
req = NewRequestWithBody(t, "POST", lockURL, strings.NewReader(lockInfo)).AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusOK)
// Deleting a locked state is forbidden
req = NewRequest(t, "DELETE", packageURL).AddTokenAuth(token)
MakeRequest(t, req, http.StatusUnprocessableEntity)
_, err = packages.GetPackageByName(t.Context(), user.ID, packages.TypeTerraformState, packageName)
require.NoError(t, err)
req = NewRequestWithBody(t, "DELETE", lockURL, strings.NewReader(lockInfo)).AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusOK)
// Deleting an unlocked state is allowed
req = NewRequest(t, "DELETE", packageURL).AddTokenAuth(token)
MakeRequest(t, req, http.StatusNoContent)
_, err = packages.GetPackageByName(t.Context(), user.ID, packages.TypeTerraformState, packageName)
assert.ErrorIs(t, err, packages.ErrPackageNotExist)
})
}