diff --git a/DATABASE_ISOLATION_FIX.md b/DATABASE_ISOLATION_FIX.md deleted file mode 100644 index 59033489..00000000 --- a/DATABASE_ISOLATION_FIX.md +++ /dev/null @@ -1,177 +0,0 @@ -# Database Isolation Fix for LearnHouse Deployments - -## Issues Identified: Multiple Sources of Cross-Deployment Contamination - -We have identified several issues causing cross-deployment contamination between DEV (adr-lms.whitex.cloud) and LIVE (edu.adradviser.ro) environments: - -### 1. Shared Database Connection - -Both deployments are connecting to the same database server, causing data sharing: - -- DEV: `postgresql://learnhouse_dev:YOUR_DEV_DB_PASSWORD@db:5432/learnhouse_dev` -- LIVE: `postgresql://learnhouse:YOUR_LIVE_DB_PASSWORD@db:5432/learnhouse` - -The container networking is not isolating these properly, causing both deployments to resolve `db` to the same physical database server. - -### 2. Hardcoded URLs in Frontend Bundle - -The DEV deployment contains hardcoded URLs pointing to the LIVE site: -- `http://edu.adradviser.ro/collections/new` -- `http://edu.adradviser.ro/courses?new=true` - -These URLs are embedded in the JavaScript bundles at build time and aren't being properly updated at runtime. - -### 3. Container API Access Inconsistencies - -The API is accessed differently from inside containers versus from outside: -- Inside container: via `http://localhost:9000` -- External access: via domain's `/api/v1` path - -This inconsistency complicates URL patching and can cause references to the wrong domain. - -## How to Fix Deployment Isolation - -### 1. Database Connection Isolation - -Each deployment must use its own fully-qualified database hostname: - -1. For DEV deployment: -``` -LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse_dev:YOUR_DEV_DB_PASSWORD@db-dev.${DEPLOYMENT_NAME}-network:5432/learnhouse_dev -``` - -2. For LIVE deployment: -``` -LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse:YOUR_LIVE_DB_PASSWORD@db-live.${DEPLOYMENT_NAME}-network:5432/learnhouse -``` - -This ensures: -- Each deployment uses a uniquely named database server -- The server hostname includes the deployment name for clarity -- The network name is deployment-specific - -### 2. Enhanced URL Patching - -We've improved the URL patching in Dockerfile_coolify to handle multiple URL formats: - -```bash -# Replace all occurrences of edu.adradviser.ro with the current domain -find /app/web/.next -type f -name "*.js" -exec sed -i "s|http://edu.adradviser.ro|$NEXT_PUBLIC_LEARNHOUSE_DOMAIN|g" {} \; -find /app/web/.next -type f -name "*.js" -exec sed -i "s|https://edu.adradviser.ro|$NEXT_PUBLIC_LEARNHOUSE_DOMAIN|g" {} \; -find /app/web/.next -type f -name "*.js" -exec sed -i "s|//edu.adradviser.ro|//$DOMAIN_ONLY|g" {} \; -find /app/web/.next -type f -name "*.js" -exec sed -i "s|\"href\":\"http://edu.adradviser.ro|\"href\":\"$NEXT_PUBLIC_LEARNHOUSE_DOMAIN|g" {} \; -``` - -### 3. Cookie Domain Isolation - -Ensure each deployment uses its own cookie domain: - -``` -LEARNHOUSE_COOKIE_DOMAIN=adr-lms.whitex.cloud # For DEV -LEARNHOUSE_COOKIE_DOMAIN=edu.adradviser.ro # For LIVE -``` - -### 4. API URL Inside vs Outside Container - -Address the inconsistency in how the API is accessed: - -1. Inside container: `http://localhost:9000` -2. External access: via domain's `/api/v1` path - -Solution: -- Added the debug endpoint at `/api/v1/debug` to ensure it's accessible externally -- Enhanced the URL patching to handle both internal and external URL formats - -### 5. API Debug Endpoints - -Added comprehensive debug endpoints: - -1. `/api/v1/debug/deployment` - Shows deployment configuration details -2. `/api/v1/debug/urls` - Scans for any remaining hardcoded URLs in the frontend bundle - -## Verification Process - -After implementing these fixes, use this verification process: - -1. **Deploy the API changes** to add the debug endpoints: - ```bash - git add apps/api/src/routers/debug.py apps/api/src/router.py apps/api/app.py - git commit -m "Add isolation debug endpoints for deployment verification" - git push - # Deploy through your CI/CD process - ``` - -2. **Verify database isolation** by accessing the debug endpoints: - ```bash - # Check DEV deployment - curl -k https://adr-lms.whitex.cloud/api/v1/debug/deployment - - # Check LIVE deployment - curl -k https://edu.adradviser.ro/api/v1/debug/deployment - ``` - -3. **Check for hardcoded URLs** in the frontend bundle: - ```bash - # Check DEV deployment - curl -k https://adr-lms.whitex.cloud/api/v1/debug/urls - - # Check LIVE deployment - curl -k https://edu.adradviser.ro/api/v1/debug/urls - ``` - -4. **Test with incognito browsers** to ensure sessions don't cross-contaminate - -5. **Run the verification script** to perform all checks automatically: - ```bash - ./verify-isolation.sh - ``` - -Solution: -- Added the debug endpoint at `/api/v1/debug` to ensure it's accessible externally -- Enhanced the URL patching to handle both internal and external URL formats - -### 5. API Debug Endpoints - -Added comprehensive debug endpoints: - -1. `/api/v1/debug/deployment` - Shows deployment configuration details -2. `/api/v1/debug/urls` - Scans for any remaining hardcoded URLs in the frontend bundle - -4. **Network Isolation**: Updated docker-compose-coolify.yml to use deployment-specific networks. - -## Verification Steps - -After implementing these changes: - -1. **Deploy the enhanced debug tools**: - ```bash - ./deploy-enhanced-debug.sh - ``` - -2. **Run the enhanced verification script** for comprehensive isolation checks: - ```bash - ./verify-enhanced-isolation.sh - ``` - -3. **Verify cookie isolation** using the dedicated cookie debug endpoint: - ```bash - curl -v https://adr-lms.whitex.cloud/api/v1/debug/cookies - curl -v https://edu.adradviser.ro/api/v1/debug/cookies - ``` - -4. **Check session configuration** to ensure proper isolation: - ```bash - curl https://adr-lms.whitex.cloud/api/v1/debug/session - curl https://edu.adradviser.ro/api/v1/debug/session - ``` - -5. **Test with incognito browsers** to ensure sessions don't cross-contaminate between deployments - -See `ENHANCED_DEBUG_TOOLS.md` for more detailed information on these debugging endpoints. - -## Implementation Plan - -1. Update database connection strings in Coolify environment variables for both deployments -2. Rebuild and redeploy both environments to apply the changes -3. Run the verification script to confirm isolation -4. Clear browser cookies and caches to test with clean state diff --git a/ENHANCED_DEBUG_TOOLS.md b/ENHANCED_DEBUG_TOOLS.md deleted file mode 100644 index 8716423a..00000000 --- a/ENHANCED_DEBUG_TOOLS.md +++ /dev/null @@ -1,123 +0,0 @@ -# Enhanced Debug Endpoints for Isolation Troubleshooting - -This document describes the enhanced debugging tools available to diagnose cross-deployment isolation issues between DEV and LIVE environments. - -## Available Debug Endpoints - -The following endpoints are available for diagnosing isolation issues: - -### 1. Deployment Information - -**Endpoint:** `/api/v1/debug/deployment` - -This endpoint provides detailed information about the current deployment, including: -- Deployment name -- Hostname and container ID -- Database connection details (host, user, database name) -- Redis connection details -- Cookie domain configuration -- Environment variables related to deployment URLs - -**Example Usage:** -```bash -curl https://adr-lms.whitex.cloud/api/v1/debug/deployment -``` - -### 2. URL Hardcoding Detection - -**Endpoint:** `/api/v1/debug/urls` - -This endpoint scans the NextJS bundle for hardcoded URLs that could lead to cross-contamination between deployments: -- Detects references to both DEV and LIVE domains -- Identifies NextAuth configuration issues -- Shows environment variables related to API URLs - -**Example Usage:** -```bash -curl https://adr-lms.whitex.cloud/api/v1/debug/urls -``` - -### 3. Cookie Isolation Testing - -**Endpoint:** `/api/v1/debug/cookies` - -This endpoint tests cookie isolation by: -- Setting a test cookie with the current deployment name -- Detecting any test cookies from other deployments -- Reporting the cookie domain in use -- Showing headers from the request - -**Example Usage:** -```bash -curl https://adr-lms.whitex.cloud/api/v1/debug/cookies -v -``` - -### 4. Session Configuration Check - -**Endpoint:** `/api/v1/debug/session` - -This endpoint examines session-related configuration: -- Shows request headers related to origins -- Reports NextAuth URL configuration -- Indicates where session requests would be sent - -**Example Usage:** -```bash -curl https://adr-lms.whitex.cloud/api/v1/debug/session -``` - -## Using the Enhanced Verification Script - -We've also created an enhanced isolation verification script that checks both DEV and LIVE deployments and provides a summary of their isolation status: - -```bash -./verify-enhanced-isolation.sh -``` - -The script will: -1. Check deployment configuration on both environments -2. Test cookie isolation -3. Look for hardcoded URLs -4. Verify session configuration -5. Analyze database isolation -6. Provide a summary of isolation status - -## Resolving Isolation Issues - -If the verification indicates isolation issues, ensure the following settings are unique between deployments: - -1. **Database Connections**: Each deployment should use its own database - ``` - # DEV environment - LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse_dev:YOUR_DEV_PASSWORD@db-dev:5432/learnhouse_dev - - # LIVE environment - LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse:YOUR_LIVE_PASSWORD@db-live:5432/learnhouse - ``` - -2. **Cookie Domains**: Each deployment should have its own cookie domain - ``` - # DEV environment - LEARNHOUSE_COOKIE_DOMAIN=adr-lms.whitex.cloud - - # LIVE environment - LEARNHOUSE_COOKIE_DOMAIN=edu.adradviser.ro - ``` - -3. **Top Domain Configuration**: Ensure each deployment has the correct top domain - ``` - # DEV environment - NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN=whitex.cloud - - # LIVE environment - NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN=adradviser.ro - ``` - -4. **Deployment Name**: Set a descriptive name to help with debugging - ``` - # DEV environment - DEPLOYMENT_NAME=DEV - - # LIVE environment - DEPLOYMENT_NAME=LIVE - ``` diff --git a/ISOLATION_IMPLEMENTATION_CHECKLIST.md b/ISOLATION_IMPLEMENTATION_CHECKLIST.md deleted file mode 100644 index 71cf4c66..00000000 --- a/ISOLATION_IMPLEMENTATION_CHECKLIST.md +++ /dev/null @@ -1,152 +0,0 @@ -# LearnHouse Deployment Isolation Implementation Checklist - -This checklist guides you through implementing complete isolation between DEV and LIVE LearnHouse deployments to prevent cross-deployment contamination. - -## Issue Overview - -We've identified that both DEV and LIVE deployments are accessing the same database and contain hardcoded URLs, causing: -- Data contamination (same courses appear in both deployments) -- Session mixing (logging in on one deployment affects the other) -- Inconsistent user experience (clicking links on DEV may lead to LIVE site) - -## Implementation Checklist - -### Step 1: Deploy API Changes - -- [ ] Pull the latest code with isolation fixes: - ```bash - git pull origin dev - ``` - -- [ ] Deploy the enhanced debug tools first: - ```bash - ./deploy-enhanced-debug.sh - ``` - -- [ ] Verify the enhanced debug endpoints are working: - ```bash - ls -la apps/api/src/routers/debug.py - ``` - -- [ ] Deploy API changes to both environments using your CI/CD system - -### Step 2: Update Environment Variables - -#### For DEV Environment: - -- [ ] Update database connection string: - ``` - LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse_dev:YOUR_DEV_PASSWORD@db-dev:5432/learnhouse_dev - ``` - -- [ ] Update Redis connection string: - ``` - LEARNHOUSE_REDIS_CONNECTION_STRING=redis://default:YOUR_DEV_REDIS_PASSWORD@redis-dev:6379/1 - ``` - -- [ ] Ensure domain settings are correct: - ``` - LEARNHOUSE_DOMAIN=adr-lms.whitex.cloud - LEARNHOUSE_COOKIE_DOMAIN=adr-lms.whitex.cloud - NEXT_PUBLIC_LEARNHOUSE_DOMAIN=adr-lms.whitex.cloud - ``` - -#### For LIVE Environment: - -- [ ] Update database connection string: - ``` - LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse:YOUR_LIVE_PASSWORD@db-live:5432/learnhouse - ``` - -- [ ] Update Redis connection string: - ``` - LEARNHOUSE_REDIS_CONNECTION_STRING=redis://default:YOUR_LIVE_REDIS_PASSWORD@redis-live:6379/0 - ``` - -- [ ] Ensure domain settings are correct: - ``` - LEARNHOUSE_DOMAIN=edu.adradviser.ro - LEARNHOUSE_COOKIE_DOMAIN=edu.adradviser.ro - NEXT_PUBLIC_LEARNHOUSE_DOMAIN=edu.adradviser.ro - ``` - -### Step 3: Database Infrastructure - -- [ ] Ensure each deployment has its own database server: - - DEV: db-dev - - LIVE: db-live - -- [ ] If using shared infrastructure, ensure logical isolation through server names and proper networking - -### Step 4: Rebuild & Deploy - -- [ ] Rebuild and deploy both environments with updated environment variables -- [ ] Restart all services to apply changes - -### Step 5: Verification - -- [ ] Run the comprehensive isolation verification script: - ```bash - ./verify-all-isolation.sh - ``` - This will: - - Check deployment configuration - - Verify database isolation - - Test cookie isolation - - Check for hardcoded URLs - - Create a visual cookie isolation demo - -- [ ] For more detailed verification, run individual scripts: - ```bash - ./verify-enhanced-isolation.sh # Basic deployment checks - ./verify-db-isolation.sh # Database-specific checks - ./test-nextauth-cookie-isolation.sh # Cookie isolation tests - ``` - -- [ ] Test the visual cookie isolation demo: - ```bash - ./create-cookie-demo.sh - # Open the resulting HTML file in a browser - ``` - -- [ ] Access debug endpoints directly: - - DEV: https://adr-lms.whitex.cloud/api/v1/debug/deployment - - LIVE: https://edu.adradviser.ro/api/v1/debug/deployment - - DEV: https://adr-lms.whitex.cloud/api/v1/debug/cookies - - LIVE: https://edu.adradviser.ro/api/v1/debug/cookies - - DEV: https://adr-lms.whitex.cloud/api/v1/debug/session - - LIVE: https://edu.adradviser.ro/api/v1/debug/session - -- [ ] Test in incognito browsers to verify session isolation - -## Troubleshooting - -If isolation issues persist after implementation: - -1. **Use the Enhanced Debug Tools**: - - Look at the detailed reports in `/tmp/learnhouse-isolation-report/` - - Run specific tests: `./test-nextauth-cookie-isolation.sh` for cookie issues - - Check session configuration: `/api/v1/debug/session` endpoint - -2. **Verify Database Connections**: - - Confirm debug endpoints show different database hosts and names - - Check actual database servers to confirm connections come from different sources - - Test with the database isolation script: `./verify-db-isolation.sh` - -3. **Clear Browser Data**: - - Use incognito mode or clear all cookies/cache for proper testing - - Try the cookie isolation demo to visually check cookie behavior - -4. **Check Docker Network Isolation**: - - Ensure each deployment uses its own Docker network - - Verify hostnames resolve to different IP addresses within containers - -5. **Validate URL Patching**: - - Run URL debug endpoint to confirm no hardcoded references remain - - Check the enhanced URL report in `/api/v1/debug/urls` endpoint - -For additional help, refer to the full documentation in: -- `ENHANCED_DEBUG_TOOLS.md` - Detailed guide to all debug endpoints -- `DATABASE_ISOLATION_FIX.md` - Database isolation specifics -- `DEPLOYMENT_TROUBLESHOOTING.md` - General deployment troubleshooting -- `ISOLATION_TOOLKIT_README.md` - Overview of all isolation tools diff --git a/ISOLATION_IMPROVEMENTS.md b/ISOLATION_IMPROVEMENTS.md deleted file mode 100644 index 80df6cee..00000000 --- a/ISOLATION_IMPROVEMENTS.md +++ /dev/null @@ -1,74 +0,0 @@ -# LearnHouse Isolation Fix: Improvements Summary - -We've developed a comprehensive set of tools, scripts, and documentation to help diagnose and fix deployment isolation issues between DEV and LIVE instances. Here's a summary of the improvements: - -## 1. Enhanced Debug Endpoints - -We expanded the API debug capabilities significantly: - -- **`/api/v1/debug/deployment`**: Enhanced with detailed database, Redis, container, and hostname information -- **`/api/v1/debug/urls`**: Improved to detect cross-contamination from both domains and categorize findings -- **`/api/v1/debug/cookies`**: New endpoint to test cookie isolation and detect cross-deployment cookies -- **`/api/v1/debug/session`**: New endpoint to check session configuration and origins - -## 2. Verification Scripts - -We created several verification scripts for different aspects of isolation: - -- **`verify-enhanced-isolation.sh`**: Comprehensive isolation checks for all aspects of deployment -- **`test-nextauth-cookie-isolation.sh`**: Focused testing for NextAuth cookie isolation -- **`verify-all-isolation.sh`**: Master script that runs all verification checks and produces a report -- **`create-cookie-demo.sh`**: Visual tool to demonstrate and test cookie behavior in browsers - -## 3. Documentation - -- **`ENHANCED_DEBUG_TOOLS.md`**: Detailed guide to all debug endpoints and how to use them -- **`ISOLATION_TOOLKIT_README.md`**: Overview of all tools available for isolation testing -- **Updated `ISOLATION_IMPLEMENTATION_CHECKLIST.md`**: Comprehensive checklist with new tools -- **Updated `DATABASE_ISOLATION_FIX.md`**: Enhanced verification methods - -## 4. Developer Experience - -- Visual cookie isolation demo with browser-based testing -- HTML reports for easy sharing and analyzing of results -- Colored terminal output for easy interpretation of verification results -- Container and hostname information for infrastructure verification - -## 5. Implementation Details - -The specific code improvements include: - -1. **Enhanced database information**: - - Now shows database username, hostname and database name - - Extracts Redis instance information - -2. **Cookie isolation testing**: - - Sets test cookies with deployment name - - Checks if cookies from one deployment are visible to another - - Visual browser-based tool to demonstrate isolation - -3. **Session configuration verification**: - - Analyzes headers and environment variables that affect session behavior - - Shows where sessions would be sent based on current configuration - -4. **Comprehensive URL checking**: - - Categorizes URLs by domain to identify cross-contamination - - Reports specific instances of hardcoded URLs in the frontend - -## Usage - -To use these enhanced tools: - -1. Deploy the enhanced debug module: - ```bash - ./deploy-enhanced-debug.sh - ``` - -2. Run the comprehensive verification: - ```bash - ./verify-all-isolation.sh - ``` - -3. Check the reports generated in `/tmp/learnhouse-isolation-report/` - -These enhancements will make it much easier to diagnose and fix isolation issues between the DEV and LIVE LearnHouse deployments. diff --git a/ISOLATION_TOOLKIT_README.md b/ISOLATION_TOOLKIT_README.md deleted file mode 100644 index 9ab7fe7c..00000000 --- a/ISOLATION_TOOLKIT_README.md +++ /dev/null @@ -1,107 +0,0 @@ -# LearnHouse Deployment Isolation Toolkit - -This toolkit provides comprehensive tools and documentation for diagnosing and fixing deployment isolation issues between DEV and LIVE LearnHouse instances. - -## Background - -We identified cross-deployment contamination issues between DEV (adr-lms.whitex.cloud) and LIVE (edu.adradviser.ro) deployments, including: - -- Data contamination (both deployments accessing the same database) -- Session mixing (cookies being shared between deployments) -- Inconsistent user experience (hardcoded URLs pointing to the wrong environment) - -## Isolation Toolkit Components - -### Documentation - -1. **[ISOLATION_IMPLEMENTATION_CHECKLIST.md](./ISOLATION_IMPLEMENTATION_CHECKLIST.md)** - Step-by-step checklist for implementing complete isolation between deployments. - -2. **[DATABASE_ISOLATION_FIX.md](./DATABASE_ISOLATION_FIX.md)** - Detailed explanation of database isolation issues and how to fix them. - -3. **[DEPLOYMENT_TROUBLESHOOTING.md](./DEPLOYMENT_TROUBLESHOOTING.md)** - Guide for troubleshooting deployment and configuration issues. - -4. **[ENHANCED_DEBUG_TOOLS.md](./ENHANCED_DEBUG_TOOLS.md)** - Documentation for the enhanced debugging endpoints. - -5. **[COOLIFY_ENV_VARS.md](./COOLIFY_ENV_VARS.md)** - Environment variable templates for Coolify deployments. - -### Debugging Tools - -1. **Debug API Endpoints** - - `/api/v1/debug/deployment` - Get detailed deployment configuration - - `/api/v1/debug/urls` - Scan for hardcoded URLs in the frontend bundle - - `/api/v1/debug/cookies` - Test cookie isolation between deployments - - `/api/v1/debug/session` - Verify session configuration - -2. **Verification Scripts** - - `verify-isolation.sh` - Basic isolation verification - - `verify-enhanced-isolation.sh` - Comprehensive isolation checks - - `verify-db-isolation.sh` - Database-specific isolation verification - - `test-nextauth-cookie-isolation.sh` - NextAuth cookie isolation test - -3. **Visual Demonstration Tools** - - `create-cookie-demo.sh` - Creates an HTML tool to visually demonstrate cookie isolation - -### Deployment Scripts - -1. **`deploy-enhanced-debug.sh`** - Deploys the enhanced debugging endpoints to diagnose isolation issues. - -2. **`deploy-isolation-fix.sh`** - Applies the complete isolation fixes to both deployments. - -## Getting Started - -1. **Deploy debugging tools:** - ```bash - ./deploy-enhanced-debug.sh - ``` - -2. **Run the enhanced isolation verification:** - ```bash - ./verify-enhanced-isolation.sh - ``` - -3. **Test cookie isolation:** - ```bash - ./test-nextauth-cookie-isolation.sh - ``` - -4. **Create a visual cookie isolation demo:** - ```bash - ./create-cookie-demo.sh - # Then open cookie-isolation-demo.html in your browser - ``` - -5. **Follow the implementation checklist:** - See [ISOLATION_IMPLEMENTATION_CHECKLIST.md](./ISOLATION_IMPLEMENTATION_CHECKLIST.md) - -## Key Environment Variables for Isolation - -For proper isolation, ensure each deployment has unique values for these variables: - -### DEV Environment -``` -DEPLOYMENT_NAME=DEV -LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse_dev:PASSWORD@db-dev:5432/learnhouse_dev -LEARNHOUSE_COOKIE_DOMAIN=adr-lms.whitex.cloud -NEXT_PUBLIC_LEARNHOUSE_DOMAIN=adr-lms.whitex.cloud -NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN=whitex.cloud -``` - -### LIVE Environment -``` -DEPLOYMENT_NAME=LIVE -LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse:PASSWORD@db-live:5432/learnhouse -LEARNHOUSE_COOKIE_DOMAIN=edu.adradviser.ro -NEXT_PUBLIC_LEARNHOUSE_DOMAIN=edu.adradviser.ro -NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN=adradviser.ro -``` - -## Troubleshooting - -If you encounter issues during the isolation process, refer to [DEPLOYMENT_TROUBLESHOOTING.md](./DEPLOYMENT_TROUBLESHOOTING.md). diff --git a/apps/api/src/router.py b/apps/api/src/router.py index 1fbc95b5..dae5b019 100644 --- a/apps/api/src/router.py +++ b/apps/api/src/router.py @@ -2,9 +2,7 @@ import os from fastapi import APIRouter, Depends from src.routers import health from src.routers import usergroups -from src.routers import dev, trail, users, auth, orgs, roles, search -# Use enhanced debug module with improved isolation diagnostics -from src.routers import debug_enhanced as debug +from src.routers import dev, trail, users, auth, orgs, roles, search, debug from src.routers.ai import ai from src.routers.courses import chapters, collections, courses, assignments, certifications from src.routers.courses.activities import activities, blocks diff --git a/apps/api/src/routers/debug_enhanced.py b/apps/api/src/routers/debug_enhanced.py deleted file mode 100644 index c2fa6cda..00000000 --- a/apps/api/src/routers/debug_enhanced.py +++ /dev/null @@ -1,269 +0,0 @@ -import os -import json -import socket -import subprocess -from fastapi import APIRouter, Request, Response -from config.config import get_learnhouse_config - -router = APIRouter() - -@router.get("/deployment") -async def debug_deployment(): - """Debug endpoint for deployment verification and isolation testing""" - learnhouse_config = get_learnhouse_config() - - # Parse database host safely - db_host = "unknown" - db_user = "unknown" - db_name = "unknown" - if '@' in learnhouse_config.database_config.sql_connection_string: - try: - # Split out username and host parts - auth_host_parts = learnhouse_config.database_config.sql_connection_string.split('@') - if len(auth_host_parts) > 1: - # Extract username - auth_parts = auth_host_parts[0].split('//') - if len(auth_parts) > 1: - user_parts = auth_parts[1].split(':') - if len(user_parts) > 0: - db_user = user_parts[0] - - # Extract host and database name - host_parts = auth_host_parts[1].split('/') - if len(host_parts) > 0: - db_host = host_parts[0] - if len(host_parts) > 1: - db_name = host_parts[1] - except Exception as e: - pass - - # Parse redis host safely - redis_host = "unknown" - redis_db = "unknown" - if '@' in learnhouse_config.redis_config.redis_connection_string: - try: - parts = learnhouse_config.redis_config.redis_connection_string.split('@') - if len(parts) > 1: - host_parts = parts[1].split(':') - if len(host_parts) > 0: - redis_host = host_parts[0] - if len(host_parts) > 1 and '/' in host_parts[1]: - redis_db = host_parts[1].split('/')[1] - except Exception: - pass - - # Get hostname information - hostname = "unknown" - try: - hostname = socket.gethostname() - except: - pass - - # Get process and container info - container_id = "unknown" - try: - # Try to get container ID from cgroup - with open('/proc/self/cgroup', 'r') as f: - for line in f: - if 'docker' in line: - container_id = line.strip().split('/')[-1] - break - except: - pass - - return { - "deployment_name": os.environ.get('DEPLOYMENT_NAME', 'NOT_SET'), - "hostname": hostname, - "container_id": container_id, - "cookie_domain": learnhouse_config.hosting_config.cookie_config.domain, - "api_domain": learnhouse_config.hosting_config.domain, - "database": { - "host": db_host, - "user": db_user, - "name": db_name, - }, - "redis": { - "host": redis_host, - "db": redis_db - }, - "env_vars": { - "NEXT_PUBLIC_LEARNHOUSE_DOMAIN": os.environ.get('NEXT_PUBLIC_LEARNHOUSE_DOMAIN', 'NOT_SET'), - "NEXT_PUBLIC_LEARNHOUSE_API_URL": os.environ.get('NEXT_PUBLIC_LEARNHOUSE_API_URL', 'NOT_SET'), - "NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN": os.environ.get('NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN', 'NOT_SET'), - "LEARNHOUSE_COOKIE_DOMAIN": os.environ.get('LEARNHOUSE_COOKIE_DOMAIN', 'NOT_SET') - } - } - -@router.get("/urls") -async def debug_urls(request: Request): - """Debug endpoint to detect hardcoded URLs in NextJS bundle""" - try: - # Define domains to check for hardcoding - known_domains = [ - "edu.adradviser.ro", # LIVE domain - "adr-lms.whitex.cloud" # DEV domain - ] - - # Add any additional domains from environment variables - current_domain = os.environ.get('NEXT_PUBLIC_LEARNHOUSE_DOMAIN', '') - if current_domain and current_domain not in known_domains: - known_domains.append(current_domain) - - # Build patterns for all domains to detect cross-contamination - patterns = [] - for domain in known_domains: - patterns.extend([ - f"http://{domain}[^\"']*", - f"https://{domain}[^\"']*", - f"//{domain}[^\"']*", - f"'{domain}'", - f"\"{domain}\"", - f"fetch\\(\"https://{domain}", - f"fetch\\(\"http://{domain}", - ]) - - # Add general patterns for NextAuth configuration - patterns.extend([ - "\"/api/auth/session\"", - "\"auth/session\"", - "fetch\\(\"/api/auth", - "domain:\"[^\"]*\"", - "baseUrl:\"[^\"]*\"", - "basePath:\"[^\"]*\"", - "NEXTAUTH_URL=\"[^\"]*\"", - "NEXTAUTH_URL='[^']*'" - ]) - - all_urls = [] - domain_matches = {domain: [] for domain in known_domains} - - # Search for URLs in JS files - for pattern in patterns: - result = subprocess.run( - ["find", "/app/web/.next", "-type", "f", "-name", "*.js", "-exec", "grep", "-o", pattern, "{}", ";"], - capture_output=True, text=True, timeout=10 - ) - if result.stdout.strip(): - found_urls = list(set(result.stdout.strip().split('\n'))) - all_urls.extend(found_urls) - - # Categorize URLs by domain - for url in found_urls: - for domain in known_domains: - if domain in url: - domain_matches[domain].append(url) - - # Look for NextAuth configuration - auth_configs = [] - try: - auth_result = subprocess.run( - ["find", "/app/web/.next", "-type", "f", "-name", "*.js", "-exec", "grep", "-o", "NEXTAUTH_URL[^,}]*", "{}", ";"], - capture_output=True, text=True, timeout=5 - ) - if auth_result.stdout.strip(): - auth_configs = list(set(auth_result.stdout.strip().split('\n'))) - except Exception: - pass - - # Gather environment variable information - env_vars = { - "NEXT_PUBLIC_LEARNHOUSE_DOMAIN": os.environ.get('NEXT_PUBLIC_LEARNHOUSE_DOMAIN', 'NOT_SET'), - "NEXT_PUBLIC_LEARNHOUSE_API_URL": os.environ.get('NEXT_PUBLIC_LEARNHOUSE_API_URL', 'NOT_SET'), - "NEXT_PUBLIC_API_URL": os.environ.get('NEXT_PUBLIC_API_URL', 'NOT_SET'), - "NEXTAUTH_URL": os.environ.get('NEXTAUTH_URL', 'NOT_SET'), - "NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN": os.environ.get('NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN', 'NOT_SET'), - "LEARNHOUSE_COOKIE_DOMAIN": os.environ.get('LEARNHOUSE_COOKIE_DOMAIN', 'NOT_SET') - } - - # Get the top domain from an environment variable or extract from current domain - top_domain = os.environ.get('NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN', '') - if not top_domain and current_domain: - parts = current_domain.split('.') - if len(parts) >= 2: - top_domain = '.'.join(parts[-2:]) - - return { - "detected_hardcoded_urls": all_urls, - "domain_specific_matches": domain_matches, - "nextauth_configs": auth_configs, - "current_domain": current_domain, - "top_domain": top_domain, - "env_vars": env_vars, - "client_host": request.client.host, - "headers": dict(request.headers), - "deployment_name": os.environ.get('DEPLOYMENT_NAME', 'NOT_SET'), - "request_url": str(request.url) - } - except Exception as e: - return { - "error": str(e), - "message": "Could not scan for hardcoded URLs", - "deployment_name": os.environ.get('DEPLOYMENT_NAME', 'NOT_SET') - } - -@router.get("/cookies") -async def debug_cookies(request: Request, response: Response): - """Debug endpoint to test cookie isolation and behavior""" - # Get current configuration - learnhouse_config = get_learnhouse_config() - cookie_domain = learnhouse_config.hosting_config.cookie_config.domain - deployment_name = os.environ.get('DEPLOYMENT_NAME', 'unknown') - - # Set a test cookie with the current configuration - response.set_cookie( - key=f"isolation-test-{deployment_name}", - value=deployment_name, - domain=cookie_domain, - httponly=True, - samesite="lax", - path="/" - ) - - # Try to read any existing isolation test cookies - cookies = request.cookies - isolation_cookies = {} - - for key, value in cookies.items(): - if key.startswith("isolation-test-"): - isolation_cookies[key] = value - - return { - "deployment_name": deployment_name, - "cookie_domain": cookie_domain, - "request_host": request.headers.get("host", "unknown"), - "detected_isolation_cookies": isolation_cookies, - "all_cookies": {k: "****" if not k.startswith("isolation-test") else v for k, v in cookies.items()}, - "top_domain": os.environ.get('NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN', 'NOT_SET'), - "message": f"Set test cookie 'isolation-test-{deployment_name}={deployment_name}' with domain={cookie_domain}" - } - -@router.get("/session") -async def debug_session(request: Request): - """Debug endpoint to check session-related headers and environment variables""" - # Extract host information - host = request.headers.get("host", "unknown") - origin = request.headers.get("origin", "unknown") - referer = request.headers.get("referer", "unknown") - - # Extract NextAuth related information - nextauth_url = os.environ.get('NEXTAUTH_URL', 'NOT_SET') - nextauth_url_internal = os.environ.get('NEXTAUTH_URL_INTERNAL', 'NOT_SET') - - # Check if session requests would go to the correct place - session_destination = nextauth_url or f"https://{host}" - - return { - "deployment_name": os.environ.get('DEPLOYMENT_NAME', 'unknown'), - "request_headers": { - "host": host, - "origin": origin, - "referer": referer, - }, - "session_config": { - "NEXTAUTH_URL": nextauth_url, - "NEXTAUTH_URL_INTERNAL": nextauth_url_internal, - "detected_session_destination": session_destination - }, - "cookie_domain": get_learnhouse_config().hosting_config.cookie_config.domain, - "message": "This endpoint helps diagnose where NextAuth session data would be sent" - } diff --git a/create-cookie-demo.sh b/create-cookie-demo.sh deleted file mode 100755 index 58ae807d..00000000 --- a/create-cookie-demo.sh +++ /dev/null @@ -1,264 +0,0 @@ -#!/bin/bash - -# Create a demonstration HTML file to visualize cookie isolation problems -# This script generates an HTML file that shows which cookies are visible across deployments - -echo "Creating cookie isolation visualization tool..." - -# Define HTML content -cat > /home/whitex/dev/github/learnhouse/cookie-isolation-demo.html << 'EOL' - - -
- - -This tool helps visualize cookie isolation between DEV and LIVE LearnHouse deployments. - It will help you identify if cookies from one deployment are visible to the other, which - could lead to session contamination.
-First, set test cookies on both deployments:
- - - -Now check if cookies are properly isolated between deployments:
- -Results will appear here after running tests...
-