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 adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ func (a *adapter) dropTable() error {
ctx, cancel := context.WithTimeout(context.TODO(), a.timeout)
defer cancel()

err := a.collection.Drop(ctx)
_, err := a.collection.DeleteMany(ctx, bson.D{{}})
if err != nil {
return err
}
Expand Down
62 changes: 62 additions & 0 deletions adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package mongodbadapter

import (
"context"
"fmt"
"os"
"strings"
Expand Down Expand Up @@ -634,3 +635,64 @@ func TestUpdateFilteredPoliciesTxn(t *testing.T) {
e.LoadPolicy()
testGetPolicyWithoutOrder(t, e, [][]string{{"alice", "data1", "write"}, {"bob", "data2", "read"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
}

func TestSavePolicyPreservesIndexes(t *testing.T) {
// Initialize with some policies
initPolicy(t, getDbURL())

a, err := NewAdapter(getDbURL())
if err != nil {
panic(err)
}

e, err := casbin.NewEnforcer("examples/rbac_model.conf", a)
if err != nil {
panic(err)
}

// Save policy which should NOT drop indexes
if err := e.SavePolicy(); err != nil {
t.Errorf("Expected SavePolicy() to be successful; got %v", err)
}

// Try to add a duplicate policy - should fail due to unique index
adapter := a.(*adapter)
line := savePolicyLine("p", []string{"alice", "data1", "read"})

ctx, cancel := context.WithTimeout(context.TODO(), adapter.timeout)
defer cancel()

// Attempting to insert a duplicate should fail
_, err = adapter.collection.InsertOne(ctx, line)
if err == nil {
t.Error("Expected InsertOne of duplicate to fail due to unique index, but it succeeded")
}
}

func TestSavePolicyPreventsDuplicates(t *testing.T) {
// Initialize with some policies
initPolicy(t, getDbURL())

a, err := NewAdapter(getDbURL())
if err != nil {
panic(err)
}

e, err := casbin.NewEnforcer("examples/rbac_model.conf", a)
if err != nil {
panic(err)
}

// Save policy which should NOT drop indexes
if err := e.SavePolicy(); err != nil {
t.Errorf("Expected SavePolicy() to be successful; got %v", err)
}

// Try to add a duplicate directly via adapter (bypassing enforcer's in-memory check)
// This should be prevented by the unique index
adapter := a.(*adapter)
err = adapter.AddPolicy("p", "p", []string{"alice", "data1", "read"})
if err == nil {
t.Error("Expected AddPolicy of duplicate to fail due to unique index, but it succeeded")
}
}