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 @@

- Branch Coverage - Property Tests + 121 Tests Passing + Property Tests Integration Tests - Security Scan - Priority 1 Validated + Security Scan

## πŸ“– 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) ---