
Building Role Mining For Rbac Optimization
- 92 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
building-role-mining-for-rbac-optimization is a Claude Code skill in the AI & Agent Building category.
- building-role-mining-for-rbac-optimization
- AI & Agent Building
- AI-coding skill
Building Role Mining For Rbac Optimization by the numbers
- 92 all-time installs (skills.sh)
- Ranked #4,749 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill building-role-mining-for-rbac-optimizationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 92 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Building Role Mining for RBAC Optimization
Overview
Role mining is the process of analyzing existing user-permission assignments to discover optimal roles for a Role-Based Access Control (RBAC) system. Organizations accumulate excessive permissions over time through job changes, project assignments, and ad-hoc access grants, leading to "role explosion" where thousands of granular roles exist with significant overlap. Role mining uses data analysis -- including clustering algorithms, formal concept analysis, and graph-based methods -- to consolidate permissions into a minimal set of roles that accurately represent business functions while enforcing least privilege.
When to Use
- When deploying or configuring building role mining for rbac optimization capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- Export of current user-permission assignments (CSV/database)
- Identity governance platform or directory service access
- Python 3.9+ with pandas, scikit-learn, numpy
- Understanding of organizational structure and job functions
- Stakeholder access for role validation workshops
Core Concepts
Role Mining Approaches
| Approach | Description | Best For |
|---|---|---|
| Bottom-Up | Analyze existing permissions to discover common patterns | Large datasets with organic permission growth |
| Top-Down | Design roles from business requirements and job descriptions | Greenfield RBAC or organizational restructuring |
| Hybrid | Combine bottom-up analysis with top-down business validation | Most production environments |
Role Mining Algorithms
1. Permission Clustering: Group users with similar permission sets using k-means or hierarchical clustering. Users in the same cluster share a common role.
2. Formal Concept Analysis (FCA): Mathematical framework that identifies complete set of concepts (user groups sharing exact permission sets) from a binary user-permission matrix.
3. Graph-Based Mining: Model users and permissions as a bipartite graph, then find dense subgraphs representing candidate roles.
4. Boolean Matrix Decomposition: Decompose the user-permission matrix U into U ≈ R × P where R maps users to roles and P maps roles to permissions.
Role Mining Metrics
| Metric | Formula | Target |
|---|---|---|
| Role Count | Total distinct roles after mining | Minimize |
| Coverage | Permissions explained by mined roles / Total permissions | > 95% |
| Weighted Structural Complexity (WSC) | Sum of role-user + role-permission assignments | Minimize |
| Deviation | Extra permissions not covered by assigned roles | < 5% |
Workflow
Step 1: Extract User-Permission Data
Collect the current access state from all identity sources:
import pandas as pd
import numpy as np
# Load user-permission assignments
# Format: user_id, permission_id (one row per assignment)
assignments = pd.read_csv("user_permissions.csv")
# Create binary user-permission matrix (UPA matrix)
upa_matrix = assignments.pivot_table(
index="user_id",
columns="permission_id",
aggfunc="size",
fill_value=0
)
upa_matrix = (upa_matrix > 0).astype(int)
print(f"Users: {upa_matrix.shape[0]}")
print(f"Permissions: {upa_matrix.shape[1]}")
print(f"Assignments: {assignments.shape[0]}")
print(f"Density: {upa_matrix.values.sum() / upa_matrix.size:.2%}")Step 2: Bottom-Up Role Discovery Using Clustering
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
def find_optimal_clusters(matrix, max_k=50):
"""Find optimal number of roles using silhouette analysis."""
scores = []
for k in range(2, min(max_k, matrix.shape[0])):
clustering = AgglomerativeClustering(
n_clusters=k, metric="jaccard", linkage="average"
)
labels = clustering.fit_predict(matrix)
score = silhouette_score(matrix, labels, metric="jaccard")
scores.append((k, score))
optimal_k = max(scores, key=lambda x: x[1])[0]
return optimal_k, scores
def mine_roles_clustering(upa_matrix, n_clusters):
"""Mine roles using hierarchical clustering on Jaccard distance."""
clustering = AgglomerativeClustering(
n_clusters=n_clusters, metric="jaccard", linkage="average"
)
user_matrix = upa_matrix.values
labels = clustering.fit_predict(user_matrix)
roles = {}
for cluster_id in range(n_clusters):
cluster_users = upa_matrix.index[labels == cluster_id]
cluster_permissions = upa_matrix.loc[cluster_users]
# Core role = permissions held by >80% of cluster members
permission_frequency = cluster_permissions.mean()
core_permissions = permission_frequency[permission_frequency >= 0.8].index.tolist()
roles[f"Role_{cluster_id}"] = {
"permissions": core_permissions,
"user_count": len(cluster_users),
"users": cluster_users.tolist(),
"coverage": permission_frequency[permission_frequency >= 0.8].mean()
}
return roles, labelsStep 3: Formal Concept Analysis
def mine_roles_fca(upa_matrix, min_support=3):
"""Mine roles using Formal Concept Analysis (frequent closed itemsets)."""
from itertools import combinations
users = upa_matrix.index.tolist()
permissions = upa_matrix.columns.tolist()
concepts = []
# Find all maximal permission sets shared by at least min_support users
for size in range(len(permissions), 0, -1):
for perm_combo in combinations(permissions, size):
perm_set = set(perm_combo)
# Find users who have ALL permissions in this set
matching_users = []
for user in users:
user_perms = set(upa_matrix.columns[upa_matrix.loc[user] == 1])
if perm_set.issubset(user_perms):
matching_users.append(user)
if len(matching_users) >= min_support:
# Check if this is a closed concept (no superset with same extent)
is_closed = True
for concept in concepts:
if set(matching_users) == set(concept["users"]) and \
perm_set.issubset(set(concept["permissions"])):
is_closed = False
break
if is_closed:
concepts.append({
"permissions": list(perm_set),
"users": matching_users,
"support": len(matching_users)
})
if len(concepts) > 100: # Limit for performance
break
return conceptsStep 4: Evaluate and Select Roles
def evaluate_role_set(roles, upa_matrix):
"""Evaluate the quality of a mined role set."""
total_assignments = upa_matrix.values.sum()
covered_assignments = 0
extra_assignments = 0
for role_name, role_data in roles.items():
role_perms = set(role_data["permissions"])
for user in role_data["users"]:
user_perms = set(upa_matrix.columns[upa_matrix.loc[user] == 1])
covered = role_perms.intersection(user_perms)
extra = role_perms - user_perms
covered_assignments += len(covered)
extra_assignments += len(extra)
metrics = {
"total_roles": len(roles),
"total_assignments": total_assignments,
"covered_assignments": covered_assignments,
"coverage_rate": covered_assignments / total_assignments if total_assignments else 0,
"extra_permissions": extra_assignments,
"deviation_rate": extra_assignments / (covered_assignments + extra_assignments) if (covered_assignments + extra_assignments) else 0,
"avg_role_size": np.mean([len(r["permissions"]) for r in roles.values()]),
"avg_users_per_role": np.mean([r["user_count"] for r in roles.values()]),
}
return metricsStep 5: Business Validation
After mining candidate roles:
1. Map mined roles to business functions (department, job title) 2. Conduct workshops with business unit managers to validate role definitions 3. Identify outlier permissions that indicate misconfiguration 4. Refine roles based on feedback and re-evaluate metrics 5. Document role definitions with business justification
Validation Checklist
- [ ] User-permission matrix extracted from all identity sources
- [ ] Multiple mining algorithms compared (clustering, FCA)
- [ ] Optimal role count determined via silhouette analysis or WSC
- [ ] Coverage rate exceeds 95% of existing assignments
- [ ] Deviation rate below 5% (minimal extra permissions)
- [ ] Mined roles validated with business stakeholders
- [ ] Role hierarchy defined (parent-child inheritance)
- [ ] Exception/outlier permissions documented
- [ ] Migration plan created for transitioning to new role model
- [ ] Ongoing role governance process defined
References
Role Mining Project Template
Project Overview
| Field | Value |
|---|---|
| Organization | |
| Project Lead | |
| Start Date | |
| Target Completion | |
| Identity Sources | AD / Azure / AWS / Applications |
Data Collection Summary
| Source | Users | Permissions | Assignments |
|---|---|---|---|
| Active Directory | |||
| AWS IAM | |||
| Azure AD | |||
| Applications | |||
| Total (Deduplicated) |
Mining Results
| Algorithm | Roles Found | Coverage | Deviation | WSC |
|---|---|---|---|---|
| Clustering (k=___) | ||||
| Intersection Mining | ||||
| Selected Approach |
Proposed Role Definitions
| Role Name | Department | Permissions | Users | Status |
|---|---|---|---|---|
| Draft/Validated/Approved | ||||
Stakeholder Validation
| Business Unit | Reviewer | Roles Reviewed | Approved | Date |
|---|---|---|---|---|
| Yes/No |
Migration Plan
- [ ] Roles created in identity governance platform
- [ ] User-role assignments configured
- [ ] Individual permission grants removed
- [ ] Test users validated access
- [ ] Full migration completed
- [ ] Post-migration access verification
- [ ] Old permissions cleanup confirmed
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Role Mining for RBAC Optimization
Input Format (CSV)
user,entitlement,system
john.doe,read_files,FileServer
john.doe,write_files,FileServer
jane.smith,read_files,FileServerRole Mining Algorithms
Bottom-Up Mining
Finds exact permission sets shared by >= N users.
- Input: user-permission matrix
- Output: candidate roles with exact permission sets
- Parameter:
min_users(default: 2)
Top-Down Mining (Jaccard Clustering)
Groups users by permission similarity.
Jaccard(A, B) = |A ∩ B| / |A ∪ B|- Threshold >= 0.8: strict similarity
- Threshold >= 0.6: moderate clustering
Optimization Metrics
| Metric | Description |
|---|---|
| Total Assignments | Sum of all user-permission pairs |
| Candidate Roles | Discovered role count |
| Role Coverage | Users assigned to candidate roles |
| Avg Permissions/User | Assignment density |
| Outlier Count | Users with unique permissions |
SailPoint IdentityNow Role Mining API
POST https://{tenant}.api.identitynow.com/beta/role-mining-sessions
Authorization: Bearer TOKEN
{
"scope": {"included": {"identityIds": [...]}},
"minEntitlementPopularity": 2,
"pruneThreshold": 50
}SailPoint Role Mining Status
GET /beta/role-mining-sessions/{sessionId}
GET /beta/role-mining-sessions/{sessionId}/potential-rolesCyberArk Identity Role Optimization
GET /Roles/GetRoleMembers?name={role}
POST /Roles/OptimizeRoles
{"minUsers": 3, "maxRoles": 50}NIST RBAC Model Levels
| Level | Description |
|---|---|
| Core RBAC | Users, roles, permissions, sessions |
| Hierarchical | Role inheritance |
| Constrained | Separation of duty (SoD) |
| Symmetric | Permission-role review |
Role Mining for RBAC Optimization - Standards Reference
RBAC Standards
ANSI/INCITS 359-2012 - Core RBAC
- Defines User, Role, Permission, Session abstractions
- Role assignment: users are assigned to roles
- Permission assignment: permissions are assigned to roles
- Role hierarchy: senior roles inherit junior role permissions
- Separation of Duty constraints (static and dynamic)
NIST RBAC Model (SP 800-162)
- Core RBAC: Basic user-role and role-permission mappings
- Hierarchical RBAC: Role inheritance relationships
- Constrained RBAC: Static and dynamic separation of duties
- Symmetric RBAC: Combined user-centric and permission-centric views
Identity Governance Standards
ISO 27001:2022 - A.5.15 Access Control
- Access control policy based on business and security requirements
- Roles determined by job function
- Regular review of access rights
- Formal authorization for privilege changes
NIST SP 800-53 Rev 5
- AC-2: Account Management
- AC-3: Access Enforcement
- AC-5: Separation of Duties
- AC-6: Least Privilege
- AC-16: Security and Privacy Attributes
- AC-24: Access Control Decisions
Role Mining Research
Key Algorithms
- RoleMiner (Vaidya et al., 2007): Iterative role mining minimizing WSC
- CompleteMiner / FastMiner (Vaidya et al., 2006): Complete vs. approximate algorithms
- ORCA (Schlegelmilch & Steffens, 2005): Clustering-based approach
- Graph Optimization (Lu et al., 2008): Graph-based role mining
Quality Metrics
- Weighted Structural Complexity: min(|UA| + |PA| + |Roles|)
- Boolean Matrix Decomposition error
- Jaccard similarity between mined and original access
- Role coverage percentage
Role Mining for RBAC Optimization - Workflows
End-to-End Role Mining Workflow
Phase 1: DATA COLLECTION (Week 1-2)
├── Export user-permission data from all identity sources
│ ├── Active Directory group memberships
│ ├── Cloud IAM role assignments
│ ├── Application-level permissions
│ └── Database access grants
├── Collect HR data (job titles, departments, cost centers)
├── Normalize data into User-Permission Assignment (UPA) matrix
└── Clean data: remove disabled accounts, system accounts
Phase 2: ANALYSIS (Week 3-4)
├── Run clustering algorithms (hierarchical, k-means)
├── Run Formal Concept Analysis for exact role candidates
├── Compare results using WSC and coverage metrics
├── Identify optimal number of roles via silhouette analysis
└── Map candidate roles to organizational structure
Phase 3: VALIDATION (Week 5-6)
├── Present candidate roles to business unit managers
├── Validate each role against job descriptions
├── Identify and resolve outlier permissions
├── Define role hierarchy (inheritance relationships)
└── Agree on role names and descriptions
Phase 4: IMPLEMENTATION (Week 7-8)
├── Create roles in identity governance platform
├── Assign users to validated roles
├── Remove individual permission assignments
├── Test access for sample users in each role
└── Document role definitions and approval chain
Phase 5: GOVERNANCE (Ongoing)
├── Monitor for permission drift
├── Quarterly role effectiveness review
├── Re-run mining annually to detect new patterns
└── Track role count and WSC metrics over timeData Normalization Workflow
Raw Data Sources
│
├── AD: user → group → permissions
│ Normalize to: user_id, permission_id
│
├── AWS: user/role → policy → actions
│ Normalize to: user_id, permission_id
│
├── Azure: user → role → permissions
│ Normalize to: user_id, permission_id
│
└── Applications: user → app_role → features
Normalize to: user_id, permission_id
Merge all sources → Deduplicate → Create UPA matrixRole Consolidation Workflow
Mining produces N candidate roles
│
├── Remove roles with < 3 users (outliers)
│
├── Merge roles with > 90% Jaccard similarity
│
├── Identify hierarchical relationships:
│ └── If Role A permissions ⊂ Role B permissions
│ → Role A is junior to Role B
│
├── Check for SoD violations:
│ └── Does any role combine conflicting permissions?
│ → Split into separate roles if needed
│
└── Final role set with hierarchy and constraints#!/usr/bin/env python3
"""Role Mining for RBAC Optimization Agent - Analyzes access patterns to optimize role-based access control."""
import json
import logging
import argparse
import csv
from collections import defaultdict
from datetime import datetime
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def load_entitlements(csv_path):
"""Load user-entitlement assignments from CSV (user,entitlement,system)."""
assignments = []
with open(csv_path, newline="") as f:
reader = csv.DictReader(f)
for row in reader:
assignments.append({"user": row.get("user", "").strip(), "entitlement": row.get("entitlement", "").strip(),
"system": row.get("system", "").strip()})
logger.info("Loaded %d user-entitlement assignments", len(assignments))
return assignments
def build_user_permission_matrix(assignments):
"""Build user-to-permission-set mapping."""
matrix = defaultdict(set)
for a in assignments:
key = f"{a['system']}:{a['entitlement']}"
matrix[a["user"]].add(key)
return {user: sorted(perms) for user, perms in matrix.items()}
def mine_roles_bottom_up(user_matrix, min_users=2):
"""Bottom-up role mining: find common permission sets shared by multiple users."""
perm_set_users = defaultdict(list)
for user, perms in user_matrix.items():
key = tuple(perms)
perm_set_users[key].append(user)
candidate_roles = []
role_id = 0
for perm_set, users in perm_set_users.items():
if len(users) >= min_users:
role_id += 1
candidate_roles.append({
"role_id": f"ROLE-{role_id:03d}",
"permissions": list(perm_set),
"assigned_users": users,
"user_count": len(users),
})
candidate_roles.sort(key=lambda r: r["user_count"], reverse=True)
logger.info("Mined %d candidate roles (min_users=%d)", len(candidate_roles), min_users)
return candidate_roles
def mine_roles_top_down(user_matrix, similarity_threshold=0.8):
"""Top-down role mining: cluster users by permission similarity (Jaccard)."""
users = list(user_matrix.keys())
clusters = []
visited = set()
for i, u1 in enumerate(users):
if u1 in visited:
continue
cluster = [u1]
visited.add(u1)
s1 = set(user_matrix[u1])
for j in range(i + 1, len(users)):
u2 = users[j]
if u2 in visited:
continue
s2 = set(user_matrix[u2])
intersection = len(s1 & s2)
union = len(s1 | s2)
jaccard = intersection / union if union > 0 else 0
if jaccard >= similarity_threshold:
cluster.append(u2)
visited.add(u2)
if len(cluster) >= 2:
common_perms = set(user_matrix[cluster[0]])
for u in cluster[1:]:
common_perms &= set(user_matrix[u])
clusters.append({"users": cluster, "common_permissions": sorted(common_perms),
"user_count": len(cluster)})
logger.info("Found %d user clusters (threshold=%.2f)", len(clusters), similarity_threshold)
return clusters
def detect_outliers(user_matrix, candidate_roles):
"""Detect users with unique permissions not covered by any candidate role."""
role_perms = set()
for role in candidate_roles:
role_perms.update(role["permissions"])
outliers = []
for user, perms in user_matrix.items():
uncovered = set(perms) - role_perms
if uncovered:
outliers.append({"user": user, "uncovered_permissions": sorted(uncovered),
"total_permissions": len(perms), "uncovered_count": len(uncovered)})
outliers.sort(key=lambda o: o["uncovered_count"], reverse=True)
logger.info("Found %d users with uncovered permissions", len(outliers))
return outliers
def calculate_optimization_metrics(user_matrix, candidate_roles):
"""Calculate RBAC optimization metrics."""
total_assignments = sum(len(perms) for perms in user_matrix.values())
total_users = len(user_matrix)
role_assignments = sum(r["user_count"] for r in candidate_roles)
all_perms = set()
for perms in user_matrix.values():
all_perms.update(perms)
return {
"total_users": total_users,
"total_unique_permissions": len(all_perms),
"total_assignments": total_assignments,
"candidate_roles": len(candidate_roles),
"role_coverage_users": role_assignments,
"avg_permissions_per_user": round(total_assignments / total_users, 1) if total_users else 0,
"avg_users_per_role": round(role_assignments / len(candidate_roles), 1) if candidate_roles else 0,
}
def generate_report(candidate_roles, clusters, outliers, metrics):
"""Generate role mining report."""
report = {
"timestamp": datetime.utcnow().isoformat(),
"optimization_metrics": metrics,
"candidate_roles": candidate_roles[:20],
"user_clusters": clusters[:20],
"permission_outliers": outliers[:20],
}
print(f"RBAC REPORT: {metrics['total_users']} users, {metrics['candidate_roles']} candidate roles, "
f"{len(outliers)} outliers")
return report
def main():
parser = argparse.ArgumentParser(description="Role Mining for RBAC Optimization")
parser.add_argument("--input", required=True, help="CSV file with user,entitlement,system columns")
parser.add_argument("--min-users", type=int, default=2, help="Minimum users for role candidate")
parser.add_argument("--similarity", type=float, default=0.8, help="Jaccard similarity threshold")
parser.add_argument("--output", default="rbac_mining_report.json")
args = parser.parse_args()
assignments = load_entitlements(args.input)
user_matrix = build_user_permission_matrix(assignments)
candidate_roles = mine_roles_bottom_up(user_matrix, args.min_users)
clusters = mine_roles_top_down(user_matrix, args.similarity)
outliers = detect_outliers(user_matrix, candidate_roles)
metrics = calculate_optimization_metrics(user_matrix, candidate_roles)
report = generate_report(candidate_roles, clusters, outliers, metrics)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Role Mining Engine for RBAC Optimization
Implements multiple role mining algorithms (clustering, FCA) on user-permission
assignment data to discover optimal RBAC roles. Generates role definitions,
coverage reports, and migration plans.
Requirements:
pip install pandas numpy scikit-learn
"""
import csv
import json
from collections import defaultdict
from itertools import combinations
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
class RoleMiningEngine:
"""Core role mining engine supporting multiple algorithms."""
def __init__(self, assignments_file=None):
self.upa_matrix = None
self.user_metadata = {}
self.mined_roles = {}
if assignments_file:
self.load_assignments(assignments_file)
def load_assignments(self, filepath):
"""Load user-permission assignments from CSV (user_id, permission_id)."""
df = pd.read_csv(filepath)
required = {"user_id", "permission_id"}
if not required.issubset(df.columns):
raise ValueError(f"CSV must contain columns: {required}")
self.upa_matrix = df.pivot_table(
index="user_id", columns="permission_id",
aggfunc="size", fill_value=0
)
self.upa_matrix = (self.upa_matrix > 0).astype(int)
print(f"[OK] Loaded UPA matrix: {self.upa_matrix.shape[0]} users x "
f"{self.upa_matrix.shape[1]} permissions")
print(f" Total assignments: {self.upa_matrix.values.sum()}")
density = self.upa_matrix.values.sum() / self.upa_matrix.size
print(f" Matrix density: {density:.2%}")
def load_user_metadata(self, filepath):
"""Load user HR data (user_id, department, title, location)."""
df = pd.read_csv(filepath)
for _, row in df.iterrows():
self.user_metadata[row["user_id"]] = row.to_dict()
def find_optimal_k(self, max_k=50):
"""Determine optimal number of roles using silhouette analysis."""
if self.upa_matrix is None:
raise ValueError("No data loaded")
matrix = self.upa_matrix.values
max_k = min(max_k, matrix.shape[0] - 1)
scores = []
for k in range(2, max_k + 1):
clustering = AgglomerativeClustering(
n_clusters=k, metric="jaccard", linkage="average"
)
labels = clustering.fit_predict(matrix)
score = silhouette_score(matrix, labels, metric="jaccard")
scores.append({"k": k, "silhouette": round(score, 4)})
best = max(scores, key=lambda x: x["silhouette"])
print(f"[OK] Optimal k={best['k']} (silhouette={best['silhouette']})")
return best["k"], scores
def mine_roles_clustering(self, n_clusters=None, threshold=0.8):
"""Mine roles using hierarchical clustering with Jaccard distance."""
if self.upa_matrix is None:
raise ValueError("No data loaded")
if n_clusters is None:
n_clusters, _ = self.find_optimal_k()
matrix = self.upa_matrix.values
clustering = AgglomerativeClustering(
n_clusters=n_clusters, metric="jaccard", linkage="average"
)
labels = clustering.fit_predict(matrix)
roles = {}
for cluster_id in range(n_clusters):
mask = labels == cluster_id
cluster_users = self.upa_matrix.index[mask].tolist()
cluster_data = self.upa_matrix.loc[cluster_users]
perm_freq = cluster_data.mean()
core_perms = perm_freq[perm_freq >= threshold].index.tolist()
# Determine role name from user metadata
role_label = f"Role_{cluster_id:03d}"
if self.user_metadata:
depts = [self.user_metadata.get(u, {}).get("department", "Unknown")
for u in cluster_users]
dept_counts = defaultdict(int)
for d in depts:
dept_counts[d] += 1
if dept_counts:
dominant_dept = max(dept_counts, key=dept_counts.get)
role_label = f"{dominant_dept}_Role_{cluster_id:03d}"
roles[role_label] = {
"permissions": core_perms,
"user_count": len(cluster_users),
"users": cluster_users,
"permission_count": len(core_perms),
}
self.mined_roles = roles
print(f"[OK] Mined {len(roles)} roles via clustering")
return roles
def mine_roles_intersection(self, min_users=3):
"""Mine roles by finding common permission intersections."""
if self.upa_matrix is None:
raise ValueError("No data loaded")
user_perm_sets = {}
for user in self.upa_matrix.index:
perms = set(self.upa_matrix.columns[self.upa_matrix.loc[user] == 1])
user_perm_sets[user] = perms
# Find unique permission sets shared by multiple users
perm_set_users = defaultdict(list)
for user, perms in user_perm_sets.items():
key = frozenset(perms)
perm_set_users[key].append(user)
roles = {}
role_idx = 0
for perm_set, users in perm_set_users.items():
if len(users) >= min_users:
roles[f"ExactRole_{role_idx:03d}"] = {
"permissions": sorted(perm_set),
"user_count": len(users),
"users": users,
"permission_count": len(perm_set),
}
role_idx += 1
self.mined_roles = roles
print(f"[OK] Mined {len(roles)} exact-match roles "
f"(min {min_users} users per role)")
return roles
def evaluate_roles(self, roles=None):
"""Calculate quality metrics for a set of mined roles."""
if roles is None:
roles = self.mined_roles
if not roles:
return {"error": "No roles to evaluate"}
total_assignments = int(self.upa_matrix.values.sum())
covered = 0
extra = 0
for role_data in roles.values():
role_perms = set(role_data["permissions"])
for user in role_data["users"]:
user_perms = set(
self.upa_matrix.columns[self.upa_matrix.loc[user] == 1]
)
covered += len(role_perms & user_perms)
extra += len(role_perms - user_perms)
total_role_assignments = sum(
r["user_count"] + r["permission_count"] for r in roles.values()
)
metrics = {
"total_roles": len(roles),
"total_original_assignments": total_assignments,
"covered_assignments": covered,
"extra_permissions_granted": extra,
"coverage_rate": round(covered / total_assignments, 4) if total_assignments else 0,
"deviation_rate": round(extra / (covered + extra), 4) if (covered + extra) else 0,
"wsc": total_role_assignments + len(roles),
"avg_permissions_per_role": round(
np.mean([r["permission_count"] for r in roles.values()]), 1
),
"avg_users_per_role": round(
np.mean([r["user_count"] for r in roles.values()]), 1
),
}
return metrics
def export_roles(self, output_path):
"""Export mined roles to JSON for import into IGA platform."""
export = {
"generated_at": pd.Timestamp.now().isoformat(),
"metrics": self.evaluate_roles(),
"roles": {}
}
for name, data in self.mined_roles.items():
export["roles"][name] = {
"name": name,
"permissions": data["permissions"],
"user_count": data["user_count"],
"permission_count": data["permission_count"],
}
with open(output_path, "w") as f:
json.dump(export, f, indent=2)
print(f"[OK] Exported {len(self.mined_roles)} roles to {output_path}")
def generate_migration_plan(self, output_path):
"""Generate a CSV migration plan mapping users to new roles."""
rows = []
for role_name, role_data in self.mined_roles.items():
for user in role_data["users"]:
rows.append({
"user_id": user,
"new_role": role_name,
"permissions_in_role": len(role_data["permissions"]),
"current_permissions": int(self.upa_matrix.loc[user].sum()),
})
df = pd.DataFrame(rows)
df.to_csv(output_path, index=False)
print(f"[OK] Migration plan exported to {output_path}")
if __name__ == "__main__":
print("=" * 60)
print("Role Mining Engine for RBAC Optimization")
print("=" * 60)
print()
print("Usage:")
print(" engine = RoleMiningEngine('user_permissions.csv')")
print(" engine.load_user_metadata('hr_data.csv')")
print(" optimal_k, scores = engine.find_optimal_k()")
print(" roles = engine.mine_roles_clustering(n_clusters=optimal_k)")
print(" metrics = engine.evaluate_roles()")
print(" engine.export_roles('mined_roles.json')")
print(" engine.generate_migration_plan('migration_plan.csv')")