Seguridad · Service Mesh · Kubernetes

NexusFlow — Linkerd Service Mesh

Plan de implementación Zero-Trust para cluster GKE eu-west · nexusflow-prod

Cliente: NexusFlow SaaS B2B
Cluster: GKE eu-west-1
Microservicios: 8 servicios
Objetivo: SOC 2 Type II · mTLS
Timeline: 3 semanas
Incidentes de seguridad recientes detectados
billing-service accedió directamente a document-store sin pasar por approval-engine — violación de política de acceso. Linkerd ServerAuthorization bloqueará este patrón de forma declarativa.
Arquitectura Linkerd — NexusFlow
Control Plane · linkerd namespace
destiny
identity
proxy-inject
viz (dashboard)
↓ mTLS automático en cada proxy ↓
Data Plane · nexusflow-prod namespace
api-gateway
Ingress
linkerd-proxy
auth-service
JWT / OIDC
linkerd-proxy
approval-engine
v1 90% · v2 10%
linkerd-proxy
billing-service
Restringido
linkerd-proxy
notification-svc
Email / Webhook
linkerd-proxy
audit-log
Inmutable
linkerd-proxy
document-store
S3-compatible
linkerd-proxy
analytics-svc
ClickHouse
linkerd-proxy
🔒
mTLS automático
Todo tráfico entre pods cifrado sin cambios en el código de aplicación.
📊
Golden metrics por ruta
Success rate, latency P50/P95/P99 y RPS visibles en Linkerd Viz.
Fase 1 — Instalación y mTLS (Semana 1)
01-install-linkerd.sh bash
Fase 1 · Semana 1
#!/bin/bash
# NexusFlow — Instalación Linkerd en GKE eu-west · nexusflow-prod
# Requisitos: kubectl configurado, cluster GKE 1.28+

# 1. Instalar CLI de Linkerd
curl --proto '=https' --tlsv1.2 -sSfL https://run.linkerd.io/install | sh
export PATH=$PATH:$HOME/.linkerd2/bin

# 2. Verificar compatibilidad del cluster GKE
linkerd check --pre

# 3. Instalar CRDs
linkerd install --crds | kubectl apply -f -

# 4. Instalar control plane (con HA para producción)
linkerd install \
  --ha \
  --cluster-domain cluster.local \
  --identity-issuance-lifetime 24h | kubectl apply -f -

# 5. Verificar instalación
linkerd check

# 6. Instalar extensión viz (dashboard)
linkerd viz install | kubectl apply -f -

# 7. Habilitar inyección automática en nexusflow-prod
kubectl annotate namespace nexusflow-prod \
  linkerd.io/inject=enabled

# 8. Rolling restart para inyectar proxies en pods existentes
kubectl rollout restart deployment -n nexusflow-prod

# 9. Verificar que todos los pods tienen proxy inyectado
linkerd check --proxy -n nexusflow-prod
namespace-injection.yaml yaml
Fase 1
# Namespace nexusflow-prod con inyección automática de proxies Linkerd
apiVersion: v1
kind: Namespace
metadata:
  name: nexusflow-prod
  annotations:
    linkerd.io/inject: "enabled"
  labels:
    environment: production
    app.kubernetes.io/managed-by: linkerd
    compliance: soc2-type-ii  # Tag para auditoría
Fase 2 — ServiceProfile: approval-engine (Semana 2)
SLA crítico: 200ms p99 en approval-engine
El ServiceProfile define timeouts por ruta y un retry budget del 20% para absorber fallos transitorios sin provocar retry storms.
approval-engine-serviceprofile.yaml yaml
Fase 2 · Semana 2
apiVersion: linkerd.io/v1alpha2
kind: ServiceProfile
metadata:
  name: approval-engine.nexusflow-prod.svc.cluster.local
  namespace: nexusflow-prod
spec:
  routes:
    # Ruta crítica: aprobar solicitud (SLA 200ms p99)
    - name: POST /api/v1/approvals
      condition:
        method: POST
        pathRegex: /api/v1/approvals
      responseClasses:
        - condition:
            status:
              min: 500
              max: 599
          isFailure: true
      isRetryable: false  # POST idempotente no aplica
      timeout: 200ms        # SLA contractual

    # Ruta: consultar estado de aprobación
    - name: GET /api/v1/approvals/{id}
      condition:
        method: GET
        pathRegex: /api/v1/approvals/[^/]+
      isRetryable: true
      timeout: 150ms

    # Ruta: listar aprobaciones (permite retry)
    - name: GET /api/v1/approvals
      condition:
        method: GET
        pathRegex: /api/v1/approvals
      isRetryable: true
      timeout: 500ms

    # Ruta: actualizar política de aprobación
    - name: PUT /api/v1/policies/{id}
      condition:
        method: PUT
        pathRegex: /api/v1/policies/[^/]+
      isRetryable: false
      timeout: 300ms

    # Health check — timeout agresivo
    - name: GET /health
      condition:
        method: GET
        pathRegex: /health
      isRetryable: true
      timeout: 50ms

  # Retry budget: máx 20% del tráfico total como reintentos
  retryBudget:
    retryRatio: 0.2
    minRetriesPerSecond: 10
    ttl: 10s
