# Keycloak Deployment Guide

This guide covers deploying and configuring Keycloak for the Sankofa Phoenix platform.

## Prerequisites

- Kubernetes cluster with admin access
- kubectl configured
- Helm 3.x installed
- PostgreSQL database (for Keycloak persistence)
- Domain name configured (e.g., `keycloak.sankofa.nexus`)

## Deployment Steps

### 1. Deploy Keycloak via Helm

```bash
# Add Keycloak Helm repository
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update

# Create namespace
kubectl create namespace keycloak

# Deploy Keycloak
helm install keycloak bitnami/keycloak \
  --namespace keycloak \
  --set auth.adminUser=admin \
  --set auth.adminPassword=$(openssl rand -base64 32) \
  --set postgresql.enabled=true \
  --set postgresql.auth.postgresPassword=$(openssl rand -base64 32) \
  --set ingress.enabled=true \
  --set ingress.hostname=keycloak.sankofa.nexus \
  --set ingress.tls=true \
  --set ingress.certManager=true \
  --set service.type=ClusterIP \
  --set service.port=8080
```

### 2. Configure Keycloak Clients

Apply the client configuration:

```bash
kubectl apply -f gitops/apps/keycloak/keycloak-clients.yaml
```

Or configure manually via Keycloak Admin Console:

#### Portal Client
- **Client ID**: `portal-client`
- **Client Protocol**: `openid-connect`
- **Access Type**: `confidential`
- **Valid Redirect URIs**: 
  - `https://portal.sankofa.nexus/*`
  - `http://localhost:3000/*` (for development)
- **Web Origins**: `+`
- **Standard Flow Enabled**: Yes
- **Direct Access Grants Enabled**: Yes

#### API Client
- **Client ID**: `api-client`
- **Client Protocol**: `openid-connect`
- **Access Type**: `confidential`
- **Service Accounts Enabled**: Yes
- **Standard Flow Enabled**: Yes

### 3. Configure Multi-Realm Support

For multi-tenant support, create realms per tenant:

```bash
# Create realm for tenant
kubectl exec -it -n keycloak deployment/keycloak -- \
  /opt/bitnami/keycloak/bin/kcadm.sh create realms \
  -s realm=tenant-1 \
  -s enabled=true \
  --no-config \
  --server http://localhost:8080 \
  --realm master \
  --user admin \
  --password $(kubectl get secret keycloak-admin -n keycloak -o jsonpath='{.data.password}' | base64 -d)
```

### 4. Configure Identity Providers

#### LDAP/Active Directory
1. Navigate to Identity Providers in Keycloak Admin Console
2. Add LDAP provider
3. Configure connection settings:
   - **Vendor**: Active Directory (or other)
   - **Connection URL**: `ldap://your-ldap-server:389`
   - **Users DN**: `ou=Users,dc=example,dc=com`
   - **Bind DN**: `cn=admin,dc=example,dc=com`
   - **Bind Credential**: (stored in secret)

#### SAML Providers
1. Add SAML 2.0 provider
2. Configure:
   - **Entity ID**: Your SAML entity ID
   - **SSO URL**: Your SAML SSO endpoint
   - **Signing Certificate**: Your SAML signing certificate

### 5. Enable Blockchain Identity Verification

For blockchain-based identity verification:

1. Install Keycloak Identity Provider plugin (if available)
2. Configure blockchain connection:
   - **Blockchain RPC URL**: `https://besu.sankofa.nexus:8545`
   - **Contract Address**: (deployed identity contract)
   - **Private Key**: (stored in Kubernetes Secret)

### 6. Configure Environment Variables

Update API service environment variables:

```yaml
env:
  - name: KEYCLOAK_URL
    value: "https://keycloak.sankofa.nexus"
  - name: KEYCLOAK_REALM
    value: "master"  # or tenant-specific realm
  - name: KEYCLOAK_CLIENT_ID
    value: "api-client"
  - name: KEYCLOAK_CLIENT_SECRET
    valueFrom:
      secretKeyRef:
        name: keycloak-client-secret
        key: api-client-secret
```

### 7. Set Up Secrets

Create Kubernetes secrets for client credentials:

```bash
# Create secret for API client
kubectl create secret generic keycloak-client-secret \
  --from-literal=api-client-secret=$(openssl rand -base64 32) \
  --namespace keycloak

# Create secret for portal client
kubectl create secret generic keycloak-portal-secret \
  --from-literal=portal-client-secret=$(openssl rand -base64 32) \
  --namespace keycloak
```

### 8. Configure Cloudflare Access

If using Cloudflare Zero Trust:

1. Configure Cloudflare Access application for Keycloak
2. Set domain: `keycloak.sankofa.nexus`
3. Configure access policies (see `cloudflare/access-policies.yaml`)
4. Require MFA for admin access

### 9. Verify Deployment

```bash
# Check Keycloak pods
kubectl get pods -n keycloak

# Check Keycloak service
kubectl get svc -n keycloak

# Test Keycloak health
curl https://keycloak.sankofa.nexus/health

# Access Admin Console
# https://keycloak.sankofa.nexus/admin
```

### 10. Post-Deployment Configuration

1. **Change Admin Password**: Change default admin password immediately
2. **Configure Email**: Set up SMTP for password reset emails
3. **Enable MFA**: Configure TOTP and backup codes
4. **Set Up Themes**: Customize Keycloak themes for branding
5. **Configure Events**: Set up event listeners for audit logging
6. **Backup Configuration**: Export realm configuration regularly

## Troubleshooting

### Keycloak Not Starting
- Check PostgreSQL connection
- Verify resource limits
- Check logs: `kubectl logs -n keycloak deployment/keycloak`

### Client Authentication Failing
- Verify client secret matches
- Check redirect URIs are correct
- Verify realm name matches

### Multi-Realm Issues
- Ensure realm names match tenant IDs
- Verify realm is enabled
- Check realm configuration

## Security Best Practices

1. **Use Strong Passwords**: Generate strong passwords for all accounts
2. **Enable MFA**: Require MFA for admin and privileged users
3. **Rotate Secrets**: Regularly rotate client secrets
4. **Monitor Access**: Enable audit logging
5. **Use HTTPS**: Always use TLS for Keycloak
6. **Limit Admin Access**: Restrict admin console access via Cloudflare Access
7. **Backup Regularly**: Export and backup realm configurations

## References

- [Keycloak Documentation](https://www.keycloak.org/documentation)
- [Keycloak Helm Chart](https://github.com/bitnami/charts/tree/main/bitnami/keycloak)
- Client configuration: `gitops/apps/keycloak/keycloak-clients.yaml`

