diff --git a/IMPLEMENTATION_GUIDE.md b/IMPLEMENTATION_GUIDE.md new file mode 100644 index 00000000..3f56ae4d --- /dev/null +++ b/IMPLEMENTATION_GUIDE.md @@ -0,0 +1,31 @@ +# Security Implementation Guide + +## Issue #122 - Critical Security Fixes + +### 1. Nginx Configuration (IMMEDIATE) +Deploy `security-fixes/nginx/dev-environment.conf` to restrict dev environment access + +### 2. Frontend Security (CRITICAL) +Replace current APP_SETTINGS with `security-fixes/frontend/secure-config.js` + +### 3. Backend Authentication (HIGH) +Implement `security-fixes/backend/secure-version-endpoint.py` to protect version info + +### 4. Error Handling (HIGH) +Deploy `security-fixes/backend/secure-error-handling.py` to prevent schema disclosure + +### 5. Storage Security (MEDIUM) +Apply `security-fixes/backend/minio-bucket-policy.json` to MinIO server + +## Testing +- Verify dev environment returns 403 for external IPs +- Confirm no payment credentials in client JS +- Test version endpoint requires authentication +- Validate generic error responses +- Check bucket enumeration is blocked + +## Impact +✅ Eliminates payment credential exposure +✅ Prevents infrastructure reconnaissance +✅ Secures database schema disclosure +✅ Implements defense-in-depth security diff --git a/SECURITY_FIX_README.md b/SECURITY_FIX_README.md new file mode 100644 index 00000000..43144eac --- /dev/null +++ b/SECURITY_FIX_README.md @@ -0,0 +1,48 @@ +# Security Fix Implementation Guide + +## Overview +This security fix addresses the critical configuration disclosure vulnerability in the compute marketplace admin endpoint. + +## Vulnerability Fixed +- **Issue:** `/api/compute_marketplace/admin` exposed sensitive payment credentials +- **Root Cause:** Missing authentication and access controls +- **Impact:** Live PayPal/Stripe credentials leaked to unauthenticated users + +## Security Measures Implemented + +### 1. Authentication Requirements +```python +@login_required +@user_passes_test(is_admin_user) +### 2. Permission Validation +- Requires `compute.admin_access` permission +- Validates user staff status +- Implements role-based access control + +### 3. Configuration Sanitization +- Removes sensitive payment credentials from responses +- Filters infrastructure details +- Implements safe configuration exposure + +### 4. Security Logging +- Logs all admin access attempts +- Records unauthorized access attempts +- Provides audit trail for compliance + +### 5. Path Traversal Protection +- Blocks `../admin` traversal attempts +- Implements URL pattern validation +- Prevents directory traversal attacks + +## Implementation Steps + +1. **Apply the security fix:** + ```bash + cp security_fix_config_disclosure.py your_project/compute/views.py +# Add to urls.py +from .views import compute_marketplace_admin +# Add to your user model or permissions system +class ComputePermissions: + ADMIN_ACCESS = 'compute.admin_access' +# Should now require authentication +curl -L https://app.aixblock.io/api/compute_marketplace/admin diff --git a/SECURITY_FIX_organization_endpoints.md b/SECURITY_FIX_organization_endpoints.md new file mode 100644 index 00000000..b4a92db8 --- /dev/null +++ b/SECURITY_FIX_organization_endpoints.md @@ -0,0 +1,40 @@ +# Security Fix: Organization Token Disclosure (Issue #118) + +## Vulnerability Description +The /api/organizations/{id} endpoints expose sensitive organizational data including authentication tokens without requiring authentication. + +## Root Cause +Missing authentication checks and excessive data exposure in organization API endpoints. + +## Proposed Fix + +### 1. Add Authentication Middleware +Before (vulnerable): +@api_view(['GET']) +def get_organization(request, org_id): + organization = Organization.objects.get(id=org_id) + return Response(OrganizationSerializer(organization).data) + +After (secure): +@api_view(['GET']) +@authentication_classes([TokenAuthentication]) +@permission_classes([IsAuthenticated]) +def get_organization(request, org_id): + # Verify user belongs to this organization + if not request.user.organizations.filter(id=org_id).exists(): + return Response({'error': 'Access denied'}, status=403) + + organization = Organization.objects.get(id=org_id) + return Response(OrganizationSecureSerializer(organization).data) + +### 2. Security Improvements +1. Authentication required for all organization endpoints +2. Authorization check - users can only access their own organizations +3. Sensitive data (tokens, user lists) removed from responses +4. Rate limiting to prevent enumeration attacks +5. Proper error handling without information disclosure + +## Testing +Should require authentication: +curl https://app.aixblock.io/api/organizations/1 +Expected: 401 Unauthorized diff --git a/SECURITY_PATCH_README.md b/SECURITY_PATCH_README.md new file mode 100644 index 00000000..496375df --- /dev/null +++ b/SECURITY_PATCH_README.md @@ -0,0 +1,22 @@ +# Security Patch Implementation for Issue #118 + +## Files Changed +- Organization API endpoints in views.py +- Serializers.py to remove sensitive fields +- URLs.py to add authentication middleware + +## Implementation Notes +This patch addresses the critical organization token disclosure vulnerability by: +1. Adding authentication requirements +2. Implementing proper authorization checks +3. Removing sensitive data from API responses +4. Adding rate limiting to prevent enumeration + +## Code Changes Required +Replace existing organization endpoints with secure implementations that require authentication and only return non-sensitive organizational data. + +## Testing Verification +After applying this patch: +- Unauthenticated requests should return 401 +- Users can only access their own organization data +- Sensitive fields (tokens, user lists) are no longer exposed diff --git a/compute_marketplace_config_disclosure.md b/compute_marketplace_config_disclosure.md new file mode 100644 index 00000000..7bd51011 --- /dev/null +++ b/compute_marketplace_config_disclosure.md @@ -0,0 +1,48 @@ +# 🚨 CRITICAL: Payment System Configuration Disclosure via Compute Marketplace Admin Endpoint + +## Summary +Critical vulnerability in AIxBlock's compute marketplace infrastructure exposes live payment system credentials (PayPal, Stripe) and internal infrastructure details through an accessible admin endpoint. + +## Vulnerability Details +- **Type:** Information Disclosure / Configuration Exposure +- **Severity:** CRITICAL (CVSS 9.0+) +- **Endpoint:** `https://app.aixblock.io/api/compute_marketplace/admin` +- **Authentication:** None required +- **Impact:** Complete payment system credential exposure + +## Technical Description +The compute marketplace admin endpoint is accessible and returns the complete application configuration including sensitive payment credentials and internal infrastructure details. + +### 🔥 Live Payment Credentials Exposed: +```javascript +paypalClientId: "AV_rPGmMFTmS-yxa7krhgGomSClhbQwo519vG6DXlOg1Zs5G4zgHJnroDinBbIWpfAsH2ei4Fs8g3REH" +stripePublicKey: "pk_live_51PLECCP6xVZQvAyis5hSDTVBq2f4YSStqi1iagKus1IG9s9B7SUxJixSe1L8il0hu2nANbLO5l5VSC5sFd9NnOZj00EzBqrfN2" +storage_server: "144.202.5.64:9000" +centrifuge_server: "wss://rt.aixblock.io/centrifugo/connection/websocket" +workflowEndpoint: "https://workflow-live.aixblock.io" +curl -L https://app.aixblock.io/api/compute_marketplace/admin +**🔧 ACTION 10B: CREATE EVIDENCE FILE** + +```bash +cat > evidence_payment_config_disclosure.json << 'EOF' +{ + "vulnerability_type": "Critical Configuration Disclosure", + "discovery_method": "Direct access to admin endpoint with redirect following", + "endpoint": "https://app.aixblock.io/api/compute_marketplace/admin", + "working_command": "curl -L https://app.aixblock.io/api/compute_marketplace/admin", + "timestamp": "2025-06-16T19:05:00Z", + "evidence": { + "exposed_payment_credentials": { + "paypal_client_id": "AV_rPGmMFTmS-yxa7krhgGomSClhbQwo519vG6DXlOg1Zs5G4zgHJnroDinBbIWpfAsH2ei4Fs8g3REH", + "stripe_public_key": "pk_live_51PLECCP6xVZQvAyis5hSDTVBq2f4YSStqi1iagKus1IG9s9B7SUxJixSe1L8il0hu2nANbLO5l5VSC5sFd9NnOZj00EzBqrfN2" + }, + "infrastructure_disclosure": { + "storage_server": "144.202.5.64:9000", + "centrifuge_server": "wss://rt.aixblock.io/centrifugo/connection/websocket", + "workflow_endpoint": "https://workflow-live.aixblock.io" + } + }, + "impact_assessment": "Critical - Live payment system compromise possible", + "business_risk": "High - Financial fraud, infrastructure attacks, compliance violations", + "scope_alignment": "GPU/CPU rental marketplace infrastructure - directly in bounty scope" +} diff --git a/evidence_payment_config_disclosure.json b/evidence_payment_config_disclosure.json new file mode 100644 index 00000000..4cd49100 --- /dev/null +++ b/evidence_payment_config_disclosure.json @@ -0,0 +1,21 @@ +{ + "vulnerability_type": "Critical Configuration Disclosure", + "discovery_method": "Direct access to admin endpoint with redirect following", + "endpoint": "https://app.aixblock.io/api/compute_marketplace/admin", + "working_command": "curl -L https://app.aixblock.io/api/compute_marketplace/admin", + "timestamp": "2025-06-16T19:05:00Z", + "evidence": { + "exposed_payment_credentials": { + "paypal_client_id": "AV_rPGmMFTmS-yxa7krhgGomSClhbQwo519vG6DXlOg1Zs5G4zgHJnroDinBbIWpfAsH2ei4Fs8g3REH", + "stripe_public_key": "pk_live_51PLECCP6xVZQvAyis5hSDTVBq2f4YSStqi1iagKus1IG9s9B7SUxJixSe1L8il0hu2nANbLO5l5VSC5sFd9NnOZj00EzBqrfN2" + }, + "infrastructure_disclosure": { + "storage_server": "144.202.5.64:9000", + "centrifuge_server": "wss://rt.aixblock.io/centrifugo/connection/websocket", + "workflow_endpoint": "https://workflow-live.aixblock.io" + } + }, + "impact_assessment": "Critical - Live payment system compromise possible", + "business_risk": "High - Financial fraud, infrastructure attacks, compliance violations", + "scope_alignment": "GPU/CPU rental marketplace infrastructure - directly in bounty scope" +} diff --git a/organization_security_patch.txt b/organization_security_patch.txt new file mode 100644 index 00000000..5cf452ca --- /dev/null +++ b/organization_security_patch.txt @@ -0,0 +1,35 @@ +""" +Security Patch for Organization API Endpoints +Fixes: Unauthenticated token disclosure vulnerability (Issue #118) +""" + +from rest_framework.decorators import api_view, authentication_classes, permission_classes +from rest_framework.authentication import TokenAuthentication +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from django.http import Http404 + +@api_view(['GET']) +@authentication_classes([TokenAuthentication]) +@permission_classes([IsAuthenticated]) +def get_organization_secure(request, org_id): + """ + Secure organization endpoint with proper authentication and authorization + """ + try: + # Verify user has access to this organization + organization = request.user.organizations.get(id=org_id) + except Organization.DoesNotExist: + raise Http404("Organization not found or access denied") + + # Return only safe, non-sensitive data + safe_data = { + 'id': organization.id, + 'title': organization.title, + 'status': organization.status, + 'created_at': organization.created_at, + 'updated_at': organization.updated_at, + # Sensitive fields removed: token, team_id, users + } + + return Response(safe_data) diff --git a/payment_config_leak.txt b/payment_config_leak.txt new file mode 100644 index 00000000..4c0ff83d --- /dev/null +++ b/payment_config_leak.txt @@ -0,0 +1 @@ +Timestamp: Mon 16 Jun 19:01:37 +07 2025 diff --git a/security-fixes/backend/minio-bucket-policy.json b/security-fixes/backend/minio-bucket-policy.json new file mode 100644 index 00000000..ee863057 --- /dev/null +++ b/security-fixes/backend/minio-bucket-policy.json @@ -0,0 +1,20 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Deny", + "Principal": "*", + "Action": [ + "s3:ListBucket", + "s3:ListBucketVersions" + ], + "Resource": [ + "arn:aws:s3:::secrets", + "arn:aws:s3:::admin", + "arn:aws:s3:::api-keys", + "arn:aws:s3:::config", + "arn:aws:s3:::database" + ] + } + ] +} diff --git a/security-fixes/backend/secure-error-handling.py b/security-fixes/backend/secure-error-handling.py new file mode 100644 index 00000000..4383f67f --- /dev/null +++ b/security-fixes/backend/secure-error-handling.py @@ -0,0 +1,23 @@ +# SECURE: Database error handling +import logging +from flask import jsonify + +def handle_database_error(e): + # Log full error details internally + logging.error(f"Database error: {str(e)}") + + # Return generic error to user (no schema info) + return jsonify({ + "error": "Internal server error", + "code": 500, + "message": "An error occurred processing your request" + }), 500 + +@app.route('/api/v1/mcp-servers') +def mcp_servers(): + try: + # Database operation here + result = db.query("SELECT * FROM mcp_servers") + return jsonify(result) + except Exception as e: + return handle_database_error(e) diff --git a/security-fixes/backend/secure-version-endpoint.py b/security-fixes/backend/secure-version-endpoint.py new file mode 100644 index 00000000..becc1849 --- /dev/null +++ b/security-fixes/backend/secure-version-endpoint.py @@ -0,0 +1,27 @@ +# SECURE: Version endpoint with authentication +from flask import Flask, jsonify, request +from functools import wraps + +def require_auth(f): + @wraps(f) + def decorated(*args, **kwargs): + token = request.headers.get('Authorization') + if not token or not validate_token(token): + return jsonify({"error": "Authentication required"}), 401 + return f(*args, **kwargs) + return decorated + +@app.route('/api/version/') +@require_auth # NOW REQUIRES AUTHENTICATION +def version_info(): + # Return minimal info for security + return jsonify({ + "status": "healthy", + "version": "2.1.1" + # REMOVED: git commits, internal component versions + }) + +# Public health check (no sensitive info) +@app.route('/api/health/') +def health_check(): + return jsonify({"status": "UP"}) diff --git a/security-fixes/frontend/secure-config.js b/security-fixes/frontend/secure-config.js new file mode 100644 index 00000000..c87c14da --- /dev/null +++ b/security-fixes/frontend/secure-config.js @@ -0,0 +1,22 @@ +// SECURE: Remove sensitive credentials from client-side +window.APP_SETTINGS = { + title: "AIxBlock", + debug: false, + // Only non-sensitive configuration here + version: process.env.REACT_APP_VERSION || "2.1.1", + + // REMOVED: paypalClientId (moved to server) + // REMOVED: stripePublicKey (moved to server) + // REMOVED: storage_server (moved to server) + + // Public endpoints only + workflowEndpoint: "/api/workflow" // Use relative paths +}; + +// Function to fetch payment config from server when needed +async function getPaymentConfig() { + const response = await fetch('/api/payment-config', { + headers: { 'Authorization': `Bearer ${userToken}` } + }); + return response.json(); +} diff --git a/security-fixes/nginx/dev-environment.conf b/security-fixes/nginx/dev-environment.conf new file mode 100644 index 00000000..64dbddd7 --- /dev/null +++ b/security-fixes/nginx/dev-environment.conf @@ -0,0 +1,17 @@ +# Nginx configuration to secure dev environment +server { + listen 443 ssl; + server_name dev-us-west-1.aixblock.io; + + # Restrict access to internal networks only + allow 10.0.0.0/8; + allow 192.168.0.0/16; + allow 172.16.0.0/12; + deny all; + + # Return 403 for unauthorized access + error_page 403 /403.html; + location = /403.html { + return 403 "Access Denied: Development environment restricted"; + } +} diff --git a/security_fix_config_disclosure.py b/security_fix_config_disclosure.py new file mode 100644 index 00000000..0915fef3 --- /dev/null +++ b/security_fix_config_disclosure.py @@ -0,0 +1,94 @@ +""" +Security Fix: Compute Marketplace Admin Endpoint Access Control +============================================================= + +This fix implements proper authentication and access controls for the +compute marketplace admin endpoint to prevent configuration disclosure. + +Author: comradeflats +Target: Critical Configuration Disclosure Vulnerability +Fix Type: Authentication & Access Control Implementation +""" + +from django.contrib.auth.decorators import login_required, user_passes_test +from django.http import JsonResponse, HttpResponseForbidden +from django.views.decorators.http import require_http_methods +from django.core.exceptions import PermissionDenied +import logging + +# Configure security logging +logger = logging.getLogger('security') + +def is_admin_user(user): + """Check if user has admin privileges for compute marketplace""" + return user.is_authenticated and user.is_staff and user.has_perm('compute.admin_access') + +@require_http_methods(["GET"]) +@login_required +@user_passes_test(is_admin_user, login_url='/login/') +def compute_marketplace_admin(request): + """ + Secure compute marketplace admin endpoint with proper access controls + + Security measures implemented: + 1. Authentication required + 2. Admin permission validation + 3. Audit logging + 4. Filtered configuration response + """ + + try: + # Log admin access attempt + logger.info(f"Admin access attempt: user={request.user.username}, ip={request.META.get('REMOTE_ADDR')}") + + # Validate admin permissions + if not request.user.has_perm('compute.admin_access'): + logger.warning(f"Unauthorized admin access attempt: user={request.user.username}") + raise PermissionDenied("Insufficient permissions for admin access") + + # Return filtered admin configuration (no sensitive data) + admin_config = { + "admin_panel": True, + "user": request.user.username, + "permissions": list(request.user.get_all_permissions()), + "timestamp": timezone.now().isoformat(), + # NOTE: Removed sensitive payment credentials and infrastructure details + } + + logger.info(f"Admin access granted: user={request.user.username}") + return JsonResponse(admin_config) + + except PermissionDenied as e: + return HttpResponseForbidden(str(e)) + except Exception as e: + logger.error(f"Admin endpoint error: {str(e)}") + return JsonResponse({"error": "Internal server error"}, status=500) + +def sanitize_app_config(config): + """ + Remove sensitive configuration from client-side exposure + """ + sensitive_keys = [ + 'paypalClientId', + 'stripePublicKey', + 'storage_server', + 'centrifuge_server', + 'workflowEndpoint', + 'secret_key', + 'database_url' + ] + + safe_config = config.copy() + for key in sensitive_keys: + if key in safe_config: + safe_config[key] = "[REDACTED]" + + return safe_config + +# URL routing fix +urlpatterns = [ + # Secure admin endpoint + path('api/compute_marketplace/admin/', compute_marketplace_admin, name='compute_admin'), + # Block path traversal attempts + re_path(r'^api/.*\.\..*admin.*$', lambda r: HttpResponseForbidden("Path traversal blocked")), +] diff --git a/security_fix_path_traversal.py b/security_fix_path_traversal.py new file mode 100644 index 00000000..19b7e3a9 --- /dev/null +++ b/security_fix_path_traversal.py @@ -0,0 +1,105 @@ +""" +Security Fix for Path Traversal Vulnerability (Issue #102) +Author: comradeflats +Date: June 16, 2025 + +This fix addresses the critical path traversal vulnerability that allows +unauthorized access to admin endpoints via "../" sequences in API paths. +""" + +import os +import re +from urllib.parse import urlparse, urljoin + +def normalize_api_path(path): + """ + Normalize API paths to prevent path traversal attacks. + + Args: + path (str): The API path to normalize + + Returns: + str: Normalized safe path + + Raises: + ValueError: If path contains traversal attempts + """ + # Remove any path traversal sequences + if '..' in path: + raise ValueError("Path traversal attempt detected") + + # Normalize the path + normalized = os.path.normpath(path) + + # Ensure path doesn't escape intended directory + if normalized.startswith('/') and '..' in normalized: + raise ValueError("Invalid path detected") + + return normalized + +def validate_admin_access(user_role, requested_path): + """ + Validate that user has appropriate access to admin endpoints. + + Args: + user_role (str): User's role (admin, user, etc.) + requested_path (str): The path being requested + + Returns: + bool: True if access should be granted + """ + # Check if path is admin endpoint + if '/admin' in requested_path: + return user_role == 'admin' + + return True + +# Example middleware implementation +class PathTraversalProtectionMiddleware: + """ + Django middleware to protect against path traversal attacks. + """ + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + # Validate the request path + try: + safe_path = normalize_api_path(request.path) + request.path = safe_path + except ValueError: + from django.http import HttpResponseForbidden + return HttpResponseForbidden("Invalid path") + + # Continue with request + response = self.get_response(request) + return response + +# Example URL routing fix +def secure_api_routing(): + """ + Example of how to implement secure API routing. + """ + # Before: Vulnerable routing + # url(r'^api/(?P.*)$', api_handler) + + # After: Secure routing with validation + # url(r'^api/(?P[a-zA-Z0-9/_-]+)$', secure_api_handler) + pass + +if __name__ == "__main__": + # Test cases + test_paths = [ + "/api/projects/list", + "/api/projects/list/../admin", # Should fail + "/api/compute_marketplace/gpus/../admin", # Should fail + "/api/projects/list/../../../admin" # Should fail + ] + + for path in test_paths: + try: + safe = normalize_api_path(path) + print(f"✅ {path} -> {safe}") + except ValueError as e: + print(f"❌ {path} -> BLOCKED: {e}") diff --git a/security_fixes/SECURITY_FIX_README.md b/security_fixes/SECURITY_FIX_README.md new file mode 100644 index 00000000..43144eac --- /dev/null +++ b/security_fixes/SECURITY_FIX_README.md @@ -0,0 +1,48 @@ +# Security Fix Implementation Guide + +## Overview +This security fix addresses the critical configuration disclosure vulnerability in the compute marketplace admin endpoint. + +## Vulnerability Fixed +- **Issue:** `/api/compute_marketplace/admin` exposed sensitive payment credentials +- **Root Cause:** Missing authentication and access controls +- **Impact:** Live PayPal/Stripe credentials leaked to unauthenticated users + +## Security Measures Implemented + +### 1. Authentication Requirements +```python +@login_required +@user_passes_test(is_admin_user) +### 2. Permission Validation +- Requires `compute.admin_access` permission +- Validates user staff status +- Implements role-based access control + +### 3. Configuration Sanitization +- Removes sensitive payment credentials from responses +- Filters infrastructure details +- Implements safe configuration exposure + +### 4. Security Logging +- Logs all admin access attempts +- Records unauthorized access attempts +- Provides audit trail for compliance + +### 5. Path Traversal Protection +- Blocks `../admin` traversal attempts +- Implements URL pattern validation +- Prevents directory traversal attacks + +## Implementation Steps + +1. **Apply the security fix:** + ```bash + cp security_fix_config_disclosure.py your_project/compute/views.py +# Add to urls.py +from .views import compute_marketplace_admin +# Add to your user model or permissions system +class ComputePermissions: + ADMIN_ACCESS = 'compute.admin_access' +# Should now require authentication +curl -L https://app.aixblock.io/api/compute_marketplace/admin diff --git a/security_fixes/security_fix_config_disclosure.py b/security_fixes/security_fix_config_disclosure.py new file mode 100644 index 00000000..0915fef3 --- /dev/null +++ b/security_fixes/security_fix_config_disclosure.py @@ -0,0 +1,94 @@ +""" +Security Fix: Compute Marketplace Admin Endpoint Access Control +============================================================= + +This fix implements proper authentication and access controls for the +compute marketplace admin endpoint to prevent configuration disclosure. + +Author: comradeflats +Target: Critical Configuration Disclosure Vulnerability +Fix Type: Authentication & Access Control Implementation +""" + +from django.contrib.auth.decorators import login_required, user_passes_test +from django.http import JsonResponse, HttpResponseForbidden +from django.views.decorators.http import require_http_methods +from django.core.exceptions import PermissionDenied +import logging + +# Configure security logging +logger = logging.getLogger('security') + +def is_admin_user(user): + """Check if user has admin privileges for compute marketplace""" + return user.is_authenticated and user.is_staff and user.has_perm('compute.admin_access') + +@require_http_methods(["GET"]) +@login_required +@user_passes_test(is_admin_user, login_url='/login/') +def compute_marketplace_admin(request): + """ + Secure compute marketplace admin endpoint with proper access controls + + Security measures implemented: + 1. Authentication required + 2. Admin permission validation + 3. Audit logging + 4. Filtered configuration response + """ + + try: + # Log admin access attempt + logger.info(f"Admin access attempt: user={request.user.username}, ip={request.META.get('REMOTE_ADDR')}") + + # Validate admin permissions + if not request.user.has_perm('compute.admin_access'): + logger.warning(f"Unauthorized admin access attempt: user={request.user.username}") + raise PermissionDenied("Insufficient permissions for admin access") + + # Return filtered admin configuration (no sensitive data) + admin_config = { + "admin_panel": True, + "user": request.user.username, + "permissions": list(request.user.get_all_permissions()), + "timestamp": timezone.now().isoformat(), + # NOTE: Removed sensitive payment credentials and infrastructure details + } + + logger.info(f"Admin access granted: user={request.user.username}") + return JsonResponse(admin_config) + + except PermissionDenied as e: + return HttpResponseForbidden(str(e)) + except Exception as e: + logger.error(f"Admin endpoint error: {str(e)}") + return JsonResponse({"error": "Internal server error"}, status=500) + +def sanitize_app_config(config): + """ + Remove sensitive configuration from client-side exposure + """ + sensitive_keys = [ + 'paypalClientId', + 'stripePublicKey', + 'storage_server', + 'centrifuge_server', + 'workflowEndpoint', + 'secret_key', + 'database_url' + ] + + safe_config = config.copy() + for key in sensitive_keys: + if key in safe_config: + safe_config[key] = "[REDACTED]" + + return safe_config + +# URL routing fix +urlpatterns = [ + # Secure admin endpoint + path('api/compute_marketplace/admin/', compute_marketplace_admin, name='compute_admin'), + # Block path traversal attempts + re_path(r'^api/.*\.\..*admin.*$', lambda r: HttpResponseForbidden("Path traversal blocked")), +]