235 lines
7.6 KiB
Bash
235 lines
7.6 KiB
Bash
#!/bin/bash
|
||
# =================================================================
|
||
# Test Training Service Token Generation and Gateway Validation
|
||
# =================================================================
|
||
|
||
set -e
|
||
|
||
# Configuration
|
||
API_BASE="http://localhost:8000"
|
||
AUTH_BASE="http://localhost:8001"
|
||
|
||
# Colors for output
|
||
RED='\033[0;31m'
|
||
GREEN='\033[0;32m'
|
||
YELLOW='\033[1;33m'
|
||
BLUE='\033[0;34m'
|
||
NC='\033[0m'
|
||
|
||
log_info() { echo -e "${BLUE}ℹ️ $1${NC}"; }
|
||
log_success() { echo -e "${GREEN}✅ $1${NC}"; }
|
||
log_warning() { echo -e "${YELLOW}⚠️ $1${NC}"; }
|
||
log_error() { echo -e "${RED}❌ $1${NC}"; }
|
||
log_step() { echo -e "${BLUE}🔄 $1${NC}"; }
|
||
|
||
echo "🧪 Testing Training Service Token with Gateway Middleware"
|
||
echo "========================================================"
|
||
|
||
# Step 1: Create a service token like training service would
|
||
log_step "Step 1: Creating Service Token (Training Service Style)"
|
||
|
||
# Use Python to create the same token the training service would create
|
||
SERVICE_TOKEN=$(python3 -c "
|
||
import sys
|
||
import time
|
||
import os
|
||
sys.path.append('.')
|
||
|
||
# Import your shared JWT handler
|
||
from shared.auth.jwt_handler import JWTHandler
|
||
|
||
# Use same secret as gateway/auth service
|
||
JWT_SECRET = os.getenv('JWT_SECRET_KEY', 'your-super-secret-jwt-key-change-in-production-min-32-characters-long')
|
||
|
||
# Create JWT handler
|
||
jwt_handler = JWTHandler(JWT_SECRET)
|
||
|
||
# Create service payload (same as training service would)
|
||
service_payload = {
|
||
'sub': 'training-service',
|
||
'user_id': 'training-service',
|
||
'email': 'training-service@internal',
|
||
'service': 'training',
|
||
'type': 'access', # Important: must be 'access' type
|
||
'exp': int(time.time()) + 3600, # 1 hour
|
||
'iat': int(time.time()),
|
||
'iss': 'training-service',
|
||
'full_name': 'Training Service',
|
||
'is_verified': True,
|
||
'is_active': True
|
||
}
|
||
|
||
# Create token
|
||
token = jwt_handler.create_access_token_from_payload(service_payload)
|
||
print(token)
|
||
")
|
||
|
||
if [ -z "$SERVICE_TOKEN" ]; then
|
||
log_error "Failed to create service token"
|
||
exit 1
|
||
fi
|
||
|
||
log_success "Service token created successfully"
|
||
echo "Token: ${SERVICE_TOKEN:0:50}..."
|
||
|
||
echo ""
|
||
|
||
# Step 2: Decode and inspect the token
|
||
log_step "Step 2: Decoding Service Token Payload"
|
||
|
||
# Decode the payload to see what's inside
|
||
PAYLOAD=$(echo "$SERVICE_TOKEN" | cut -d'.' -f2)
|
||
# Add padding if needed
|
||
while [ $((${#PAYLOAD} % 4)) -ne 0 ]; do
|
||
PAYLOAD="${PAYLOAD}="
|
||
done
|
||
|
||
echo "Service Token Payload:"
|
||
echo "$PAYLOAD" | base64 -d 2>/dev/null | jq '.' || echo "Failed to decode"
|
||
|
||
echo ""
|
||
|
||
# Step 3: Test token with gateway middleware
|
||
log_step "Step 3: Testing Service Token with Gateway Middleware"
|
||
|
||
# Test a tenant-scoped endpoint that training service would call
|
||
TENANT_ID="b2a268a0-904f-4182-8f81-ec25d0e6def7" # From your test
|
||
|
||
log_info "Testing GET /api/v1/tenants/$TENANT_ID/sales with service token..."
|
||
|
||
GATEWAY_RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}\n" -X GET \
|
||
"$API_BASE/api/v1/tenants/$TENANT_ID/sales" \
|
||
-H "Authorization: Bearer $SERVICE_TOKEN" \
|
||
-H "X-Tenant-ID: $TENANT_ID" \
|
||
-H "X-Service: training-service" \
|
||
-H "Content-Type: application/json")
|
||
|
||
echo "Gateway Response:"
|
||
echo "$GATEWAY_RESPONSE"
|
||
|
||
# Check the result
|
||
if echo "$GATEWAY_RESPONSE" | grep -q "HTTP_CODE:200"; then
|
||
log_success "✅ Service token ACCEPTED by gateway middleware!"
|
||
log_success "Training service authentication would work!"
|
||
elif echo "$GATEWAY_RESPONSE" | grep -q "HTTP_CODE:401"; then
|
||
log_error "❌ Service token REJECTED by gateway middleware (401 Unauthorized)"
|
||
log_warning "This explains why training service fails"
|
||
elif echo "$GATEWAY_RESPONSE" | grep -q "HTTP_CODE:404"; then
|
||
log_warning "⚠️ Endpoint not found (404) - but token was accepted by middleware"
|
||
log_success "Authentication passed, routing issue"
|
||
else
|
||
log_warning "Unexpected HTTP response code"
|
||
fi
|
||
|
||
echo ""
|
||
|
||
# Step 4: Test with a known working user token for comparison
|
||
log_step "Step 4: Comparison Test with User Token"
|
||
|
||
# Get a real user token from the onboarding test
|
||
USER_TOKEN=""
|
||
if [ -f "/tmp/test_user_token.txt" ]; then
|
||
USER_TOKEN=$(cat /tmp/test_user_token.txt)
|
||
fi
|
||
|
||
if [ -z "$USER_TOKEN" ]; then
|
||
log_info "Creating a user token for comparison..."
|
||
|
||
# Quick user login to get a token
|
||
USER_LOGIN_RESPONSE=$(curl -s -X POST "$API_BASE/api/v1/auth/login" \
|
||
-H "Content-Type: application/json" \
|
||
-d '{
|
||
"email": "onboarding.test.1753606890@bakery.com",
|
||
"password": "TestPassword123!"
|
||
}')
|
||
|
||
USER_TOKEN=$(echo "$USER_LOGIN_RESPONSE" | jq -r '.access_token' 2>/dev/null)
|
||
fi
|
||
|
||
if [ -n "$USER_TOKEN" ] && [ "$USER_TOKEN" != "null" ]; then
|
||
log_info "Testing same endpoint with user token..."
|
||
|
||
USER_RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}\n" -X GET \
|
||
"$API_BASE/api/v1/tenants/$TENANT_ID/sales" \
|
||
-H "Authorization: Bearer $USER_TOKEN" \
|
||
-H "X-Tenant-ID: $TENANT_ID")
|
||
|
||
if echo "$USER_RESPONSE" | grep -q "HTTP_CODE:200"; then
|
||
log_success "User token works - gateway middleware is functioning"
|
||
elif echo "$USER_RESPONSE" | grep -q "HTTP_CODE:401"; then
|
||
log_warning "User token also fails - gateway middleware issue"
|
||
else
|
||
log_info "User token response: $(echo "$USER_RESPONSE" | tail -1)"
|
||
fi
|
||
else
|
||
log_warning "Could not get user token for comparison"
|
||
fi
|
||
|
||
echo ""
|
||
|
||
# Step 5: Test gateway auth verification endpoint
|
||
log_step "Step 5: Testing Token with Gateway Auth Verification"
|
||
|
||
log_info "Testing service token with /api/v1/auth/verify..."
|
||
VERIFY_RESPONSE=$(curl -s -X POST "$API_BASE/api/v1/auth/verify" \
|
||
-H "Authorization: Bearer $SERVICE_TOKEN")
|
||
|
||
echo "Verification Response:"
|
||
echo "$VERIFY_RESPONSE" | jq '.' 2>/dev/null || echo "$VERIFY_RESPONSE"
|
||
|
||
if echo "$VERIFY_RESPONSE" | jq -e '.valid' > /dev/null 2>&1; then
|
||
if [ "$(echo "$VERIFY_RESPONSE" | jq -r '.valid')" = "true" ]; then
|
||
log_success "Service token is VALID according to auth service"
|
||
else
|
||
log_error "Service token is INVALID according to auth service"
|
||
fi
|
||
else
|
||
log_warning "Verification response doesn't contain 'valid' field"
|
||
fi
|
||
|
||
echo ""
|
||
|
||
# Step 6: Diagnosis and recommendations
|
||
log_step "Step 6: Diagnosis and Recommendations"
|
||
|
||
# Check JWT secrets match
|
||
log_info "Checking JWT secret consistency..."
|
||
if docker-compose exec -T gateway env 2>/dev/null | grep -q JWT_SECRET_KEY; then
|
||
log_success "Gateway has JWT_SECRET_KEY configured"
|
||
else
|
||
log_error "Gateway missing JWT_SECRET_KEY configuration"
|
||
fi
|
||
|
||
if docker-compose exec -T auth-service env 2>/dev/null | grep -q JWT_SECRET_KEY; then
|
||
log_success "Auth service has JWT_SECRET_KEY configured"
|
||
else
|
||
log_error "Auth service missing JWT_SECRET_KEY configuration"
|
||
fi
|
||
|
||
echo ""
|
||
echo "🏁 Test Summary:"
|
||
echo "=================="
|
||
|
||
if echo "$GATEWAY_RESPONSE" | grep -q "HTTP_CODE:200"; then
|
||
echo "✅ Service token authentication: WORKING"
|
||
echo "✅ Training service should be able to fetch sales data"
|
||
echo ""
|
||
echo "🎯 Next Steps:"
|
||
echo "1. Update training service to use gateway URL: http://gateway:8000"
|
||
echo "2. Ensure training service creates tokens with same payload structure"
|
||
echo "3. Test with: docker-compose restart training-service"
|
||
elif echo "$GATEWAY_RESPONSE" | grep -q "HTTP_CODE:401"; then
|
||
echo "❌ Service token authentication: FAILING"
|
||
echo "❌ This explains why training service gets 401 errors"
|
||
echo ""
|
||
echo "🔧 Fixes needed:"
|
||
echo "1. Check JWT_SECRET_KEY matches across services"
|
||
echo "2. Update gateway middleware to accept service tokens"
|
||
echo "3. Verify token payload structure matches gateway expectations"
|
||
else
|
||
echo "⚠️ Inconclusive test results"
|
||
echo "Check the response details above"
|
||
fi
|
||
|
||
echo ""
|
||
echo "🧪 Test completed!" |