Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
242 changes: 141 additions & 101 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
<a href="#-interactive-documentation">📖 Interactive Docs</a> •
<a href="#-quick-start">⚡ Quick Start</a> •
<a href="#-key-features">✨ Features</a> •
<a href="PROJECT_STRUCTURE.md">📁 Project Structure</a> •
<a href="docs/CONTRIBUTING.md">🤝 Contributing</a>
</p>

Expand All @@ -31,11 +30,10 @@
</p>

<p align="center">
<img src="https://img.shields.io/badge/branch%20coverage-95%25+-brightgreen" alt="Branch Coverage">
<img src="https://img.shields.io/badge/property%20tests-1.5K+-blue" alt="Property Tests">
<img src="https://img.shields.io/badge/tests-121%20passing-brightgreen" alt="121 Tests Passing">
<img src="https://img.shields.io/badge/property%20tests-Hypothesis-blue" alt="Property Tests">
<img src="https://img.shields.io/badge/integration%20tests-8-blue" alt="Integration Tests">
<img src="https://img.shields.io/badge/security%20scan-passing-success" alt="Security Scan">
<img src="https://img.shields.io/badge/validated-priority%201-success" alt="Priority 1 Validated">
<img src="https://img.shields.io/badge/security%20scan-SonarQube%20%2B%20CodeQL-success" alt="Security Scan">
</p>

## 📖 Interactive Documentation
Expand All @@ -58,7 +56,7 @@
```bash
cd docs
npm install # First time only
npm start # Opens at http://localhost:3001
npm start # Opens at http://localhost:3000
```

**What you'll find:**
Expand Down Expand Up @@ -93,74 +91,63 @@ A production-ready, high-performance Role-Based Access Control (RBAC) framework
## ✨ Key Features

### Core Capabilities
- **🚀 Simple API**: Intuitive authorization checks - `can(user, action, resource)`
- **⚡ High Performance**: 10K+ authorization checks/second with optimized algorithms
- **🔄 Storage Layer**: Protocol-based storage interface with in-memory implementation
- **🏢 Multi-Tenancy**: Built-in domain/organization isolation
- **📊 Role Hierarchies**: Support for role inheritance and nested permissions
- **🔍 Attribute-Based**: Hybrid RBAC/ABAC for context-aware authorization
- **📝 Audit Ready**: Complete audit trail for compliance
- **🌐 Framework Agnostic**: Works with any application architecture
- **📦 Zero Dependencies**: Minimal core with optional extensions
- **🎯 Permissions Matrix**: Visual role×permission management with interactive editing

### Enterprise-Grade Validation
- **🧪 Property-Based Testing**: 1,500+ auto-generated test cases using Hypothesis
- **🔗 Integration Testing**: Complete end-to-end workflow validation
- **📈 95%+ Branch Coverage**: Comprehensive code path testing
- **🔒 Automated Security Scanning**: Continuous dependency vulnerability monitoring
- **✅ One-Command Validation**: Run all quality checks with a single script
- **🚀 Simple API**: Three-method surface — `can()`, `check()`, `require()`
- **⚡ High Performance**: 10K+ authorization checks/second (benchmarked)
- **🔄 Pluggable Storage**: Protocol-based interface — swap backends without changing app code
- **🏢 Multi-Tenancy**: Domain-scoped users, roles, resources, and assignments
- **📊 Role Hierarchies**: Single-parent inheritance with circular dependency detection
- **🔍 Hybrid RBAC + ABAC**: Dynamic conditions on permissions — ownership, time, level, department
- **🌐 Framework Agnostic**: Works with Flask, FastAPI, or any Python application
- **📦 Zero Core Dependencies**: No external packages required for the core library
- **🎯 Permissions Matrix**: Visual role×permission management with read/edit modes
- **🗄️ SQLAlchemy Adapter**: Built-in support for PostgreSQL, MySQL, SQLite
- **⏱️ Expiring Assignments**: `expires_at` on role assignments — auto-excluded at auth time
- **🚦 User Lifecycle Enforcement**: SUSPENDED/DELETED users denied at engine level automatically

### Validation & Quality
- **🧪 Property-Based Testing**: Adversarial input generation with Hypothesis
- **🔗 Integration Testing**: 8 end-to-end workflow tests covering real-world patterns
- **📈 95%+ Branch Coverage**: 121 tests total — 49 unit + 8 integration + 14 property + 50 SQLAlchemy
- **🔒 Security Scanned**: SonarQube + CodeQL — all findings resolved
- **✅ Dependency Audited**: All Dependabot vulnerabilities resolved

## 🎯 Design Philosophy

1. **Simplicity First**: Easy to understand, easy to implement
2. **Performance**: Sub-millisecond authorization checks
3. **Standards Compliant**: Follows NIST RBAC model and industry best practices
4. **Extensible**: Plugin architecture for custom requirements
5. **Type Safe**: Full TypeScript/type definitions support
6. **Quality Assured**: Multi-layered automated validation and testing
4. **Extensible**: Protocol-based architecture — implement `IStorageProvider` for custom backends
5. **Quality Assured**: Multi-layered automated validation and testing

