# Auditoria de Seguranca de Edge Functions Supabase

Voce e um Senior DevOps Security Auditor. Sua tarefa e verificar se as
Edge Functions do Supabase foram implementadas corretamente conforme o runbook (artigo 3).

Execute os seguintes checks na ordem. Utilize as ferramentas disponiveis.
Para cada check: reporte APROVADO, AVISO ou CRITICO com justificativa breve.
Ao final, elabore um resumo com recomendacoes de acao.

---

## A1: Edge Functions apenas para integracoes

Verifique se as Edge Functions sao utilizadas como pontos de integracao, nao como um segundo backend.

```bash
# Alle Edge Functions auflisten
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

echo "=== Functions Verzeichnis: $FUNCTIONS_DIR ==="
ls -d ${FUNCTIONS_DIR}/*/ 2>/dev/null | grep -v "main\|_shared"

# Für jede Function prüfen: Webhook/Integration oder Business-Logik?
echo "=== Webhook/Integration Patterns ==="
for dir in ${FUNCTIONS_DIR}/*/; do
  name=$(basename "$dir")
  [[ "$name" == "main" || "$name" == "_shared" ]] && continue
  echo "--- $name ---"

  # Webhook-Patterns vorhanden?
  grep -l "signature\|webhook\|stripe\|github\|trigger\|event" "$dir"*.ts 2>/dev/null || true

  # Business-Logik Patterns (Warnung)?
  if grep -qE "getUser\|session\|createServerClient\|\.from\(.*\)\.select\(.*\)\.eq\(" "$dir/index.ts" 2>/dev/null; then
    echo "AVISO: Enthält möglicherweise Business-Logik (User-Kontext, komplexe Queries)"
  fi

  # CRUD-Patterns (Warnung)?
  if grep -qE "\.insert\(|\.update\(|\.delete\(" "$dir/index.ts" 2>/dev/null; then
    COUNT=$(grep -cE "\.insert\(|\.update\(|\.delete\(" "$dir/index.ts" 2>/dev/null || echo 0)
    if [ "$COUNT" -gt 2 ]; then
      echo "AVISO: $COUNT DB-Mutationen. Möglicherweise Business-Logik statt Integration."
    fi
  fi
done
```

Expectativa: Functions sao webhooks, event handlers ou integracoes de API. Logica de negocios complexa (CRUD, User-Session, Ownership) pertence ao Next.js.
Risco: Logica duplicada em Edge Functions e Next.js leva a validacao inconsistente e erros dificeis de debugar.

---

## A2: Endpoints de Webhook isolados

Verifique se cada provedor de webhook possui sua propria Function.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

echo "=== Webhook Functions ==="
ls -d ${FUNCTIONS_DIR}/*webhook*/ 2>/dev/null || echo "Keine Webhook-Functions gefunden"

# Prüfe ob eine Function mehrere Provider bedient
for dir in ${FUNCTIONS_DIR}/*-webhook/; do
  [ -d "$dir" ] || continue
  name=$(basename "$dir")
  providers=$(grep -ciE "stripe|github|trigger|slack|sendgrid|twilio" "$dir/index.ts" 2>/dev/null || echo 0)
  if [ "$providers" -gt 1 ]; then
    echo "AVISO: $name referenziert mehrere Provider ($providers)"
  else
    echo "OK: $name"
  fi
done
```

Expectativa: Um provedor de webhook por Function (stripe-webhook, github-webhook, etc.).
Risco: Error handlers compartilhados. Payload Stripe defeituoso bloqueia o webhook do GitHub.

---

## A3: CORS configurado corretamente

Verifique se o CORS esta definido corretamente em todas as Functions.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

# Shared CORS Config vorhanden?
echo "=== Shared CORS Config ==="
ls ${FUNCTIONS_DIR}/_shared/cors.ts 2>/dev/null || echo "AVISO: Keine shared cors.ts"

if [ -f "${FUNCTIONS_DIR}/_shared/cors.ts" ]; then
  cat "${FUNCTIONS_DIR}/_shared/cors.ts"
fi

# Wildcard CORS in Produktion?
echo "=== Wildcard CORS ==="
grep -rn "'\\*'" ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null | grep -i "origin" || \
  echo "Kein Wildcard-Origin gefunden (gut)"

# Alle Functions haben OPTIONS Handler?
echo "=== OPTIONS Handler ==="
for dir in ${FUNCTIONS_DIR}/*/; do
  name=$(basename "$dir")
  [[ "$name" == "main" || "$name" == "_shared" ]] && continue
  if ! grep -q "OPTIONS" "$dir/index.ts" 2>/dev/null; then
    echo "AVISO: $name hat keinen OPTIONS Handler"
  else
    echo "OK: $name"
  fi
