MCPcopy Create free account
hub / github.com/chainloop-dev/chainloop / syncRBACRoles

Function syncRBACRoles

app/controlplane/pkg/authz/enforcer.go:86–173  ·  view source on GitHub ↗
(e *CasbinEnforcer, c *Config)

Source from the content-addressed store, hash-verified

84}
85
86func syncRBACRoles(e *CasbinEnforcer, c *Config) error {
87 // allow to override config during sync
88 conf := c
89 if conf == nil {
90 conf = e.config
91 }
92
93 // Add all the defined policies if they don't exist
94 for role, policies := range conf.RolesMap {
95 for _, p := range policies {
96 // Add policies one by one to skip existing ones
97 casbinPolicy := []string{string(role), p.Resource, p.Action}
98 _, err := e.AddPolicy(casbinPolicy)
99 if err != nil {
100 return fmt.Errorf("failed to add policy: %w", err)
101 }
102 }
103 }
104
105 // Delete all the policies that are not in the roles map
106 // 1 - load the policies from the enforcer
107 policies, err := e.GetPolicy()
108 if err != nil {
109 return fmt.Errorf("failed to get policies: %w", err)
110 }
111
112 // clone policies, as delete operations in CasBin alters the "policies" slice
113 clonedPolicies := slices.Clone(policies)
114
115 for _, p := range clonedPolicies {
116 role := p[0]
117 resource := p[1]
118 action := p[2]
119
120 wantPolicies, ok := conf.RolesMap[Role(role)]
121 // if the role does not exist in the map, we can delete the policy
122 if !ok {
123 _, err := e.RemovePolicy(role, resource, action)
124 if err != nil {
125 return fmt.Errorf("failed to remove policy: %w", err)
126 }
127 continue
128 }
129
130 // We have the role in the map, so we now compare the policies
131 found := false
132 for _, p := range wantPolicies {
133 if p.Resource == resource && p.Action == action {
134 found = true
135 break
136 }
137 }
138
139 // If the policy is not in the map, we remove it
140 if !found {
141 _, err := e.RemovePolicy(p)
142 if err != nil {
143 return fmt.Errorf("failed to remove policy: %w", err)

Callers 3

TestSyncRBACRolesFunction · 0.85
TestDoSyncFunction · 0.85
NewCasbinEnforcerFunction · 0.85

Calls 3

RoleTypeAlias · 0.70
GetPolicyMethod · 0.65
CloneMethod · 0.45

Tested by 2

TestSyncRBACRolesFunction · 0.68
TestDoSyncFunction · 0.68