# Mailu Deployment Architecture for Bakery-IA Project

## Executive Summary

This document outlines the recommended architecture for deploying Mailu email services across development and production environments for the Bakery-IA project. The solution addresses DNSSEC validation requirements using CoreDNS with DNS-over-TLS while maintaining consistency across different Kubernetes platforms.

## Environment Overview

### Development Environment
- **Platform**: Kind (Kubernetes in Docker) or Colima
- **Purpose**: Local development and testing
- **Characteristics**: Ephemeral, single-node, resource-constrained

### Production Environment
- **Platform**: MicroK8s on Ubuntu VPS
- **Purpose**: Production email services
- **Characteristics**: Single-node or small cluster, persistent storage, production-grade reliability

## Core Requirements

1. **DNSSEC Validation**: Mailu v1.9+ requires DNSSEC-validating resolver
2. **Cross-Environment Consistency**: Unified approach for dev and prod
3. **Resource Efficiency**: Optimized for constrained environments
4. **Reliability**: Production-grade availability and monitoring

## Architectural Solution

### DNS Resolution Strategy

**Approach**: Use CoreDNS with DNS-over-TLS to Cloudflare (1.1.1.1) for DNSSEC validation

#### Benefits:
- ✅ Leverages existing Kubernetes DNS infrastructure
- ✅ No additional pods required (uses CoreDNS already in cluster)
- ✅ DNSSEC validation provided by Cloudflare's DNS-over-TLS
- ✅ Consistent behavior across dev and prod
- ✅ Meets Mailu's DNSSEC requirements
- ✅ Simple and reliable

### Implementation Components

#### 1. CoreDNS Configuration with DNS-over-TLS

```yaml
# CoreDNS Corefile configuration for DNSSEC via DNS-over-TLS
.:53 {
    errors
    health {
       lameduck 5s
    }
    ready
    kubernetes cluster.local in-addr.arpa ip6.arpa {
       pods insecure
       fallthrough in-addr.arpa ip6.arpa
       ttl 30
    }
    prometheus :9153
    forward . tls://1.1.1.1 tls://1.0.0.1 {
       tls_servername cloudflare-dns.com
       health_check 5s
    }
    cache 30 {
       disable success cluster.local
       disable denial cluster.local
    }
    loop
    reload
    loadbalance
}
```

#### 2. Mailu Configuration (values.yaml)

```yaml
# Production-tuned Mailu configuration
global:
  # Using Kubernetes CoreDNS for DNS resolution
  # CoreDNS is configured with DNS-over-TLS (Cloudflare) for DNSSEC validation
  custom_dns_servers: "10.152.183.10"  # MicroK8s CoreDNS IP (adjust for your cluster)

# DNS configuration - use Kubernetes DNS (ClusterFirst)
# CoreDNS provides DNSSEC validation via DNS-over-TLS to Cloudflare
admin:
  dnsPolicy: "ClusterFirst"

rspamd:
  dnsPolicy: "ClusterFirst"

# Environment-specific configurations
persistence:
  enabled: true
  storageClass: ""  # Use cluster default

replicas: 1  # Increase in production as needed

# Security settings
secretKey: "generate-strong-key-here"
```

### Environment-Specific Adaptations

#### Development (Kind/Colima)

**Optimizations:**
- Use hostPath volumes for persistence
- Reduce resource requests/limits
- Disable or simplify monitoring
- Use NodePort for external access

**Deployment:**
```bash
# Get CoreDNS service IP
COREDNS_IP=$(kubectl get svc kube-dns -n kube-system -o jsonpath='{.spec.clusterIP}')

# Deploy Mailu with dev-specific values
helm upgrade --install mailu mailu/mailu \
  --namespace bakery-ia \
  -f infrastructure/platform/mail/mailu-helm/values.yaml \
  -f infrastructure/platform/mail/mailu-helm/dev/values.yaml \
  --set global.custom_dns_servers=$COREDNS_IP
```

#### Production (MicroK8s/Ubuntu)

**Enhancements:**
- Use microk8s-hostpath for storage
- Enable monitoring and logging
- Configure proper ingress with TLS
- Set up backup solutions