done

# CORS Headers in ALLEN Responses (auch Error)?
echo "=== CORS in Error Responses ==="
for dir in ${FUNCTIONS_DIR}/*/; do
  name=$(basename "$dir")
  [[ "$name" == "main" || "$name" == "_shared" ]] && continue
  ERROR_RESPONSES=$(grep -c "new Response" "$dir/index.ts" 2>/dev/null || echo 0)
  CORS_RESPONSES=$(grep -c "corsHeaders\|getCorsHeaders" "$dir/index.ts" 2>/dev/null || echo 0)
  if [ "$ERROR_RESPONSES" -gt "$CORS_RESPONSES" ] && [ "$ERROR_RESPONSES" -gt 0 ]; then
    echo "AVISO: $name hat $ERROR_RESPONSES Responses aber nur $CORS_RESPONSES mit CORS Headers"
  fi
done
```

Expectativa:
- cors.ts compartilhado presente em _shared/
- Sem Wildcard-Origin (`'*'`) em producao
- Todas as Functions possuem handler OPTIONS de preflight
- CORS Headers em todas as respostas (incluindo respostas de erro)

Risco: Sem CORS, requests do browser falham. Com Wildcard, qualquer site pode enviar requests.

---

## B1: Assinaturas de Webhook verificadas

Verifique se todas as Webhook-Functions verificam assinaturas.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

echo "=== Signaturprüfung ==="
for dir in ${FUNCTIONS_DIR}/*-webhook/ ${FUNCTIONS_DIR}/*webhook*/; do
  [ -d "$dir" ] || continue
  name=$(basename "$dir")

  if grep -qE "signature|verify|hmac|crypto\.subtle" "$dir/index.ts" 2>/dev/null; then
    echo "OK: $name prüft Signaturen"

    # Timing-Check vorhanden (Replay-Schutz)?
    if grep -qE "timestamp|Date\.now\|time" "$dir/index.ts" 2>/dev/null; then
      echo "  + Timing/Replay-Schutz vorhanden"
    else
      echo "  - AVISO: Kein Timing-Check für Replay-Schutz"
    fi
  else
    echo "CRÍTICO: $name hat KEINE Signaturprüfung"
  fi
done

# Auch Non-Webhook Functions die POST akzeptieren
echo "=== Non-Webhook Functions mit POST ==="
for dir in ${FUNCTIONS_DIR}/*/; do
  name=$(basename "$dir")
  [[ "$name" == "main" || "$name" == "_shared" || "$name" == *"webhook"* ]] && continue
  if grep -q "POST" "$dir/index.ts" 2>/dev/null; then
    echo "INFO: $name akzeptiert POST. Auth-Mechanismus prüfen:"
    grep -n "auth\|token\|Bearer\|jwt\|verify" "$dir/index.ts" 2>/dev/null | head -3 || \
      echo "  AVISO: Kein Auth-Mechanismus erkennbar"
  fi
done
```

Expectativa: Todas as Webhook-Functions verificam assinaturas do provedor (Stripe: stripe-signature + HMAC, GitHub: X-Hub-Signature-256).
Risco: Sem verificacao de assinatura, qualquer pessoa pode enviar eventos falsificados (ex. confirmacao de pagamento falsa).

---

## B2: Supabase Client correto (anon vs. service_role)

Verifique se o Supabase Client nas Edge Functions esta inicializado corretamente.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

# Shared Client vorhanden?
echo "=== Shared Supabase Client ==="
ls ${FUNCTIONS_DIR}/_shared/supabase*.ts 2>/dev/null || echo "Keine shared Client-Datei"

# Wo wird service_role verwendet?
echo "=== service_role Nutzung ==="
grep -rn "SERVICE_ROLE\|service_role" ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null | \
  grep -v "_shared/"

# In welchen Functions wird der Admin/Service-Role Client erstellt?
echo "=== createClient mit service_role ==="
for dir in ${FUNCTIONS_DIR}/*/; do
  name=$(basename "$dir")
  [[ "$name" == "main" || "$name" == "_shared" ]] && continue
  if grep -qE "SERVICE_ROLE|createAdminClient|service_role" "$dir/index.ts" 2>/dev/null; then
    echo "$name: nutzt service_role"
    # Wird User-Input direkt in Queries verwendet?
    if grep -qE "payload\.\|body\.\|data\." "$dir/index.ts" 2>/dev/null; then
      if ! grep -qE "safeParse\|z\.\|validate\|schema" "$dir/index.ts" 2>/dev/null; then
        echo "  AVISO: Nutzt service_role UND verarbeitet Payload ohne erkennbare Validation"
      fi
    fi
  fi
