{"slug":"operations/NEON_TUNNEL_CONFIG","title":"Neon ↔ Cloudflare Tunnel Configuration","section":"operations","sectionLabel":"Operations","status":"unclassified","type":"document","path":"operations/NEON_TUNNEL_CONFIG.mdx","bytes":14589,"description":null,"updated":null,"source":"integratewise/Integratewise-docs-wiki","content":"\n## Overview\n\nSecure, encrypted tunnels connect Cloudflare Workers to Neon PostgreSQL databases across all 3 deployment profiles.\n\n---\n\n## Dev Profile Tunnel\n\n### Endpoint Configuration\n\n```yaml\nprofile: dev\nendpoint: neon.dev.integratewise.internal:5432\ntype: tcp\nencryption: TLS 1.2\nauth_method: JWT\n```\n\n### Setup Steps\n\n1. **Create Neon branch for dev**:\n\n```bash\nneon branches create --project-id dev-project --branch dev-branch\n```\n\n2. **Get connection string**:\n\n```bash\nneon connection-string --project-id dev-project --branch dev-branch\n# postgresql://user:pass@neon.dev.integratewise.internal/dev_db\n```\n\n3. **Configure in Wrangler**:\n\n```toml\n[env.dev.vars]\nNEON_DATABASE_URL = \"postgresql://user:pass@neon.dev.integratewise.internal/dev_db\"\nNEON_TUNNEL_ENDPOINT = \"neon.dev.integratewise.internal\"\n```\n\n4. **Generate JWT token**:\n\n```bash\nopenssl genrsa -out dev_key.pem 2048\nopenssl rsa -in dev_key.pem -pubout -out dev_pub.pem\n\n# Create JWT payload\ncat > dev_jwt_payload.json <<EOF\n{\n  \"aud\": \"neon-tunnel-dev\",\n  \"iss\": \"integratewise-dev\",\n  \"sub\": \"dev-worker\",\n  \"iat\": $(date +%s),\n  \"exp\": $(($(date +%s) + 86400))\n}\nEOF\n\n# Sign JWT (using offline tool or service)\n# Store in: NEON_TUNNEL_AUTH_TOKEN\n```\n\n5. **Test connection from Worker**:\n\n```typescript\n// services/gateway/src/index.ts\nconst client = new postgres.Client({\n  connectionString: env.NEON_DATABASE_URL,\n  ssl: {\n    rejectUnauthorized: true,\n    ca: env.NEON_TUNNEL_CERT, // If using mTLS\n  },\n});\n\nawait client.connect();\n```\n\n### Monitoring\n\n```bash\n# Check tunnel status\ncurl https://neon.dev.integratewise.internal/health\n\n# Monitor latency\nneon telemetry --project-id dev-project\n\n# View connection pool\nSELECT count(*) FROM pg_stat_activity;\n```\n\n---\n\n## Customer Zero Profile Tunnel\n\n### Endpoint Configuration\n\n```yaml\nprofile: customer-zero\nendpoint: neon.customer-zero.integratewise.internal:5432\ntype: tcp\nencryption: TLS 1.3\nauth_method: mTLS (certificate pinning)\ncertificate_rotation: every 60 days\nbackup_certificates: 2\n```\n\n### Setup Steps\n\n1. **Create dedicated Neon project for Customer Zero**:\n\n```bash\nneon projects create --name \"IntegrateWise Customer Zero\"\nneon branches create --project-id customer-zero-project --branch production\n```\n\n2. **Get connection string**:\n\n```bash\nneon connection-string \\\n  --project-id customer-zero-project \\\n  --branch production\n# postgresql://user:pass@neon.customer-zero.integratewise.internal/customer_zero_db\n```\n\n3. **Generate mTLS certificates** (Let's Encrypt):\n\n```bash\n# Primary certificate (rotate every 60 days)\ncertbot certonly \\\n  --standalone \\\n  --domain neon.customer-zero.integratewise.internal \\\n  --email ops@integratewise.com\n\n# Private key\nopenssl pkcs8 -in /etc/letsencrypt/live/neon.customer-zero.integratewise.internal/privkey.pem \\\n  -topk8 -nocrypt -out customer_zero_private.key\n\n# Public cert\ncp /etc/letsencrypt/live/neon.customer-zero.integratewise.internal/fullchain.pem \\\n  customer_zero_cert.pem\n\n# CA bundle\ncurl https://letsencrypt.org/certs/isrgrootx1.pem > ca_bundle.pem\n```\n\n4. **Configure in Wrangler**:\n\n```toml\n[env.customer-zero.vars]\nNEON_DATABASE_URL = \"postgresql://user:pass@neon.customer-zero.integratewise.internal/customer_zero_db\"\nNEON_TUNNEL_ENDPOINT = \"neon.customer-zero.integratewise.internal\"\nNEON_TUNNEL_REGIONS = \"us-east\"\nNEON_CONNECTION_POOL_MIN = \"10\"\nNEON_CONNECTION_POOL_MAX = \"100\"\n```\n\n5. **Store certificates in Cloudflare Secrets**:\n\n```bash\nwrangler secret put NEON_TUNNEL_CERT --env customer-zero < customer_zero_cert.pem\nwrangler secret put NEON_TUNNEL_KEY --env customer-zero < customer_zero_private.key\nwrangler secret put NEON_TUNNEL_AUTH_TOKEN --env customer-zero \"jwt_token_here\"\n```\n\n6. **Enable Connection Pool** (Neon):\n\n```bash\nneon connection-pooling enable \\\n  --project-id customer-zero-project \\\n  --branch production \\\n  --pool-size 25\n```\n\n### Connection Pool Configuration\n\n```sql\n-- pgBouncer pooling on Neon\nSET client_encoding = 'UTF-8';\n\n-- Create pool connection\nSELECT create_pool_connection(\n  'customer_zero_pool',\n  'transaction',\n  25,\n  300\n);\n```\n\n### Monitoring\n\n```bash\n# Check tunnel certificate expiration\nopenssl x509 -in customer_zero_cert.pem -noout -dates\n# notBefore=Dec 15 10:00:00 2024 GMT\n# notAfter=Mar 15 10:00:00 2025 GMT\n\n# Monitor connection pool\nSELECT\n  database,\n  user,\n  state,\n  count(*) as connections\nFROM pg_stat_activity\nGROUP BY database, user, state;\n\n# Health check\ncurl -X GET https://neon.customer-zero.integratewise.internal/health \\\n  --cert customer_zero_cert.pem \\\n  --key customer_zero_private.key\n```\n\n### Backup Certificate Rotation\n\n```bash\n# Day 1: Create backup cert 1\ncertbot certonly \\\n  --standalone \\\n  --domain neon.customer-zero.integratewise.internal-backup-1 \\\n  --email ops@integratewise.com\n\n# Day 30: Create backup cert 2\ncertbot certonly \\\n  --standalone \\\n  --domain neon.customer-zero.integratewise.internal-backup-2 \\\n  --email ops@integratewise.com\n\n# Day 60: Rotate primary cert\ncertbot renew --force-renewal\n\n# Update secrets\nwrangler secret put NEON_TUNNEL_CERT_BACKUP_1 --env customer-zero < backup1_cert.pem\nwrangler secret put NEON_TUNNEL_CERT_BACKUP_2 --env customer-zero < backup2_cert.pem\n```\n\n---\n\n## External Users Profile Tunnel\n\n### Endpoint Configuration\n\n```yaml\nprofile: external-users\nendpoints:\n  - us-east.neon.integratewise.io:5432\n  - eu-west.neon.integratewise.io:5432\n  - ap-south.neon.integratewise.io:5432\ntype: tcp\nencryption: TLS 1.3 + TLS 1.2 fallback\nauth_method: mTLS with certificate pinning\ncertificate_rotation: every 330 days (before expiry)\nbackup_certificates: 3\ncircuit_breaker:\n  failure_threshold: 50%\n  timeout: 60s\n  half_open_requests: 3\n```\n\n### Setup Steps\n\n1. **Create multi-tenant Neon project**:\n\n```bash\nneon projects create --name \"IntegrateWise External Users\"\nneon branches create --project-id external-users-project --branch production\n\n# Enable read replicas for each region\nneon replicas create \\\n  --project-id external-users-project \\\n  --branch production \\\n  --region us-east-1\n\nneon replicas create \\\n  --project-id external-users-project \\\n  --branch production \\\n  --region eu-west-1\n\nneon replicas create \\\n  --project-id external-users-project \\\n  --branch production \\\n  --region ap-south-1\n```\n\n2. **Get connection strings for each region**:\n\n```bash\n# US East\nneon connection-string \\\n  --project-id external-users-project \\\n  --branch production \\\n  --replica us-east\n# postgresql://user:pass@us-east.neon.integratewise.io/multi_tenant_db\n\n# EU West\nneon connection-string \\\n  --project-id external-users-project \\\n  --branch production \\\n  --replica eu-west\n# postgresql://user:pass@eu-west.neon.integratewise.io/multi_tenant_db\n\n# AP South\nneon connection-string \\\n  --project-id external-users-project \\\n  --branch production \\\n  --replica ap-south\n# postgresql://user:pass@ap-south.neon.integratewise.io/multi_tenant_db\n```\n\n3. **Generate DigiCert EV certificates** (1-year validity):\n\n```bash\n# Primary certificate\ncertbot certonly \\\n  --dns-cloudflare \\\n  --dns-cloudflare-credentials ~/.secrets/cloudflare.ini \\\n  --domain neon.integratewise.io \\\n  --domain \"*.neon.integratewise.io\" \\\n  --preferred-chain \"DigiCert Global Root CA\" \\\n  --email ops@integratewise.com\n\n# Extract keys for each region\nopenssl pkcs8 -in /etc/letsencrypt/live/neon.integratewise.io/privkey.pem \\\n  -topk8 -nocrypt -out external_users_private.key\n\nopenssl x509 -in /etc/letsencrypt/live/neon.integratewise.io/fullchain.pem \\\n  -out external_users_cert.pem\n\n# Create region-specific cert aliases (SANs already included)\ncp external_users_cert.pem us_east_cert.pem\ncp external_users_cert.pem eu_west_cert.pem\ncp external_users_cert.pem ap_south_cert.pem\n```\n\n4. **Configure in Wrangler**:\n\n```toml\n[env.external-users.vars]\nNEON_TUNNEL_ENDPOINT = \"neon.integratewise.io\"\nNEON_TUNNEL_REGIONS = \"us-east,eu-west,ap-south\"\nNEON_CONNECTION_POOL_MIN = \"50\"\nNEON_CONNECTION_POOL_MAX = \"500\"\nNEON_POOL_IDLE_TIMEOUT = \"30s\"\nNEON_POOL_STATEMENT_CACHE_SIZE = \"50\"\nNEON_CIRCUIT_BREAKER_ENABLED = \"true\"\nNEON_CIRCUIT_BREAKER_FAILURE_THRESHOLD = \"50\"\nNEON_CIRCUIT_BREAKER_TIMEOUT = \"60000\"\n```\n\n5. **Store certificates in Cloudflare Secrets** (with backup rotation):\n\n```bash\n# Primary\nwrangler secret put NEON_TUNNEL_CERT --env external-users < external_users_cert.pem\nwrangler secret put NEON_TUNNEL_KEY --env external-users < external_users_private.key\n\n# Backup 1 (created day 1)\nwrangler secret put NEON_TUNNEL_CERT_BACKUP_1 --env external-users < backup1_cert.pem\n\n# Backup 2 (created day 180)\nwrangler secret put NEON_TUNNEL_CERT_BACKUP_2 --env external-users < backup2_cert.pem\n\n# Backup 3 (created day 300, before primary expires)\nwrangler secret put NEON_TUNNEL_CERT_BACKUP_3 --env external-users < backup3_cert.pem\n```\n\n6. **Enable advanced pooling**:\n\n```bash\nneon connection-pooling enable \\\n  --project-id external-users-project \\\n  --branch production \\\n  --pool-size 100 \\\n  --pool-mode transaction \\\n  --idle-timeout 30\n\n# Per-region pooling\nfor region in us-east eu-west ap-south; do\n  neon connection-pooling enable \\\n    --project-id external-users-project \\\n    --replica $region \\\n    --pool-size 100 \\\n    --pool-mode transaction \\\n    --idle-timeout 30\ndone\n```\n\n7. **Enable Row-Level Security (RLS)** on all tables:\n\n```sql\n-- Enable RLS on tables\nALTER TABLE tenants ENABLE ROW LEVEL SECURITY;\nALTER TABLE users ENABLE ROW LEVEL SECURITY;\nALTER TABLE connectors ENABLE ROW LEVEL SECURITY;\n-- ... etc\n\n-- Create policy for tenant isolation\nCREATE POLICY tenant_isolation_policy ON users\n  USING (tenant_id = current_setting('app.current_tenant_id')::uuid);\n\nCREATE POLICY tenant_isolation_policy ON connectors\n  USING (tenant_id = current_setting('app.current_tenant_id')::uuid);\n\n-- ... etc for all multi-tenant tables\n```\n\n### Connection Pool Configuration\n\n```sql\n-- Configure pgBouncer for multi-region\nSET client_encoding = 'UTF-8';\n\n-- US East\nSELECT create_pool_connection(\n  'us_east_pool',\n  'transaction',\n  100,\n  30\n);\n\n-- EU West\nSELECT create_pool_connection(\n  'eu_west_pool',\n  'transaction',\n  100,\n  30\n);\n\n-- AP South\nSELECT create_pool_connection(\n  'ap_south_pool',\n  'transaction',\n  100,\n  30\n);\n```\n\n### Monitoring\n\n```bash\n# Certificate expiration check (automated weekly)\nfor cert in us_east_cert.pem eu_west_cert.pem ap_south_cert.pem; do\n  echo \"=== $cert ===\"\n  openssl x509 -in $cert -noout -dates -subject\n  # Alert if expires in < 30 days\ndone\n\n# Multi-region connection pool status\nfor region in us-east eu-west ap-south; do\n  echo \"=== $region region ===\"\n  curl -X GET \"https://$region.neon.integratewise.io/health\" \\\n    --cert external_users_cert.pem \\\n    --key external_users_private.key \\\n    --insecure  # In prod, verify cert\ndone\n\n# Circuit breaker metrics\nSELECT\n  endpoint,\n  failures,\n  successes,\n  failure_rate,\n  circuit_state\nFROM circuit_breaker_metrics\nWHERE profile = 'external-users'\nORDER BY endpoint;\n\n# Connection pool status per tenant\nSELECT\n  tenant_id,\n  active_connections,\n  idle_connections,\n  total_connections,\n  region\nFROM pg_stat_activity\nGROUP BY tenant_id, region;\n```\n\n### Automatic Certificate Rotation\n\n```bash\n#!/bin/bash\n# certificate-rotation.sh - Run weekly\n\nPROFILE=\"external-users\"\nCERT_EXPIRY_WARNING_DAYS=30\n\ncheck_certificate_expiry() {\n  local cert_file=$1\n  local expiry_date=$(openssl x509 -in $cert_file -noout -dates | grep notAfter | cut -d= -f2)\n  local expiry_epoch=$(date -d \"$expiry_date\" +%s)\n  local now_epoch=$(date +%s)\n  local days_until_expiry=$(( ($expiry_epoch - $now_epoch) / 86400 ))\n\n  echo \"Certificate expires in: $days_until_expiry days\"\n\n  if [ $days_until_expiry -lt $CERT_EXPIRY_WARNING_DAYS ]; then\n    echo \"ALERT: Certificate expiring in $days_until_expiry days\"\n\n    # Rotate certificates\n    certbot renew --force-renewal \\\n      --dns-cloudflare \\\n      --domain neon.integratewise.io\n\n    # Update backups (shift them)\n    mv backup2_cert.pem backup3_cert.pem\n    mv backup1_cert.pem backup2_cert.pem\n    cp external_users_cert.pem backup1_cert.pem\n\n    # Update secrets\n    wrangler secret put NEON_TUNNEL_CERT --env $PROFILE < external_users_cert.pem\n    wrangler secret put NEON_TUNNEL_CERT_BACKUP_1 --env $PROFILE < backup1_cert.pem\n    wrangler secret put NEON_TUNNEL_CERT_BACKUP_2 --env $PROFILE < backup2_cert.pem\n    wrangler secret put NEON_TUNNEL_CERT_BACKUP_3 --env $PROFILE < backup3_cert.pem\n\n    # Redeploy workers\n    wrangler deploy --env $PROFILE\n\n    echo \"Certificate rotation completed\"\n  fi\n}\n\ncheck_certificate_expiry \"external_users_cert.pem\"\n```\n\n---\n\n## Testing Tunnels\n\n### Test Dev Tunnel\n\n```bash\n# Connect directly\npsql \"postgresql://user:pass@neon.dev.integratewise.internal/dev_db\"\n\n# Test from Worker\ncurl -X POST https://api.dev.integratewise.internal/test-db \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"query\": \"SELECT 1\"}'\n```\n\n### Test Customer Zero Tunnel\n\n```bash\n# Verify certificate\nopenssl s_client -connect neon.customer-zero.integratewise.internal:5432 \\\n  -cert customer_zero_cert.pem \\\n  -key customer_zero_private.key \\\n  -CAfile ca_bundle.pem\n\n# Test from Worker\ncurl -X POST https://api.customer-zero.integratewise.com/test-db \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer $JWT_TOKEN\" \\\n  -d '{\"query\": \"SELECT 1\"}'\n```\n\n### Test External Users Tunnel (Multi-region)\n\n```bash\n# Test each region\nfor region in us-east eu-west ap-south; do\n  echo \"Testing $region.neon.integratewise.io...\"\n\n  curl -X POST \"https://api.integratewise.com/test-db\" \\\n    -H \"Content-Type: application/json\" \\\n    -H \"X-Region: $region\" \\\n    -d '{\"query\": \"SELECT 1\"}' \\\n    --cert external_users_cert.pem \\\n    --key external_users_private.key\ndone\n```\n\n---\n\n## Troubleshooting\n\n### Certificate Issues\n\n```bash\n# Verify certificate is valid\nopenssl x509 -in cert.pem -noout -text\n\n# Check certificate chain\nopenssl verify -CAfile ca_bundle.pem cert.pem\n\n# Extract certificate from running connection\necho | openssl s_client -connect neon.integratewise.io:5432 2>/dev/null | openssl x509\n```\n\n### Connection Pool Issues\n\n```bash\n# Check pool statistics\nneon telemetry --project-id external-users-project | grep pool\n\n# Monitor active connections\nSELECT pid, usename, application_name, state, query\nFROM pg_stat_activity\nWHERE state != 'idle'\nLIMIT 10;\n```\n\n### Latency Issues\n\n```bash\n# Measure tunnel latency\ntime psql \"postgresql://user:pass@neon.integratewise.io/multi_tenant_db\" \\\n  -c \"SELECT 1\"\n\n# Check network latency\nping neon.integratewise.io\n\n# Trace network path\ntraceroute neon.integratewise.io\n```\n"}