diff --git a/README.md b/README.md
index 2b75be5..522b744 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,6 @@
π Interactive Docs β’
β‘ Quick Start β’
β¨ Features β’
- π Project Structure β’
π€ Contributing
@@ -31,11 +30,10 @@
-
-
+
+
-
-
+
## π Interactive Documentation
@@ -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:**
@@ -93,43 +91,42 @@ 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
@@ -137,22 +134,12 @@ 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
@@ -160,7 +147,7 @@ dotnet add package RbacAlgorithm
```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
@@ -196,11 +183,12 @@ 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"
@@ -208,22 +196,23 @@ rbac.assign_role_to_user(
# 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
@@ -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
@@ -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
@@ -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
@@ -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)
---