done
```

Expectativa:
- Client Factory compartilhado em _shared/ (anon vs. admin separados)
- service_role apenas em Functions de Webhook/Integracao (sem contexto de usuario)
- Se service_role + input de usuario: validacao de input deve estar presente

Risco: service_role + input nao validado = operacoes arbitrarias no banco sem RLS.

---

## B3: Validacao de Input

Verifique se todas as Edge Functions validam dados de entrada.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

echo "=== Input Validation ==="
for dir in ${FUNCTIONS_DIR}/*/; do
  name=$(basename "$dir")
  [[ "$name" == "main" || "$name" == "_shared" ]] && continue

  if grep -qE "zod|safeParse|z\.object|z\.string|validate|schema" "$dir/index.ts" 2>/dev/null; then
    echo "OK: $name hat Schema Validation"
  elif grep -qE "JSON\.parse|req\.json\(\)" "$dir/index.ts" 2>/dev/null; then
    echo "AVISO: $name parsed JSON/Body ohne Schema Validation"
  else
    echo "INFO: $name verarbeitet möglicherweise keinen Body"
  fi
done

# Wird zod über npm: importiert (Deno-kompatibel)?
echo "=== Zod Import ==="
grep -rn "from.*zod\|import.*zod" ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null | head -5
```

Expectativa: Todas as Functions que processam payloads possuem Schema Validation (ex. zod).
Risco: Sem validacao, estruturas de dados inesperadas podem levar a operacoes indefinidas no banco.

---

## B4: Secrets fora do codigo

Verifique se os secrets sao carregados corretamente via variaveis de ambiente.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

# Hardcoded Secrets
echo "=== Hardcoded Secrets ==="
grep -rn "sk_live\|sk_test\|whsec_\|ghsec_\|Bearer ey\|SG\.\|sk-proj\|sk-ant" \
  ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null || echo "Keine hardcoded Secrets gefunden (gut)"

# Secrets korrekt über Deno.env geladen?
echo "=== Deno.env.get Nutzung ==="
grep -rn "Deno.env.get" ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null | head -10

# .env.functions Datei vorhanden und sicher?
echo "=== .env.functions ==="
ENV_FUNC=$(find /opt -name ".env.functions" 2>/dev/null | head -1)
if [ -n "$ENV_FUNC" ]; then
  stat -c "%a %U" "$ENV_FUNC"
  # Nicht im Git?
  cd $(dirname "$ENV_FUNC") && git ls-files .env.functions 2>/dev/null
else
  echo "Keine .env.functions gefunden (Secrets möglicherweise über docker-compose)"
fi
```

Expectativa:
- Sem API Keys, Webhook Secrets ou Tokens hardcoded no codigo
- Secrets carregados via Deno.env.get()
- .env.functions com permissoes 600, fora do Git

Risco: Secrets hardcoded no repositorio Git expostos em cada clone.

---

## B5: Timeouts e operacoes de longa duracao

Verifique se as Edge Functions nao contem operacoes de longa duracao.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

# Langläufer-Patterns
echo "=== Langläufer-Patterns ==="
grep -rn "openai\|anthropic\|sharp\|ffmpeg\|puppeteer\|playwright\|pdf\|video\|transcode" \
  ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null || echo "Keine Langläufer-Patterns gefunden (gut)"

# Sleep/Timeout Patterns
echo "=== Sleep/Delay Patterns ==="
grep -rn "sleep\|setTimeout\|delay\|await new Promise" \
  ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null | head -5

# Externe fetch-Calls ohne Timeout?
echo "=== Fetch ohne AbortSignal ==="
for dir in ${FUNCTIONS_DIR}/*/; do
  name=$(basename "$dir")
  [[ "$name" == "main" || "$name" == "_shared" ]] && continue
  FETCHES=$(grep -c "fetch(" "$dir/index.ts" 2>/dev/null || echo 0)
  TIMEOUTS=$(grep -c "AbortSignal\|signal\|timeout" "$dir/index.ts" 2>/dev/null || echo 0)
  if [ "$FETCHES" -gt 0 ] && [ "$TIMEOUTS" -eq 0 ]; then
    echo "AVISO: $name hat $FETCHES fetch-Calls ohne Timeout/AbortSignal"
  fi
done
```

