Skip to content

feat(core): integrate Detector into DefaultRoleManager and add unit tests #475

@knyk-dev

Description

@knyk-dev

Background:
We need to add a hook point for cycle detection into jcasbin, while following the principles of “minimal intrusion” and “loose coupling.” DefaultRoleManager’s addLink method is the only place that updates the inheritance relationship
github.com
.

Tasks:

  1. Add an optional Detector field in DefaultRoleManager:

    private Detector detector;

    public void setDetector(Detector detector) {
    this.detector = detector;
    }

    The default value is null to maintain backward compatibility.

  2. Modify addLink(String name1, String name2, String... domain): after successfully adding the parent-child relationship, if detector is not null, call detector.check(this).

    • If a non-empty error message is returned, immediately roll back the current addRole operation (call removeRole or delete that link), and throw an IllegalArgumentException containing the error description.
  3. Create src/test/java/org/casbin/jcasbin/main/DetectorTest.java:

    • Construct a DefaultRoleManager, inject a DefaultDetector, add some valid inheritance chains, and assert that no exception is thrown.
    • Construct a chain containing a cycle, e.g., A→B→C→A, and assert that when adding the third link, an exception is thrown.
    • Assert that after rollback, the state no longer contains the illegal link.
    • If necessary, add more boundary tests (e.g., self-loop, complex graphs).
  4. In tests, do not depend on Enforcer; only use DefaultRoleManager and DefaultDetector. This can speed up test execution and reduce coupling.

Constraints:

  • Integration modifications must keep the existing public API unchanged. Inject detector only via a setter; do not force all users to enable detection.
  • Unit tests must use JUnit 5 and ensure they pass within the project’s existing test suite.

Metadata

Metadata

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions