Files
summercms/modules/cabana/backend_access_revoked_tx_test.go
Jakub Zych a261a8fdfe fix(32.2): WR-04 never fire BackendAccessRevokedEvent without the save's transaction
fireBackendAccessRevoked refuses a nil tx before any listener runs, and the Administrators and Roles update hooks fail closed (like the delete hook) when the save carries no transaction, instead of firing with whatever TxFromContext answered.
2026-11-21 09:17:33 +01:00

61 lines
2.2 KiB
Go

package cabana
import (
"context"
"testing"
"git.golem15.com/golem15/summercms/modules/backpack"
"gorm.io/gorm"
)
// TestBackendAccessRevokedNeedsTransaction locks the fail-closed side of the
// BackendAccessRevokedEvent contract (32.2 WR-04): a revocation with no
// transaction to commit with is refused before any listener runs, both in
// the helper every site fires through and in the Administrators hook, which
// no longer fires with whatever TxFromContext answered. A save that changes
// nothing a revocation is about still needs no transaction.
func TestBackendAccessRevokedNeedsTransaction(t *testing.T) {
app := backpack.New(nil)
fired := 0
app.Events.Listen("test", func(_ context.Context, ev *BackendAccessRevokedEvent) error {
fired++
return nil
})
ctx := context.Background()
if err := fireBackendAccessRevoked(ctx, app, nil, BackendAccessPermissions, 7); err == nil {
t.Fatal("a revocation without a transaction answered nil")
}
if err := fireBackendAccessRevoked(ctx, app, nil, BackendAccessPermissions, 0); err != nil {
t.Fatalf("no id left: %v, want the no-op nil", err)
}
if err := fireBackendAccessRevoked(ctx, app, &gorm.DB{}, BackendAccessPermissions, 7); err != nil {
t.Fatalf("with a transaction: %v", err)
}
if fired != 1 {
t.Fatalf("listener ran %d times, want 1 (only with a transaction)", fired)
}
users := usersAdmin{screens: &backendScreens{app: app}}
for name, user := range map[string]*BackendUser{
"password set": {ID: 7, priorLoaded: true, passwordSetByOther: true},
"superuser": {ID: 7, priorLoaded: true, IsSuperuser: true},
} {
if err := users.FormAfterUpdate(ctx, user); err == nil {
t.Fatalf("%s: an update without its transaction answered nil", name)
}
}
if err := users.FormAfterUpdate(ctx, &BackendUser{ID: 7, priorLoaded: true}); err != nil {
t.Fatalf("an update that revokes nothing: %v", err)
}
if fired != 1 {
t.Fatalf("listener ran %d times after the hooks, want still 1", fired)
}
roles := rolesAdmin{screens: &backendScreens{app: app}}
role := &BackendUserRole{ID: 3, priorLoaded: true, priorPermissions: `{"a":1}`, Permissions: `{"b":1}`}
if err := roles.FormAfterUpdate(ctx, role); err == nil {
t.Fatal("a role save without its transaction answered nil")
}
}