Expectativa:
- Sem inferencia de IA, geracao de PDF ou processamento de video em Edge Functions
- Chamadas fetch externas possuem timeouts (AbortSignal)
- Operacoes de longa duracao sao delegadas ao Trigger.dev

Risco: Operacoes de longa duracao bloqueiam worker slots. Chamadas subsequentes de webhook falham com timeout.

---

## B6: Tratamento de Erros

Verifique se as Edge Functions tratam erros de forma segura.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

# Try/Catch vorhanden?
echo "=== Try/Catch ==="
for dir in ${FUNCTIONS_DIR}/*/; do
  name=$(basename "$dir")
  [[ "$name" == "main" || "$name" == "_shared" ]] && continue
  if ! grep -q "try" "$dir/index.ts" 2>/dev/null; then
    echo "AVISO: $name hat kein try/catch"
  else
    echo "OK: $name"
  fi
done

# Error Details in Responses?
echo "=== Error Details an Client geleakt? ==="
grep -rn "error\.stack\|error\.message" ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null | \
  grep "Response" || echo "Keine Error-Detail-Leaks gefunden (gut)"

# Secrets in console.log?
echo "=== Secrets in Logs ==="
grep -rn "console\.log.*KEY\|console\.log.*SECRET\|console\.log.*token\|console\.log.*password" \
  ${FUNCTIONS_DIR}/ --include="*.ts" 2>/dev/null || echo "Keine Secret-Logs gefunden (gut)"
```

Expectativa:
- Todas as Functions possuem try/catch envolvendo a logica
- Sem error.stack ou error.message nas respostas ao cliente
- Sem secrets em console.log

Risco: Stack traces nas respostas revelam caminhos internos e detalhes do banco. Facilita ataques direcionados.

---

## C1: Workflow de Deployment

Verifique se as Edge Functions sao deployadas corretamente.

```bash
FUNCTIONS_DIR=$(find /opt -path "*/volumes/functions" -type d 2>/dev/null | head -1)
FUNCTIONS_DIR=${FUNCTIONS_DIR:-"./supabase/functions"}

# Edge Runtime Container läuft?
echo "=== Edge Runtime Container ==="
docker ps --format '{{.Names}}\t{{.Image}}\t{{.Status}}' 2>/dev/null | grep -i "function\|edge"

# Functions im Volume vorhanden?
echo "=== Functions im Volume ==="
ls -la ${FUNCTIONS_DIR}/ 2>/dev/null | head -20

# VERIFY_JWT Einstellung
echo "=== VERIFY_JWT ==="
grep "VERIFY_JWT" /opt/supabase/.env /opt/supabase/docker-compose.yml 2>/dev/null
```

Expectativa:
- Container Edge Runtime em execucao
- Functions presentes como arquivos no volume
- VERIFY_JWT configurado conscientemente (false para webhooks que nao enviam JWT)

---

## Resumo

Elabore agora um resumo neste formato:

```
# Auditoria de Seguranca Edge Functions - [DATA]

## Resultado

APROVADO:  X de Y Checks
AVISO:     X Checks
CRITICO:   X Checks

## Findings Criticos (agir imediatamente)
- ...

## Avisos (resolver nesta semana)
- ...

## Aprovados
- ...

## Proximos Passos Recomendados
1. ...
2. ...
3. ...
```

Priorize estritamente: Findings criticos primeiro, depois avisos.
Para cada finding: Qual e o problema, por que e um risco, qual e a solucao.
