# Authentik - SSO / Identity Provider

**Host**: Calypso (DS723+)  
**Domain**: `sso.vish.gg`  
**Ports**: 9000 (HTTP), 9443 (HTTPS)  
**Compose File**: `Calypso/authentik/docker-compose.yaml`

## Overview

Authentik provides Single Sign-On (SSO) and identity management for homelab services. It supports:
- OAuth2 / OpenID Connect
- SAML 2.0
- LDAP
- Proxy authentication (forward auth)
- SCIM provisioning

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                        Cloudflare DNS                            │
│                      (sso.vish.gg → Calypso)                    │
└─────────────────────┬───────────────────────────────────────────┘
                      │
                      ▼
┌─────────────────────────────────────────────────────────────────┐
│                   Synology Reverse Proxy                         │
│              (sso.vish.gg → localhost:9000)                     │
└─────────────────────┬───────────────────────────────────────────┘
                      │
                      ▼
┌─────────────────────────────────────────────────────────────────┐
│                     Authentik Stack                              │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │ authentik-   │  │ authentik-   │  │ authentik-   │          │
│  │   server     │◄─┤   worker     │  │    redis     │          │
│  │  (9000)      │  │              │  │              │          │
│  └──────┬───────┘  └──────┬───────┘  └──────────────┘          │
│         │                 │                                      │
│         ▼                 ▼                                      │
│  ┌────────────────────────────────┐                             │
│  │        authentik-db            │                             │
│  │       (PostgreSQL 16)          │                             │
│  └────────────────────────────────┘                             │
└─────────────────────────────────────────────────────────────────┘
```

## Initial Setup

### 1. Deploy the Stack

Deploy via Portainer GitOps - the stack will auto-pull from the repository.

### 2. Configure DNS

Add DNS record in Cloudflare:
- **Type**: A or CNAME
- **Name**: sso
- **Target**: Your Calypso IP or DDNS hostname
- **Proxy**: Orange cloud ON (recommended for DDoS protection)

### 3. Configure Synology Reverse Proxy

In DSM → Control Panel → Login Portal → Advanced → Reverse Proxy:

| Setting | Value |
|---------|-------|
| Description | Authentik SSO |
| Source Protocol | HTTPS |
| Source Hostname | sso.vish.gg |
| Source Port | 443 |
| Enable HSTS | Yes |
| Destination Protocol | HTTP |
| Destination Hostname | localhost |
| Destination Port | 9000 |

**Custom Headers** (Add these):
| Header | Value |
|--------|-------|
| X-Forwarded-Proto | $scheme |
| X-Forwarded-For | $proxy_add_x_forwarded_for |
| Host | $host |

**WebSocket** (Enable):
- Check "Enable WebSocket"

### 4. Initial Admin Setup

1. Navigate to `https://sso.vish.gg/if/flow/initial-setup/`
2. Create your admin account (default username: akadmin)
3. Set a strong password
4. Complete the setup wizard

## Integrating Services

### Grafana (gf.vish.gg)

1. **In Authentik**: Create OAuth2/OIDC Provider
   - Name: Grafana
   - Client ID: (copy this)
   - Client Secret: (generate and copy)
   - Redirect URIs: `https://gf.vish.gg/login/generic_oauth`

2. **In Grafana** (grafana.ini or environment):
   ```ini
   [auth.generic_oauth]
   enabled = true
   name = Authentik
   allow_sign_up = true
   client_id = YOUR_CLIENT_ID
   client_secret = YOUR_CLIENT_SECRET
   scopes = openid profile email
   auth_url = https://sso.vish.gg/application/o/authorize/
   token_url = https://sso.vish.gg/application/o/token/
   api_url = https://sso.vish.gg/application/o/userinfo/
   role_attribute_path = contains(groups[*], 'Grafana Admins') && 'Admin' || 'Viewer'
   ```

### Gitea (git.vish.gg)

1. **In Authentik**: Create OAuth2/OIDC Provider
   - Name: Gitea
   - Redirect URIs: `https://git.vish.gg/user/oauth2/authentik/callback`

2. **In Gitea**: Settings → Authentication → Add OAuth2
   - Provider: OpenID Connect
   - Client ID: (from Authentik)
   - Client Secret: (from Authentik)
   - OpenID Connect Auto Discovery URL: `https://sso.vish.gg/application/o/gitea/.well-known/openid-configuration`

### Seafile (seafile.vish.gg)

1. **In Authentik**: Create OAuth2/OIDC Provider
   - Name: Seafile
   - Redirect URIs: `https://seafile.vish.gg/oauth/callback/`

2. **In Seafile** (seahub_settings.py):
   ```python
   ENABLE_OAUTH = True
   OAUTH_ENABLE_INSECURE_TRANSPORT = False
   OAUTH_CLIENT_ID = 'YOUR_CLIENT_ID'
   OAUTH_CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
   OAUTH_REDIRECT_URL = 'https://seafile.vish.gg/oauth/callback/'
   OAUTH_PROVIDER_DOMAIN = 'sso.vish.gg'
   OAUTH_AUTHORIZATION_URL = 'https://sso.vish.gg/application/o/authorize/'
   OAUTH_TOKEN_URL = 'https://sso.vish.gg/application/o/token/'
   OAUTH_USER_INFO_URL = 'https://sso.vish.gg/application/o/userinfo/'
   OAUTH_SCOPE = ['openid', 'profile', 'email']
   OAUTH_ATTRIBUTE_MAP = {
       'id': (True, 'email'),
       'email': (True, 'email'),
       'name': (False, 'name'),
   }
   ```

### Forward Auth (Proxy Provider)

For services that don't support OAuth natively, use Authentik's proxy provider:

1. **In Authentik**: Create Proxy Provider
   - Name: Protected Service
   - External Host: https://service.vish.gg
   - Mode: Forward auth (single application)

2. **In Synology Reverse Proxy**: Add auth headers
   - Forward requests to Authentik's outpost first

## Backup & Recovery

### Data Locations
| Data | Path | Backup Priority |
|------|------|-----------------|
| Database | `/volume1/docker/authentik/database` | Critical |
| Media | `/volume1/docker/authentik/media` | High |
| Templates | `/volume1/docker/authentik/templates` | Medium |

### Backup Command
```bash
# On Calypso via SSH
docker exec Authentik-DB pg_dump -U authentik authentik > /volume1/backups/authentik_$(date +%Y%m%d).sql
```

### Restore
```bash
docker exec -i Authentik-DB psql -U authentik authentik < backup.sql
```

## Troubleshooting

### Check Logs
```bash
docker logs Authentik-SERVER
docker logs Authentik-WORKER
```

### Database Connection Issues
```bash
docker exec Authentik-DB pg_isready -U authentik
```

### Reset Admin Password
```bash
docker exec -it Authentik-SERVER ak create_recovery_key 10 akadmin
```
This creates a recovery link valid for 10 minutes.

## Security Considerations

- Authentik is the gateway to all services - protect it well
- Use a strong admin password
- Enable 2FA for admin accounts
- Regularly rotate the AUTHENTIK_SECRET_KEY (requires re-authentication)
- Keep the PostgreSQL password secure
- Consider IP restrictions in Cloudflare for admin paths

## Related Documentation

- [Official Docs](https://docs.goauthentik.io/)
- [OAuth2 Provider Setup](https://docs.goauthentik.io/docs/providers/oauth2/)
- [Proxy Provider Setup](https://docs.goauthentik.io/docs/providers/proxy/)
