# Irene Auth - Architecture & Feature Mapping

## 🏗️ Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│                    FastAPI Application                       │
│  (User's code - uses irene_auth as a library)               │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│               Python Auth Library (irene_auth)               │
│  ┌───────────────────────────────────────────────────────┐  │
│  │  • User models (SQLAlchemy)                          │  │
│  │  • Signup/login workflows                            │  │
│  │  • Refresh token storage                             │  │
│  │  │  • Role-based access control                      │  │
│  │  • Password reset workflow                           │  │
│  │  • Email verification workflow                       │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼ (calls for crypto)
┌─────────────────────────────────────────────────────────────┐
│            Rust Crypto Module (irene_auth._crypto)          │
│  ┌───────────────────────────────────────────────────────┐  │
│  │  • Argon2id password hashing                         │  │
│  │  • Secure random token generation                    │  │
│  │  • Token hashing (for DB)                            │  │
│  │  • JWT encoding/decoding (HS256 + RS256)            │  │
│  │  • Constant-time comparisons                         │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

## 📋 Feature Mapping (All 8 Required Features)

### 1️⃣ User Model (Python/DB)
**Layer**: Python  
**Implementation**: SQLAlchemy model with:
- `id`, `email`, `password_hash`, `is_verified`, `is_active`
- `roles` (many-to-many relationship)
- `created_at`, `updated_at`
- `verification_token_hash`, `reset_token_hash`

### 2️⃣ Password Hashing (Argon2id)
**Layer**: Rust → Python  
**Rust**: `hash_password()`, `verify_password()`  
**Python**: Calls Rust module for all password operations  
**Security**: Argon2id (memory-hard, GPU-resistant)

### 3️⃣ Signup + Login
**Layer**: Python  
**Signup Flow**:
1. Validate email/password
2. Hash password (Rust)
3. Generate verification token (Rust)
4. Store user + token hash in DB
5. Send verification email

**Login Flow**:
1. Find user by email
2. Verify password (Rust)
3. Check if verified & active
4. Generate JWT access token (Rust)
5. Generate refresh token (Rust)
6. Return tokens

### 4️⃣ JWT Access Tokens
**Layer**: Rust → Python  
**Rust**: `jwt_encode()`, `jwt_decode()`  
**Python**: Wrapper functions + FastAPI dependencies  
**Support**: HS256 (HMAC) and RS256 (RSA)  
**Features**: Expiration, validation, claims

### 5️⃣ Refresh Tokens
**Layer**: Python  
**Implementation**:
- Store refresh token hashes in DB
- Associate with user + expiration
- Revocation support
- Rotation on use (optional)

**Rust**: Token generation + hashing  
**Python**: DB storage, validation, revocation

### 6️⃣ Role-Based Access Control (RBAC)
**Layer**: Python  
**Implementation**:
- `Role` model (name, permissions)
- `User` ↔ `Role` many-to-many
- FastAPI dependencies: `require_role()`, `require_any_role()`
- Permission checking in endpoints

### 7️⃣ Password Reset
**Layer**: Python  
**Workflow**:
1. User requests reset (email)
2. Generate reset token (Rust)
3. Store token hash + expiration in DB
4. Send reset email with token
5. User submits token + new password
6. Validate token (Rust constant-time)
7. Hash new password (Rust)
8. Update user, invalidate token

### 8️⃣ Email Verification
**Layer**: Python  
**Workflow**:
1. On signup, generate verification token (Rust)
2. Store token hash in DB
3. Send verification email
4. User clicks link with token
5. Validate token (Rust constant-time)
6. Mark user as verified
7. Invalidate token

## 🔐 Security Model

### Rust Crypto Responsibilities
- ✅ Password hashing (Argon2id: 64 MiB, 3 iterations)
- ✅ Secure random token generation (32 bytes default)
- ✅ Token hashing for DB storage (SHA-256)
- ✅ JWT encoding/decoding with validation
- ✅ Constant-time comparisons (passwords, tokens)

### Python Auth Responsibilities
- ✅ Database models & migrations
- ✅ User workflows (signup, login, reset, verify)
- ✅ Token storage & revocation
- ✅ Role & permission management
- ✅ FastAPI integration (dependencies, middleware)

### Security Guarantees
- **No plaintext passwords**: All passwords hashed with Argon2id
- **No plaintext tokens in DB**: All tokens hashed before storage
- **Constant-time comparisons**: Prevents timing attacks
- **JWT validation**: Expiration, signature, claims checked
- **Token expiration**: All tokens have TTL
- **Revocation support**: Tokens can be invalidated
- **RBAC**: Fine-grained access control

## 🔧 Technology Stack

### Rust (Crypto Layer)
- `argon2` - Password hashing
- `rand` - Cryptographically secure RNG
- `sha2` - Token hashing
- `jsonwebtoken` - JWT encoding/decoding
- `subtle` - Constant-time comparisons
- `pyo3` - Python bindings

### Python (Auth Layer)
- `SQLAlchemy` - ORM
- `FastAPI` - Web framework integration
- `pydantic` - Data validation
- `python-multipart` - Form handling
- `email-validator` - Email validation

## 📦 Package Structure

```
irene-auth/
├── src/                          # Rust source
│   ├── lib.rs                    # Module entry
│   ├── password.rs               # Argon2id hashing
│   ├── token.rs                  # Token generation & hashing
│   ├── jwt.rs                    # JWT operations
│   └── python_bindings.rs        # PyO3 bindings
├── python/irene_auth/            # Python package
│   ├── __init__.py               # Package exports
│   ├── models.py                 # User, Role, RefreshToken models
│   ├── auth.py                   # Signup/login logic
│   ├── password_reset.py         # Password reset flow
│   ├── email_verification.py    # Email verification flow
│   ├── rbac.py                   # Role-based access control
│   ├── dependencies.py           # FastAPI dependencies
│   └── utils.py                  # Helpers
├── examples/                     # Usage examples
│   └── fastapi_app.py            # Complete FastAPI example
├── Cargo.toml                    # Rust config
├── pyproject.toml                # Python config
└── README.md                     # Documentation
```

## 🎯 Design Principles

1. **Security First**: All crypto in Rust, audited crates only
2. **Clear Separation**: Rust = crypto, Python = workflows
3. **Production Ready**: Proper error handling, logging, validation
4. **Extensible**: Easy to add new roles, permissions, workflows
5. **Well Documented**: Every function, class, and flow explained
6. **Best Practices**: Follow OWASP guidelines, secure defaults

## 🚀 Usage Flow Example

```python
from fastapi import FastAPI, Depends
from irene_auth import AuthManager, require_role
from irene_auth.models import User

app = FastAPI()
auth = AuthManager(database_url="sqlite:///./auth.db", secret_key="...")

# Signup
@app.post("/signup")
async def signup(email: str, password: str):
    user = await auth.signup(email, password)
    # Send verification email
    return {"message": "Check your email"}

# Login
@app.post("/login")
async def login(email: str, password: str):
    tokens = await auth.login(email, password)
    return tokens  # {access_token, refresh_token}

# Protected endpoint (requires authentication)
@app.get("/profile")
async def profile(user: User = Depends(auth.get_current_user)):
    return user

# Admin-only endpoint (requires role)
@app.get("/admin")
async def admin(user: User = Depends(require_role("admin"))):
    return {"message": "Admin access granted"}
```

---

**All 8 features will be fully implemented and production-ready.**
