# Authentik SSO Automated Setup Guide

This guide explains how to use the automated Authentik SSO setup for the AI Tax Agent platform.

## Overview

The AI Tax Agent platform uses Authentik for Single Sign-On (SSO) with automated configuration through blueprints. This provides:

- **Automated application configuration** using Authentik blueprints
- **Secure secret generation** for all OAuth clients
- **Role-based access control** with predefined user groups
- **ForwardAuth integration** with Traefik for seamless authentication

## Quick Start

### 1. Deploy Infrastructure

```bash
# Generate secure secrets and deploy infrastructure
make generate-secrets
make run
```

### 2. Complete Initial Setup

**Option A: Automated (recommended)**

```bash
make setup-sso
```

**Option B: Manual Steps**

```bash
# Step 1: Complete initial Authentik setup manually
# Open https://auth.local/if/flow/initial-setup/
# Use credentials: admin@local / admin123

# Step 2: Get API token and import configuration
make complete-authentik-setup
make setup-authentik
```

### 3. Verify Setup

```bash
make verify
```

All services should redirect to Authentik for authentication.

## Detailed Process

### Step 1: Infrastructure Deployment

```bash
# Generate secure secrets
make generate-secrets

# Deploy all services
make run
```

This will:

- Generate secure random secrets for all services
- Deploy Authentik with the latest version (2025.8.3)
- Mount the bootstrap blueprint for automatic configuration

### Step 2: Initial Authentik Setup

The system will detect if initial setup is needed and guide you through it:

```bash
make complete-authentik-setup
```

**Manual Setup (if automated fails):**

1. Open https://auth.local/if/flow/initial-setup/
2. Use these credentials:
   - Email: `admin@local`
   - Password: `admin123`
3. Complete the setup wizard

### Step 3: Blueprint Import

```bash
make setup-authentik
```

This will automatically:

- Import the blueprint configuration
- Create user groups (Administrators, Tax Reviewers, Accountants, Clients)
- Configure OAuth2 providers for API and Grafana
- Set up ForwardAuth proxy for Traefik integration
- Create applications with proper redirect URIs

## Configuration Details

### User Groups Created

| Group              | Description           | Permissions                            |
| ------------------ | --------------------- | -------------------------------------- |
| **Administrators** | System administrators | Full access to all services            |
| **Tax Reviewers**  | Review extracted data | Access to review portal, read-only API |
| **Accountants**    | Firm accountants      | Access to client data, forms           |
| **Clients**        | End clients           | Limited access to own data             |

### Applications Configured

#### 1. AI Tax Agent API

- **Client ID**: `ai-tax-agent-api`
- **Type**: OAuth2/OIDC
- **Scopes**: `openid`, `profile`, `email`, `roles`
- **Redirect URIs**:
  - `https://api.local/auth/callback`
  - `https://review.local/auth/callback`

#### 2. Grafana

- **Client ID**: `grafana`
- **Type**: OAuth2/OIDC
- **Scopes**: `openid`, `profile`, `email`
- **Redirect URI**: `https://grafana.local/login/generic_oauth`

#### 3. ForwardAuth Proxy

- **Type**: Proxy Provider
- **Mode**: `forward_single`
- **External Host**: `https://api.local`
- **Skip Paths**: `/health`, `/metrics`, `/docs`, `/openapi.json`

### Environment Variables

The setup automatically configures these environment variables:

```bash
# Authentik Configuration
AUTHENTIK_SECRET_KEY=<generated-50-char-secret>
AUTHENTIK_BOOTSTRAP_EMAIL=admin@local
AUTHENTIK_BOOTSTRAP_PASSWORD=admin123
AUTHENTIK_BOOTSTRAP_TOKEN=<auto-generated-api-token>

# OAuth Client Secrets
AUTHENTIK_API_CLIENT_SECRET=<generated-32-char-secret>
AUTHENTIK_GRAFANA_CLIENT_SECRET=<generated-32-char-secret>
```

## Verification

### 1. Check Service Status

```bash
make status
```

All Authentik services should show as "healthy":

- `authentik-server`
- `authentik-worker`
- `authentik-outpost`
- `authentik-db`
- `authentik-redis`

### 2. Test Authentication

```bash
make verify
```

Should show:

- ✅ Authentik (https://auth.local) -> 200

### 3. Access URLs

- **Authentik Admin**: https://auth.local
- **API Gateway**: https://api.local (redirects to Authentik)
- **Grafana**: https://grafana.local (SSO enabled)
- **Review Portal**: https://review.local (SSO enabled)

## Troubleshooting

### Common Issues

#### 1. Initial Setup Page Still Shows

```bash
# Check if setup completed properly
curl -k --resolve 'auth.local:443:127.0.0.1' -I https://auth.local/if/flow/initial-setup/
```

If you get HTTP 200, setup is still needed. Complete it manually.

#### 2. Blueprint Import Failed

```bash
# Check Authentik logs
make logs-service SERVICE=authentik-server

# Re-run blueprint import
make setup-authentik
```

#### 3. API Token Issues

```bash
# Manually create API token
# 1. Login to https://auth.local
# 2. Go to Admin Interface > Tokens
# 3. Create new token
# 4. Update .env file:
echo "AUTHENTIK_BOOTSTRAP_TOKEN=your-token-here" >> infra/compose/.env
```

#### 4. Services Not Redirecting to Authentik

```bash
# Check Traefik configuration
make logs-service SERVICE=traefik

# Restart Authentik components
make restart-authentik
```

### Debug Mode

Enable debug logging:

```bash
# Add to docker-compose.local.yml
AUTHENTIK_LOG_LEVEL: debug
```

## Security Considerations

### Production Deployment

1. **Change default passwords** immediately after setup
2. **Use strong secret keys** (automatically generated)
3. **Enable HTTPS** with valid certificates
4. **Configure proper CORS** origins
5. **Set up backup** for Authentik database
6. **Enable audit logging**

### Secret Management

- All secrets are automatically generated with sufficient entropy
- Client secrets are stored in environment variables
- API tokens should be rotated regularly
- Never commit `.env` file to version control

## Integration Examples

### FastAPI Service Integration

```python
from libs.security import AuthenticationHeaders

@app.get("/protected")
async def protected_endpoint(request: Request):
    auth = AuthenticationHeaders(request)

    if not auth.has_role("Tax Reviewers"):
        raise HTTPException(403, "Insufficient permissions")

    return {"user": auth.authenticated_user}
```

### Grafana Configuration

Grafana is automatically configured with these settings:

```ini
[auth.generic_oauth]
enabled = true
name = Authentik
client_id = grafana
client_secret = <auto-generated>
scopes = openid profile email
auth_url = https://auth.local/application/o/authorize/
token_url = https://auth.local/application/o/token/
api_url = https://auth.local/application/o/userinfo/
```

## Support

For issues with the automated setup:

1. Check the logs: `make logs-service SERVICE=authentik-server`
2. Verify network connectivity: `make verify`
3. Review the blueprint file: `infra/compose/authentik/bootstrap.yaml`
4. Check Traefik routing: `make logs-service SERVICE=traefik`

For Authentik-specific issues, refer to the [official documentation](https://goauthentik.io/docs/).