## 📋 Quick Start

### Installation

#### Python (Current Implementation)

```bash
# Clone the repository
git clone https://github.com/yourusername/rbac-algorithm.git
cd rbac-algorithm
git clone https://github.com/Maneesh-Relanto/RBAC-algorithm.git
cd RBAC-algorithm

# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate

# Install in development mode
pip install -e .

# Or install required dependencies
pip install dataclasses-json typing-extensions
```

#### Other Languages (Coming Soon)
Or install from PyPI:

```bash
# Node.js
npm install rbac-algorithm

# Go
go get github.com/yourusername/rbac-algorithm

# .NET
dotnet add package RbacAlgorithm
pip install rbac-algorithm
```

### Basic Usage

```python
from rbac import RBAC

# Initialize RBAC engine with in-memory storage
# Initialize RBAC engine (in-memory storage by default)
rbac = RBAC()

# Create a user
Expand Down Expand Up @@ -196,34 +183,36 @@ editor_role = rbac.create_role(
role_id="role_editor",
name="Editor",
domain="company_a",
permissions=["perm_read", "perm_write"]
permissions=["perm_read", "perm_write"],
parent_id="role_viewer" # inherits everything from Viewer
)

# Assign role to user
rbac.assign_role_to_user(
rbac.assign_role(
user_id="user_john",
role_id="role_viewer",
domain="company_a"
)

# Create a resource
post = rbac.create_resource(
resource_id="post_1",
resource_id="resource_post_1",
resource_type="posts",
domain="company_a",
owner_id="user_john"
)

# Check permission
result = rbac.check_permission(
user_id="user_john",
action="read",
resource_id="post_1"
attributes={"owner_id": "user_john"}
)

if result.allowed:
# Check permission — simple boolean
if rbac.can("user_john", "read", "posts"):
print("Access granted!")
print(f"Reason: {result.reason}")

# Check permission — with full result details
result = rbac.check("user_john", "read", "posts")
print(f"Allowed: {result['allowed']}")
print(f"Reason: {result['reason']}")

# Check permission — raises PermissionDenied if denied (for middleware)
rbac.require("user_john", "read", "posts")
```

### Permissions Matrix
Expand Down Expand Up @@ -327,44 +316,85 @@ Rules that govern access decisions.

### Role Hierarchies
```python
admin = Role("admin", parent=editor)
editor = Role("editor", parent=viewer)
viewer = Role("viewer")
# Editor inherits all Viewer permissions
rbac.create_role("role_viewer", "Viewer", permissions=["perm_read"])
rbac.create_role("role_editor", "Editor", permissions=["perm_write"], parent_id="role_viewer")
rbac.create_role("role_admin", "Admin", permissions=["perm_delete"], parent_id="role_editor")
# admin → editor → viewer: admin can read, write, and delete
```

### Context-Aware Permissions
### ABAC — Attribute-Based Conditions
```python
rbac.can(user, "approve", invoice, context={
"amount": 10000,
"department": "finance"
})
# Only allow editing own documents
rbac.create_permission(
"perm_edit_own", "document", "edit",
conditions={"resource.owner_id": {"==": "{{user.id}}"}}
)

# Time-gated + level-gated delete
rbac.create_permission(
"perm_delete_draft", "document", "delete",
conditions={"user.level": {">": 5}, "resource.status": {"==": "draft"}}
)
```

**12 operators:** `==` `!=` `>` `<` `>=` `<=` `in` `not_in` `contains` `startswith` `endswith` `matches`

### SQLAlchemy Storage (PostgreSQL / MySQL / SQLite)
```python
from rbac.storage.sqlalchemy_adapter import SQLAlchemyStorage

storage = SQLAlchemyStorage("postgresql://user:pass@localhost/mydb")
rbac = RBAC(storage=storage)
```

### Expiring Role Assignments
```python
from datetime import datetime, timedelta, timezone

rbac.assign_role(
user_id="user_contractor",
role_id="role_viewer",
expires_at=datetime.now(timezone.utc) + timedelta(days=30)
)
# Expired assignments are automatically excluded — no cron job needed
```

### Bulk Authorization
### User Lifecycle Enforcement
```python
results = rbac.batch_check([
(user1, "read", resource1),
(user2, "write", resource2),
(user3, "delete", resource3)
])
import dataclasses
from rbac.core.models import EntityStatus

# Suspend a user — no access regardless of roles
existing = rbac._storage.get_user("user_john")
rbac._storage.update_user(dataclasses.replace(existing, status=EntityStatus.SUSPENDED))
rbac.can("user_john", "read", "posts") # False — enforced at engine level
```

### Context-Aware Authorization
```python
rbac.can("user_john", "approve", "invoice", context={
"amount": 10000,
"department": "finance"
})
```

## 📊 Performance