Fase 2 — Políticas de Autorización Zero-Trust
billing-service-authz.yaml yaml
Fase 2 · Semana 2
# billing-service: SOLO accesible desde api-gateway y approval-engine
# Bloquea el acceso directo desde billing-service → document-store

---
# Definir el servidor de billing-service
apiVersion: policy.linkerd.io/v1beta1
kind: Server
metadata:
  name: billing-service-http
  namespace: nexusflow-prod
spec:
  podSelector:
    matchLabels:
      app: billing-service
  port: 8080
  proxyProtocol: HTTP/2

---
# Autorizar: api-gateway → billing-service
apiVersion: policy.linkerd.io/v1beta1
kind: ServerAuthorization
metadata:
  name: billing-allow-api-gateway
  namespace: nexusflow-prod
spec:
  server:
    name: billing-service-http
  client:
    meshTLS:
      serviceAccounts:
        - name: api-gateway
          namespace: nexusflow-prod

---
# Autorizar: approval-engine → billing-service
apiVersion: policy.linkerd.io/v1beta1
kind: ServerAuthorization
metadata:
  name: billing-allow-approval-engine
  namespace: nexusflow-prod
spec:
  server:
    name: billing-service-http
  client:
    meshTLS:
      serviceAccounts:
        - name: approval-engine
          namespace: nexusflow-prod

---
# document-store: SOLO approval-engine + document-store propios
apiVersion: policy.linkerd.io/v1beta1
kind: Server
metadata:
  name: document-store-http
  namespace: nexusflow-prod
spec:
  podSelector:
    matchLabels:
      app: document-store
  port: 9000
  proxyProtocol: HTTP/1
---
apiVersion: policy.linkerd.io/v1beta1
kind: ServerAuthorization
metadata:
  name: docstore-allow-approval-only
  namespace: nexusflow-prod
spec:
  server:
    name: document-store-http
  client:
    meshTLS:
      serviceAccounts:
        - name: approval-engine
          namespace: nexusflow-prod
        - name: api-gateway
          namespace: nexusflow-prod
  # NOTA: billing-service NO aparece aquí → bloqueado por mTLS policy
Fase 3 — Canary Deployment: approval-engine v2 (Semana 3)
approval-engine-canary.yaml yaml
Fase 3 · Semana 3
# TrafficSplit: 90% → approval-engine-stable, 10% → approval-engine-v2
apiVersion: split.smi-spec.io/v1alpha1
kind: TrafficSplit
metadata:
  name: approval-engine-canary
  namespace: nexusflow-prod
spec:
  service: approval-engine       # Servicio principal (VIP)
  backends:
    - service: approval-engine-stable
      weight: 900m               # 90% del tráfico
    - service: approval-engine-v2
      weight: 100m               # 10% canary — incrementar gradualmente

---
# HTTPRoute avanzado: enrutar tráfico de beta-testers al 100% a v2
apiVersion: policy.linkerd.io/v1beta2
kind: HTTPRoute
metadata:
  name: approval-engine-beta-route
  namespace: nexusflow-prod
spec:
  parentRefs:
    - name: approval-engine
      kind: Service
      group: core
      port: 8080
  rules:
    # Clientes beta (header X-NexusFlow-Beta: true) → siempre v2
    - matches:
        - headers:
            - name: x-nexusflow-beta
              value: "true"
      backendRefs:
        - name: approval-engine-v2
          port: 8080
    # API v2 endpoints → siempre v2
    - matches:
        - path:
            type: PathPrefix
            value: /api/v2
      backendRefs:
        - name: approval-engine-v2
          port: 8080
    # Resto → stable (v1)
    - matches:
        - path:
            type: PathPrefix
            value: /
      backendRefs:
        - name: approval-engine-stable
          port: 8080
Comandos de Monitorización y Debugging
monitor-nexusflow.sh bash
# Golden metrics en tiempo real
linkerd viz top \
  deploy/approval-engine \
  -n nexusflow-prod

# Métricas por ruta del ServiceProfile
linkerd viz routes \
  deploy/approval-engine \
  -n nexusflow-prod

