Skip to content

Commit c407251

Browse files
committed
fix: add DefaultDetector with DFS-based RBAC cycle detection (#1632)
1 parent 53fb4e4 commit c407251

2 files changed

Lines changed: 488 additions & 0 deletions

File tree

detector/default_detector.go

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// Copyright 2025 The casbin Authors. All Rights Reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package detector
16+
17+
import (
18+
"fmt"
19+
"strings"
20+
21+
"github.com/casbin/casbin/v3/rbac"
22+
)
23+
24+
// rangeableRM is an interface for role managers that support iterating over all role links.
25+
// This is used to build the adjacency graph for cycle detection.
26+
type rangeableRM interface {
27+
Range(func(name1, name2 string, domain ...string) bool)
28+
}
29+
30+
// DefaultDetector is the default implementation of the Detector interface.
31+
// It uses depth-first search (DFS) to detect cycles in role inheritance.
32+
type DefaultDetector struct{}
33+
34+
// NewDefaultDetector creates a new instance of DefaultDetector.
35+
func NewDefaultDetector() *DefaultDetector {
36+
return &DefaultDetector{}
37+
}
38+
39+
// Check checks whether the current status of the passed-in RoleManager contains logical errors (e.g., cycles in role inheritance).
40+
// It uses DFS to traverse the role graph and detect cycles.
41+
// Returns nil if no cycle is found, otherwise returns an error with a description of the cycle.
42+
func (d *DefaultDetector) Check(rm rbac.RoleManager) error {
43+
// Defensive nil check to prevent runtime panics
44+
if rm == nil {
45+
return fmt.Errorf("role manager cannot be nil")
46+
}
47+
48+
// Build the adjacency graph by exploring all roles
49+
graph, err := d.buildGraph(rm)
50+
if err != nil {
51+
return err
52+
}
53+
54+
// Run DFS to detect cycles
55+
visited := make(map[string]bool)
56+
recursionStack := make(map[string]bool)
57+
58+
for role := range graph {
59+
if !visited[role] {
60+
if cycle := d.detectCycle(role, graph, visited, recursionStack, []string{}); cycle != nil {
61+
return fmt.Errorf("cycle detected: %s", strings.Join(cycle, " -> "))
62+
}
63+
}
64+
}
65+
66+
return nil
67+
}
68+
69+
// buildGraph builds an adjacency list representation of the role inheritance graph.
70+
// It uses the Range method (via type assertion) to iterate through all role links.
71+
func (d *DefaultDetector) buildGraph(rm rbac.RoleManager) (map[string][]string, error) {
72+
graph := make(map[string][]string)
73+
74+
// Try to cast to a RoleManager implementation that supports Range
75+
// This works with RoleManagerImpl and similar implementations
76+
rrm, ok := rm.(rangeableRM)
77+
if !ok {
78+
// Return an error if the RoleManager doesn't support Range iteration
79+
return nil, fmt.Errorf("RoleManager does not support Range iteration, cannot detect cycles")
80+
}
81+
82+
// Use Range method to build the graph directly
83+
rrm.Range(func(name1, name2 string, domain ...string) bool {
84+
// Initialize empty slice for name1 if it doesn't exist
85+
if graph[name1] == nil {
86+
graph[name1] = []string{}
87+
}
88+
// Add the link: name1 -> name2
89+
graph[name1] = append(graph[name1], name2)
90+
91+
// Ensure name2 exists in graph even if it has no outgoing edges
92+
if graph[name2] == nil {
93+
graph[name2] = []string{}
94+
}
95+
return true
96+
})
97+
return graph, nil
98+
}
99+
100+
// detectCycle performs DFS to detect cycles in the role graph.
101+
// Returns a slice representing the cycle path if found, nil otherwise.
102+
func (d *DefaultDetector) detectCycle(
103+
role string,
104+
graph map[string][]string,
105+
visited map[string]bool,
106+
recursionStack map[string]bool,
107+
path []string,
108+
) []string {
109+
// Mark the current role as visited and add to recursion stack
110+
visited[role] = true
111+
recursionStack[role] = true
112+
path = append(path, role)
113+
114+
// Visit all neighbors (parent roles)
115+
for _, neighbor := range graph[role] {
116+
if !visited[neighbor] {
117+
// Recursively visit unvisited neighbor
118+
if cycle := d.detectCycle(neighbor, graph, visited, recursionStack, path); cycle != nil {
119+
return cycle
120+
}
121+
} else if recursionStack[neighbor] {
122+
// Back edge found - cycle detected
123+
// Find where the cycle starts in the path
124+
cycleStart := -1
125+
for i, p := range path {
126+
if p == neighbor {
127+
cycleStart = i
128+
break
129+
}
130+
}
131+
if cycleStart >= 0 {
132+
// Build the cycle path
133+
cyclePath := append([]string{}, path[cycleStart:]...)
134+
cyclePath = append(cyclePath, neighbor)
135+
return cyclePath
136+
}
137+
}
138+
}
139+
140+
// Remove from recursion stack before returning
141+
recursionStack[role] = false
142+
return nil
143+
}

0 commit comments

Comments
 (0)