# Corteq Framework
> **Enterprise-Grade Multi-Tenant SaaS Framework for Rust**
[](LICENSE)
[](https://www.rust-lang.org)
[](tests/)
Corteq is a security-first, production-ready framework for building multi-tenant SaaS applications in Rust. Built on Actix Web, it provides comprehensive tenant isolation, authentication, encryption, and compliance features out of the box.
## ๐ Features
### ๐ **Security First**
- **Row-Level Security (RLS)**: Automatic tenant data isolation at the PostgreSQL level
- **AES-256-GCM Encryption**: Data at rest encryption with tenant-specific keys
- **JWT Authentication**: Bearer token & HTTP cookie support
- **Defense in Depth**: Multiple layers of security (middleware + database)
### ๐ข **Multi-Tenant Architecture**
- **Zero Cross-Tenant Leakage**: Database-level isolation with compile-time safety
- **Per-Tenant Encryption**: Each tenant has unique encryption keys
- **Tenant Context**: Automatic tenant identification from JWT claims
- **Efficient Caching**: In-memory tenant data caching
### ๐ก๏ธ **Compliance Ready**
- **GDPR**: Data isolation, encryption, audit trails
- **HIPAA**: PHI protection with encryption at rest
- **SOC 2**: Security controls and audit logging patterns
### โก **Production Ready**
- **64+ Tests**: Comprehensive test coverage including security tests
- **Type Safety**: Compile-time guarantees prevent common mistakes
- **Performance**: Efficient connection pooling and caching
- **Observability**: Built-in tracing and logging support
## ๐ฆ Quick Start
```toml
[dependencies]
corteq = "0.1"
actix-web = "4.9"
tokio = { version = "1", features = ["full"] }
```
```rust
use actix_web::{web, App, HttpServer};
use corteq::CorteqApp;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let app_config = CorteqApp::builder()
.with_database("postgres://user:pass@localhost/db")
.with_jwt_secret("your-secret-key-min-32-chars!!")
.build()
.await?;
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(app_config.clone()))
.service(
web::scope("/api")
.wrap(corteq::TenantContextMiddleware)
.route("/data", web::get().to(get_tenant_data))
)
})
.bind("0.0.0.0:8080")?
.run()
.await
}
```
## ๐๏ธ Architecture
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HTTP Request โ
โ Authorization: Bearer <jwt_token> โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TenantContextMiddleware โ
โ โข Extracts JWT from Bearer token or Cookie โ
โ โข Validates signature and expiration โ
โ โข Loads tenant context from cache/database โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Handler Function โ
โ (tenant: TenantExtractor) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TenantDatabase โ
โ โข Begins transaction โ
โ โข Sets app.current_tenant_id session variable โ
โ โข RLS policies automatically filter queries โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PostgreSQL with RLS Enabled โ
โ โข Row-Level Security enforces tenant isolation โ
โ โข Only returns rows matching current_tenant_id โ
โ โข Blocks INSERT/UPDATE/DELETE for other tenants โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
## ๐ Security Features
### Tenant Isolation (RLS)
```rust
// Automatically filtered by tenant_id
let mut db = TenantDatabase::begin(&pool, &tenant_ctx).await?;
let docs = sqlx::query!("SELECT * FROM documents")
.fetch_all(db.connection())
.await?;
// โ
Only returns documents for current tenant
```
### JWT Authentication
```rust
// Bearer Token
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
// HTTP Cookie (automatically handled)
Cookie: token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```
### Data Encryption
```rust
let encryption = EncryptionService::new();
// Encrypt with tenant-specific key
let encrypted = encryption.encrypt(plaintext, &tenant_ctx)?;
let bytes = encrypted.to_bytes(); // Store in database
// Decrypt
let decrypted = encryption.decrypt(&encrypted, &tenant_ctx)?;
```
## ๐ Project Structure
```
.
corteq/ # Framework library crate
โโโ src/
โ โโโ lib.rs # Main library exports
โ โโโ auth.rs # JWT authentication
โ โโโ cache.rs # Tenant caching layer
โ โโโ database/ # RLS database wrapper
โ โโโ domain.rs # Tenant, TenantContext models
โ โโโ encryption.rs # AES-256-GCM encryption
โ โโโ error.rs # Framework error types
โ โโโ middleware.rs # Tenant context middleware
โ โโโ repository/ # Tenant repository
โโโ tests/ # Integration & security tests
```
## ๐ Documentation
- **[API Documentation](https://docs.rs/corteq)** - Rust API docs (run `cargo doc --open`)
## ๐งช Running Tests
```bash
# All tests
cargo test
# Specific test suite
cargo test --test test_encryption
cargo test --test test_security_critical
cargo test --test test_rls_isolation
# With output
cargo test -- --nocapture
# Integration tests only
cargo test --test '*'
```
## ๐จ Development Setup
```bash
# 1. Clone repository
git clone https://github.com/Trendium-Labs/corteq
cd corteq
# 2. Start PostgreSQL
docker-compose up -d postgres
# 3. Run migrations (automatic on first run)
# Migrations run automatically when CorteqApp::builder().build() is called
# 4. Run demo app
cargo run --bin server
# 5. Test the API
curl http://localhost:3000/health
# Generate demo token
curl -X POST http://localhost:3000/auth/demo-token \
-H "Content-Type: application/json" \
-d '{"tenant_id": "11111111-1111-1111-1111-111111111111"}'
# Use token
curl -H "Authorization: Bearer <token>" \
http://localhost:3000/api/me
```
## ๐ฏ Use Cases
Perfect for building:
- ๐ข **B2B SaaS platforms**
- ๐ผ **Enterprise applications**
- ๐ฅ **Healthcare systems** (HIPAA compliant)
- ๐ฐ **Financial services** (SOC 2 ready)
- ๐ **Analytics platforms**
- ๐ **EdTech applications**
## ๐ฆ Development Status
### โ
Completed Phases (1-5)
#### Phase 1: Foundation
- [x] Cargo workspace setup (corteq + demo-app)
- [x] Core dependencies configured
- [x] Module structure created
- [x] PostgreSQL Docker Compose setup
- [x] Test infrastructure configured
- [x] Switched to Actix Web
#### Phase 2: Authentication & Middleware
- [x] JWT token encoding/decoding with tenant claims
- [x] Bearer token authentication
- [x] HTTP cookie authentication
- [x] Tenant context middleware
- [x] Tenant caching layer (in-memory)
- [x] Tenant repository for database access
- [x] Demo app with protected routes
#### Phase 3: Row-Level Security
- [x] PostgreSQL RLS migrations
- [x] TenantDatabase wrapper with automatic context setting
- [x] Comprehensive RLS isolation tests (9 tests)
- [x] Non-superuser role for proper RLS testing
- [x] Cross-tenant access blocking verified
#### Phase 4: Security Testing
- [x] SQL injection prevention tests
- [x] Malformed UUID handling tests
- [x] JWT token manipulation tests
- [x] Cache poisoning prevention tests
- [x] Concurrent transaction isolation tests
- [x] Session variable isolation tests
- [x] Tampering detection tests
#### Phase 5: Encryption
- [x] AES-256-GCM encryption service
- [x] Tenant-specific key derivation
- [x] EncryptedData serialization for database storage
- [x] Nonce uniqueness verification
- [x] 11 comprehensive encryption tests
- [x] Cross-tenant encryption isolation
### ๐ Upcoming Phases
- **Phase 6**: RBAC authorization system
- **Phase 7**: Audit logging framework
- **Phase 8**: Rate limiting & throttling
- **Phase 9**: Performance optimization
- **Phase 10**: Documentation & examples
## ๐ข Production Deployment
### Docker
```dockerfile
FROM rust:1.75 AS builder
WORKDIR /app
COPY . .
RUN cargo build --release
FROM debian:bookworm-slim
COPY --from=builder /app/target/release/app /usr/local/bin/
EXPOSE 8080
CMD ["app"]
```
### Environment Variables
```bash
DATABASE_URL=postgres://user:pass@host:5432/db
JWT_SECRET=your-production-secret-key-min-32-chars!!
RUST_LOG=info
SERVER_PORT=8080
```
## ๐ค Contributing
This project is currently in active development. Contributions, issues, and feature requests are welcome!
## ๐ License
Licensed under MIT License ([LICENSE-MIT](LICENSE-MIT))
## ๐ Acknowledgments
Built with these amazing technologies:
- [Actix Web](https://actix.rs/) - Fast, pragmatic web framework
- [SQLx](https://github.com/launchbadge/sqlx) - Async SQL toolkit
- [PostgreSQL](https://www.postgresql.org/) - Advanced open source database
- [jsonwebtoken](https://github.com/Keats/jsonwebtoken) - JWT implementation
- [aes-gcm](https://github.com/RustCrypto/AEADs) - Authenticated encryption
---
**Built with โค๏ธ by [Trendium Labs](https://trendiumlabs.com)**
**โญ Star this repo if you find it useful!**