# Azure Managed Redis Setup Guide (Entra ID Authentication)

Your application is now configured to use Azure Managed Redis with Microsoft Entra ID authentication (the modern, secure approach).

## Prerequisites

1. **Azure subscription** - create one for free at https://azure.com
2. **Python 3.7+** language environment
3. **Azure CLI** installed and authenticated (`az login`)

## Dependencies

The following packages are automatically included in your requirements.txt:
- `redis` - The Redis Python client
- `redis-entraid` - Redis Microsoft Entra ID authentication extension  
- `azure-identity` - Azure authentication library

## Azure Managed Redis Setup

### 1. Create Azure Managed Redis Cache

Using Azure Portal:
1. Go to Azure Portal → Create a resource → Databases → Azure Managed Redis
2. Configure:
   - **Resource Group**: Create new or use existing
   - **Cache Name**: Choose a unique name (e.g., `my-app-redis`)
   - **Location**: Choose your preferred region
   - **Pricing tier**: Start with Basic for development
   - **Public endpoint**: Enable for this setup
   - **Microsoft Entra ID**: Enabled by default ✓

Using Azure CLI:
```bash
# Create resource group (if needed)
az group create --name my-redis-rg --location eastus

# Create Azure Managed Redis cache
az redisenterprise create \
  --resource-group my-redis-rg \
  --name my-app-redis \
  --location eastus \
  --sku Basic_B0 \
  --tags environment=development
```

### 2. Add Yourself as Redis User

**Important**: You must add yourself as a Redis user to access the cache.

Using Azure Portal:
1. Go to your Redis cache → Data Access Configuration
2. Click "Add" → "Add Redis User"
3. Select your user account
4. Grant appropriate permissions (Redis Contributor)

Using Azure CLI:
```bash
# Get your user ID
USER_ID=$(az ad signed-in-user show --query id -o tsv)

# Add yourself as Redis user
az redisenterprise database access-policy-assignment create \
  --resource-group my-redis-rg \
  --cluster-name my-app-redis \
  --database-name default \
  --access-policy-assignment-name my-user \
  --object-id $USER_ID \
  --access-policy-name "Data Contributor"
```

### 3. Get Connection Information

From Azure Portal:
1. Go to your Redis cache → Overview
2. Copy the **Host name** (e.g., `my-app-redis.eastus.redisenterprise.cache.azure.net`)
3. Note the **Port**: 10000 (default for Managed Redis)

### 4. Update Your .env File

```env
# Update with your actual cache hostname
AZURE_REDIS_HOST=my-app-redis.eastus.redisenterprise.cache.azure.net
AZURE_REDIS_PORT=10000

# Local fallback (optional)
REDIS_URL=redis://localhost:6379/0
```

### 5. Authenticate with Azure

Before running your application, authenticate with Azure:

```bash
# Login to Azure (opens browser)
az login

# Or for non-interactive environments
az login --service-principal --username <app-id> --password <password> --tenant <tenant>
```

## How It Works

### Authentication Flow
1. Application uses `DefaultAzureCredential` to authenticate
2. Tries multiple credential sources in order:
   - Environment variables (service principal)
   - Managed identity (if running on Azure)
   - Azure CLI credentials (`az login`)
   - Interactive browser login

### Code Structure
```python
# Your Redis client automatically handles:
credential_provider = create_from_default_azure_credential(
    ("https://redis.azure.com/.default",),
)

client = redis.Redis(
    host=redis_host,
    port=10000,  # Managed Redis port
    ssl=True,
    credential_provider=credential_provider
)
```

## Testing the Setup

Install dependencies and test:
```bash
# Install new dependencies
pip install -r requirements.txt

# Test database and Redis connections
python test_postgres.py

# Start the application
python -m src.app.main_v2
```

## Port Configuration

- **Azure Managed Redis**: Port **10000** (SSL enabled by default)
- **Azure Cache for Redis**: Port 6380 (if you use the older service)
- **Local Redis**: Port 6379 (fallback for development)

## Benefits of Entra ID Authentication

✅ **No passwords or keys to manage**
✅ **Azure AD integration with role-based access**
✅ **Automatic credential rotation**
✅ **Centralized access management**
✅ **Audit logging through Azure AD**
✅ **Works with managed identities**

## Production Deployment

### Using Managed Identity (Recommended)
```bash
# Enable managed identity on your Azure App Service/Container
az webapp identity assign --resource-group <rg> --name <app-name>

# Grant Redis access to the managed identity
PRINCIPAL_ID=$(az webapp identity show --resource-group <rg> --name <app-name> --query principalId -o tsv)

az redisenterprise database access-policy-assignment create \
  --resource-group my-redis-rg \
  --cluster-name my-app-redis \
  --database-name default \
  --access-policy-assignment-name app-identity \
  --object-id $PRINCIPAL_ID \
  --access-policy-name "Data Contributor"
```

### Using Service Principal
Set these environment variables in production:
```env
AZURE_CLIENT_ID=your-app-registration-id
AZURE_CLIENT_SECRET=your-client-secret  
AZURE_TENANT_ID=your-tenant-id
```

## Troubleshooting

### Authentication Issues
```bash
# Check if you're logged in to Azure
az account show

# Re-login if needed
az login

# Check Redis permissions
az redisenterprise database access-policy-assignment list \
  --resource-group my-redis-rg \
  --cluster-name my-app-redis \
  --database-name default
```

### Connection Issues
- Ensure your cache allows public access (for development)
- Check firewall rules if connection fails
- Verify the hostname is correct (no https:// prefix needed)
- Port 10000 is the default for Managed Redis

### Fallback Behavior
The application gracefully falls back:
1. **Azure Managed Redis** (preferred)
2. **Local Redis** (development)  
3. **In-memory Redis** (ultimate fallback)

This ensures your app works in any environment!