building-role-mining-for-rbac-optimization

mukul975/Anthropic-Cybersecurity-Skills · updated May 25, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills install mukul975/Anthropic-Cybersecurity-Skills/building-role-mining-for-rbac-optimization
0 commentsdiscussion
summary

Apply bottom-up and top-down role mining techniques to discover optimal RBAC roles from existing user-permission assignments, reducing role explosion and enforcing least privilege.

skill.md
name
building-role-mining-for-rbac-optimization
description
Apply bottom-up and top-down role mining techniques to discover optimal RBAC roles from existing user-permission assignments, reducing role explosion and enforcing least privilege.
domain
cybersecurity
subdomain
identity-access-management
tags
- rbac - role-mining - identity-governance - access-control - least-privilege - clustering
version
'1.0'
author
mahipal
license
Apache-2.0
nist_csf
- PR.AA-01 - PR.AA-02 - PR.AA-05 - PR.AA-06

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

ApproachDescriptionBest For
Bottom-UpAnalyze existing permissions to discover common patternsLarge datasets with organic permission growth
Top-DownDesign roles from business requirements and job descriptionsGreenfield RBAC or organizational restructuring
HybridCombine bottom-up analysis with top-down business validationMost 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

MetricFormulaTarget
Role CountTotal distinct roles after miningMinimize
CoveragePermissions explained by mined roles / Total permissions> 95%
Weighted Structural Complexity (WSC)Sum of role-user + role-permission assignmentsMinimize
DeviationExtra 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, labels

Step 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 concepts

Step 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 metrics

Step 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

how to use building-role-mining-for-rbac-optimization

How to use building-role-mining-for-rbac-optimization on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add building-role-mining-for-rbac-optimization
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills install mukul975/Anthropic-Cybersecurity-Skills/building-role-mining-for-rbac-optimization

The skills CLI fetches building-role-mining-for-rbac-optimization from GitHub repository mukul975/Anthropic-Cybersecurity-Skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/building-role-mining-for-rbac-optimization

Reload or restart Cursor to activate building-role-mining-for-rbac-optimization. Access the skill through slash commands (e.g., /building-role-mining-for-rbac-optimization) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.658 reviews
  • William Gonzalez· Dec 24, 2024

    building-role-mining-for-rbac-optimization is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Chen Farah· Dec 24, 2024

    Solid pick for teams standardizing on skills: building-role-mining-for-rbac-optimization is focused, and the summary matches what you get after install.

  • Ganesh Mohane· Dec 16, 2024

    We added building-role-mining-for-rbac-optimization from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Aditi Garcia· Nov 15, 2024

    Keeps context tight: building-role-mining-for-rbac-optimization is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Chen Haddad· Nov 15, 2024

    building-role-mining-for-rbac-optimization has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Rahul Santra· Nov 7, 2024

    building-role-mining-for-rbac-optimization reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Pratham Ware· Oct 26, 2024

    building-role-mining-for-rbac-optimization is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Aditi Johnson· Oct 6, 2024

    We added building-role-mining-for-rbac-optimization from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Noor Dixit· Oct 6, 2024

    building-role-mining-for-rbac-optimization fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Alexander Perez· Sep 17, 2024

    Useful defaults in building-role-mining-for-rbac-optimization — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

showing 1-10 of 58

1 / 6