- ⚡ **Sub-millisecond authorization checks** (10K+ checks/sec per core)
- ⚡ **Sub-millisecond authorization checks** (10K+ checks/sec — see `benchmarks/`)
- 🚀 **In-memory storage** for consistent, predictable performance
- 📈 **Horizontally scalable** for high-throughput applications
- ⏱️ **Production-ready** with extensive benchmarking
- 🗄️ **SQLAlchemy storage** for persistent deployments with connection pooling

*See benchmarks/ directory for detailed performance tests*
*See the `benchmarks/` directory for detailed performance results.*

## 🔒 Security

- **Principle of Least Privilege**: Default deny policy
- **Input Validation**: All inputs sanitized
- **Audit Logging**: Comprehensive activity tracking
- **No Information Leakage**: Secure error messages
- **Regular Security Audits**: Automated vulnerability scanning
- **Principle of Least Privilege**: Default deny — access requires explicit permission
- **Input Validation**: All entity IDs validated against prefix rules (`user_`, `role_`, `perm_`, `resource_`)
- **No Information Leakage**: Denied results return `False`/`PermissionDenied` without exposing role details
- **User Lifecycle Enforcement**: SUSPENDED and DELETED users are denied at the engine level
- **Dependency Audited**: All Dependabot vulnerabilities resolved; scanned with Safety + pip-audit
- **SonarQube + CodeQL**: All security findings resolved across source and integration layers

## 🤝 Contributing

Expand Down Expand Up @@ -393,9 +423,20 @@ RBAC algorithm/

**Common Commands:**
```bash
# Run all Priority 1 validations (recommended)
.\scripts\validate-priority1.ps1 # Windows
bash scripts/validate-priority1.sh # Linux/Mac
# Run core test suite (121 tests)
pytest tests/

# Run by type
pytest tests/property/ -m property # Property-based tests (Hypothesis)
pytest tests/integration/ -m integration # Integration tests
pytest tests/test_sqlalchemy_storage.py # SQLAlchemy adapter tests

# Run integration apps (run separately to avoid module name collision)
pytest test-apps/02-flask-blog-api/ # Flask Blog API — 34 tests
pytest test-apps/03-fastapi-blog-api/ # FastAPI Blog API — 39 tests

# With coverage (enforces 95% threshold)
pytest tests/ --cov=src --cov-branch

# Code quality check
.\scripts\validate-code.bat # Windows
Expand All @@ -408,12 +449,6 @@ bash scripts/scan-vulnerabilities.sh # Linux/Mac
# Start documentation
.\scripts\start-docs.bat # Windows
./scripts/start-docs.sh # Unix

# Run tests by type
pytest tests/ # All tests
pytest tests/property/ -m property # Property-based tests
pytest tests/integration/ -m integration # Integration tests
pytest tests/ --cov=src --cov-branch # With branch coverage
```

## 📄 License
Expand All @@ -430,19 +465,24 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file

This library is **battle-tested and production-ready** with:

- ✅ Core RBAC implementation (users, roles, permissions)
- ✅ Multi-tenancy support (domain isolation)
- ✅ Role hierarchies with permission inheritance
- ✅ ABAC support with 12 condition operators
- ✅ Permissions matrix for visual management
- ✅ Interactive Streamlit UI for testing and validation
- ✅ Comprehensive test suite (100% validation pass rate)
- ✅ Property-based testing with Hypothesis (1,500+ test cases)
- ✅ Integration testing suite (8 integration tests)
- ✅ 95%+ code coverage with branch analysis
- ✅ Automated security scanning (SonarQube)
- ✅ Zero dependencies core library
- ✅ 10K+ authorization checks per second
- ✅ Core RBAC implementation (users, roles, permissions, resources)
- ✅ Multi-tenancy / domain isolation
- ✅ Role hierarchies with permission inheritance and circular dependency detection
- ✅ Hybrid RBAC + ABAC with 12 condition operators
- ✅ User lifecycle enforcement (ACTIVE / SUSPENDED / DELETED)
- ✅ Expiring role assignments (`expires_at` — auto-excluded at runtime)
- ✅ In-memory storage (zero-config, production-speed)
- ✅ SQLAlchemy storage adapter (PostgreSQL, MySQL, SQLite)
- ✅ Permissions matrix for visual role×permission management
- ✅ Flask Blog API integration (34 tests — JWT auth, ownership, admin panel)
- ✅ FastAPI Blog API integration (39 tests — async, dependency injection, Pydantic)
- ✅ Interactive Streamlit demo (live on Streamlit Community Cloud)
- ✅ 121 tests total (49 unit + 8 integration + 14 property-based + 50 SQLAlchemy)
- ✅ 95%+ branch coverage
- ✅ Property-based testing with Hypothesis (adversarial input generation)
- ✅ SonarQube + CodeQL security scan — all findings resolved
- ✅ Zero core dependencies
- ✅ 10K+ authorization checks per second (benchmarked)

---

Expand Down
Loading