**Deployment:**
```bash
# Enable required MicroK8s addons
microk8s enable dns storage ingress

# Get CoreDNS service IP
COREDNS_IP=$(kubectl get svc kube-dns -n kube-system -o jsonpath='{.spec.clusterIP}')

# Deploy Mailu with production values
helm upgrade --install mailu mailu/mailu \
  --namespace bakery-ia \
  -f infrastructure/platform/mail/mailu-helm/values.yaml \
  -f infrastructure/platform/mail/mailu-helm/prod/values.yaml \
  --set global.custom_dns_servers=$COREDNS_IP
```

## Verification Procedures

### DNSSEC Validation Test

```bash
# Test DNS resolution from within a Mailu pod
kubectl exec -it -n bakery-ia deploy/mailu-admin -- bash

# Test DNSSEC validation (via CoreDNS -> Cloudflare DNS-over-TLS)
dig +short +dnssec +adflag example.org A

# Should show AD flag in response indicating DNSSEC validation
```

### Service Health Checks

```bash
# Check CoreDNS is running
kubectl get pods -n kube-system -l k8s-app=kube-dns

# Check Mailu components
kubectl get pods -n bakery-ia | grep mailu
kubectl logs -n bakery-ia -l app.kubernetes.io/name=mailu
```

## Monitoring and Maintenance

### Production Monitoring Setup

CoreDNS exposes Prometheus metrics on port 9153 by default. Monitor:
- DNS query latency
- DNS query success/failure rates
- DNS cache hit ratio

### Backup Strategy

**Production:**
- Daily Velero backups of bakery-ia namespace
- Weekly database dumps
- Monthly full cluster snapshots

**Development:**
- On-demand backups before major changes
- Volume snapshots for critical data

## Troubleshooting Guide

### Common Issues and Solutions

**Issue: DNS resolution failures**
- Verify CoreDNS pods are running
- Check CoreDNS logs: `kubectl logs -n kube-system -l k8s-app=kube-dns`
- Test DNS resolution: `kubectl run -it --rm dns-test --image=busybox -- nslookup google.com`

**Issue: Mailu pods failing to start**
- Confirm DNS configuration in values.yaml
- Verify CoreDNS service is reachable
- Check resource availability

**Issue: DNSSEC validation errors**
- Ensure CoreDNS is configured with DNS-over-TLS
- Test with: `dig +dnssec example.org`
- Verify Cloudflare DNS is reachable

**Issue: Performance problems**
- Monitor CPU/memory usage
- Adjust resource limits
- Consider scaling replicas

## Migration Path

### From Development to Production

1. **Configuration Migration**
   - Update storage class from hostPath to production storage
   - Adjust resource requests/limits
   - Enable monitoring and logging

2. **Data Migration**
   - Export development data
   - Import into production environment
   - Verify data integrity

3. **DNS Configuration**
   - Update DNS records to point to production
   - Verify TLS certificates
   - Test email delivery

## Security Considerations

### Production Security Hardening

1. **Network Security**
   - Implement network policies
   - Restrict ingress/egress traffic
   - Use TLS for all external communications

2. **Access Control**
   - Implement RBAC for Mailu namespace
   - Restrict admin access
   - Use strong authentication

3. **Monitoring and Alerting**
   - Set up anomaly detection
   - Configure alert thresholds
   - Implement log retention policies

## Cost Optimization

### Resource Management

**Development:**
- Use minimal resource allocations
- Scale down when not in use
- Clean up unused resources

**Production:**
- Right-size resource requests
- Implement auto-scaling where possible
- Monitor and optimize usage patterns

## Conclusion

This architecture provides a robust, consistent solution for deploying Mailu across development and production environments. By using CoreDNS with DNS-over-TLS to Cloudflare, we ensure compliance with Mailu's DNSSEC requirements while maintaining simplicity and reliability.

The solution is designed to be:
- **Simple**: Uses existing Kubernetes DNS infrastructure
- **Consistent**: Same core architecture across environments
- **Reliable**: Production-grade availability
- **Efficient**: No additional pods required for DNS

This approach aligns with the Bakery-IA project's requirements for a secure, reliable email infrastructure that can be consistently deployed across different environments.