# Stats de todos los servicios
linkerd viz stat deploy \
  -n nexusflow-prod

# Grafo de dependencias
linkerd viz edges deploy \
  -n nexusflow-prod

# Dashboard (abre browser)
linkerd viz dashboard
debug-billing-authz.sh bash
# Verificar estado de mTLS e identidades
linkerd identity \
  -n nexusflow-prod

# TAP: ver tráfico billing-service (live)
linkerd viz tap deploy/api-gateway \
  --to deploy/billing-service \
  -n nexusflow-prod

# Confirmar que billing→document-store está BLOQUEADO
linkerd viz tap deploy/billing-service \
  --to deploy/document-store \
  -n nexusflow-prod
# Esperado: 0 conexiones (política bloquea)

# Ver logs del proxy de billing-service
kubectl logs deploy/billing-service \
  -c linkerd-proxy \
  -n nexusflow-prod | grep -i denied
Golden Metrics Objetivo — Post Implementación
Servicio Métrica Objetivo Alerta mTLS Política
approval-engine Success Rate ≥ 99.5% < 99.0% Activo TrafficSplit
approval-engine Latency P99 ≤ 200ms > 250ms Activo ServiceProfile
billing-service Accesos no autorizados 0 > 0 Activo ServerAuthz
document-store Accesos desde billing Bloqueado Cualquiera Activo ServerAuthz
api-gateway RPS Monitor Activo HTTPRoute
approval-engine v2 Error Rate (canary) ≤ 0.5% > 2% Activo TrafficSplit
Cobertura SOC 2 Type II — Controles de Seguridad

🛡
Controles Cubiertos

Cifrado en tránsito (mTLS) 100%
Control de acceso entre servicios 100%
Identidad criptográfica por pod 100%
Monitorización de tráfico E2E 90%
Certificados auto-rotados 100%

📋
Checklist de Implementación

  • Linkerd CLI instalado y cluster validado
  • mTLS automático en namespace nexusflow-prod
  • ServiceProfile approval-engine desplegado
  • ServerAuthorization billing-service activo
  • ServerAuthorization document-store activo
  • TrafficSplit canary 10% approval-engine v2
  • HTTPRoute beta-testers configurado
  • Dashboard Viz + alertas Prometheus
  • Multi-cluster us-east (Fase 4)
✓ Completado (2) ◎ En progreso (3) ○ Pendiente (4)
Plan de Ejecución — 3 Semanas
Semana 1 · Fase 1
Instalación y mTLS automático
  • Instalar Linkerd CLI y validar cluster GKE eu-west
  • Desplegar control plane en modo HA (alta disponibilidad)
  • Anotar namespace nexusflow-prod con inject:enabled
  • Rolling restart de los 8 deployments
  • Verificar que todos los pods tienen linkerd-proxy inyectado
  • Confirmar mTLS activo con linkerd identity
Semana 2 · Fase 2
Políticas de autorización y ServiceProfile
  • Desplegar Server + ServerAuthorization para billing-service
  • Desplegar Server + ServerAuthorization para document-store
  • Verificar que billing → document-store está bloqueado (TAP)
  • Crear ServiceProfile approval-engine con timeouts y retry budget
  • Validar métricas por ruta en Linkerd Viz dashboard
  • Confirmar SLA 200ms p99 con carga de prueba
Semana 3 · Fase 3
Canary deployment y monitorización completa
  • Desplegar approval-engine-v2 como servicio paralelo
  • Configurar TrafficSplit 90/10 en approval-engine
  • Configurar HTTPRoute para beta-testers y /api/v2
  • Monitorizar error rate v2 durante 48h antes de escalar
  • Integrar alertas Prometheus (success rate, latency p99)
  • Documentar procedimiento de rollback y plan multi-cluster
Buenas Prácticas — NexusFlow

Hacer

  • Ejecutar linkerd check tras cada cambio
  • Usar ServiceProfiles en todos los servicios críticos
  • Definir retry budgets (máx 20%)
  • Monitorizar golden metrics diariamente
  • Rotar certificados: TTL 24h (configurado)

Evitar

  • Saltar validación pre-instalación
  • POST como retryable (no idempotente)
  • Sobreconfigurar (los defaults son sensatos)
  • Ignorar timeouts en rutas de pago
  • Escalar canary sin monitorizar 24h antes

Próximos pasos

  • Multi-cluster: enlazar us-east con linkerd multicluster link
  • Exportar approval-engine al cluster us-east
  • Integrar Grafana con métricas de Linkerd Viz
  • Automatizar promote canary con Flagger
  • Generar evidencias SOC 2 con linkerd check