File size: 10,824 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
"""

Secure API endpoints with integrated security measures.

"""

from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from typing import Dict, List, Optional
import asyncio
from datetime import datetime

from .security import (
    file_validator, secure_storage, audit_logger, 
    SecurityEvent, FileValidationResult
)
from .auth import get_current_user
from .models import User

router = APIRouter()
security = HTTPBearer()

async def get_client_ip(request: Request) -> str:
    """Extract client IP from request."""
    forwarded_for = request.headers.get('X-Forwarded-For')
    if forwarded_for:
        return forwarded_for.split(',')[0].strip()
    
    real_ip = request.headers.get('X-Real-IP')
    if real_ip:
        return real_ip
    
    return request.client.host if request.client else 'unknown'

@router.post("/secure-upload")
async def secure_file_upload(

    request: Request,

    file: UploadFile = File(...),

    credentials: HTTPAuthorizationCredentials = Depends(security)

) -> Dict:
    """

    Secure file upload endpoint with comprehensive validation.

    """
    # Get current user
    user = await get_current_user(credentials.credentials)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid authentication")
    
    client_ip = await get_client_ip(request)
    
    try:
        # Read file content
        file_content = await file.read()
        
        # Validate file security
        validation_result = await file_validator.validate_file(
            file_content, file.filename, user.id
        )
        
        # Log upload attempt
        audit_logger.log_file_upload_event(
            user.id, client_ip, file.filename, validation_result
        )
        
        # Check if file passed validation
        if not validation_result.is_valid:
            raise HTTPException(
                status_code=400,
                detail={
                    "error": "File validation failed",
                    "threats": validation_result.threats_detected,
                    "warnings": validation_result.warnings
                }
            )
        
        # Store file securely
        stored_path = secure_storage.store_file(
            user.id, file.filename, file_content
        )
        
        # Log successful upload
        audit_logger.log_event(SecurityEvent(
            timestamp=datetime.utcnow(),
            event_type='file_upload_success',
            user_id=user.id,
            ip_address=client_ip,
            severity='LOW',
            details={
                'filename': file.filename,
                'stored_path': stored_path,
                'file_size': validation_result.size_bytes,
                'file_type': validation_result.file_type,
                'file_hash': validation_result.hash_sha256
            }
        ))
        
        return {
            "success": True,
            "file_id": stored_path,
            "filename": file.filename,
            "size": validation_result.size_bytes,
            "type": validation_result.file_type,
            "hash": validation_result.hash_sha256,
            "warnings": validation_result.warnings
        }
        
    except HTTPException:
        raise
    except Exception as e:
        # Log upload error
        audit_logger.log_event(SecurityEvent(
            timestamp=datetime.utcnow(),
            event_type='file_upload_error',
            user_id=user.id,
            ip_address=client_ip,
            severity='HIGH',
            details={
                'filename': file.filename,
                'error': str(e)
            }
        ))
        
        raise HTTPException(
            status_code=500,
            detail=f"File upload failed: {str(e)}"
        )

@router.get("/secure-download/{file_id}")
async def secure_file_download(

    file_id: str,

    request: Request,

    credentials: HTTPAuthorizationCredentials = Depends(security)

):
    """

    Secure file download with access control validation.

    """
    # Get current user
    user = await get_current_user(credentials.credentials)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid authentication")
    
    client_ip = await get_client_ip(request)
    
    try:
        # Retrieve file with access control
        file_content = secure_storage.get_file(user.id, file_id)
        
        # Log download
        audit_logger.log_event(SecurityEvent(
            timestamp=datetime.utcnow(),
            event_type='file_download',
            user_id=user.id,
            ip_address=client_ip,
            severity='LOW',
            details={
                'file_id': file_id,
                'file_size': len(file_content)
            }
        ))
        
        return {
            "success": True,
            "content": file_content.hex(),  # Return as hex for JSON compatibility
            "size": len(file_content)
        }
        
    except PermissionError:
        audit_logger.log_event(SecurityEvent(
            timestamp=datetime.utcnow(),
            event_type='unauthorized_file_access',
            user_id=user.id,
            ip_address=client_ip,
            severity='HIGH',
            details={'file_id': file_id}
        ))
        
        raise HTTPException(
            status_code=403,
            detail="Access denied to requested file"
        )
    
    except FileNotFoundError:
        raise HTTPException(
            status_code=404,
            detail="File not found"
        )
    
    except Exception as e:
        audit_logger.log_event(SecurityEvent(
            timestamp=datetime.utcnow(),
            event_type='file_download_error',
            user_id=user.id,
            ip_address=client_ip,
            severity='MEDIUM',
            details={
                'file_id': file_id,
                'error': str(e)
            }
        ))
        
        raise HTTPException(
            status_code=500,
            detail=f"File download failed: {str(e)}"
        )

@router.delete("/secure-delete/{file_id}")
async def secure_file_delete(

    file_id: str,

    request: Request,

    credentials: HTTPAuthorizationCredentials = Depends(security)

) -> Dict:
    """

    Secure file deletion with access control validation.

    """
    # Get current user
    user = await get_current_user(credentials.credentials)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid authentication")
    
    client_ip = await get_client_ip(request)
    
    try:
        # Delete file with access control
        deleted = secure_storage.delete_file(user.id, file_id)
        
        if deleted:
            # Log successful deletion
            audit_logger.log_event(SecurityEvent(
                timestamp=datetime.utcnow(),
                event_type='file_deletion',
                user_id=user.id,
                ip_address=client_ip,
                severity='LOW',
                details={'file_id': file_id}
            ))
            
            return {"success": True, "message": "File deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="File not found")
        
    except PermissionError:
        audit_logger.log_event(SecurityEvent(
            timestamp=datetime.utcnow(),
            event_type='unauthorized_file_deletion',
            user_id=user.id,
            ip_address=client_ip,
            severity='HIGH',
            details={'file_id': file_id}
        ))
        
        raise HTTPException(
            status_code=403,
            detail="Access denied to requested file"
        )
    
    except Exception as e:
        audit_logger.log_event(SecurityEvent(
            timestamp=datetime.utcnow(),
            event_type='file_deletion_error',
            user_id=user.id,
            ip_address=client_ip,
            severity='MEDIUM',
            details={
                'file_id': file_id,
                'error': str(e)
            }
        ))
        
        raise HTTPException(
            status_code=500,
            detail=f"File deletion failed: {str(e)}"
        )

@router.get("/security-status")
async def get_security_status(

    request: Request,

    credentials: HTTPAuthorizationCredentials = Depends(security)

) -> Dict:
    """

    Get security status and recent events for the current user.

    """
    # Get current user
    user = await get_current_user(credentials.credentials)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid authentication")
    
    client_ip = await get_client_ip(request)
    
    # This would typically read from the audit log
    # For now, return basic security status
    return {
        "user_id": user.id,
        "ip_address": client_ip,
        "security_level": "HIGH",
        "last_login": datetime.utcnow().isoformat(),
        "active_sessions": 1,
        "recent_uploads": 0,  # Would be calculated from audit log
        "security_alerts": 0   # Would be calculated from audit log
    }

@router.post("/validate-input")
async def validate_user_input(

    request: Request,

    data: Dict,

    credentials: HTTPAuthorizationCredentials = Depends(security)

) -> Dict:
    """

    Validate user input for security threats.

    """
    from .security import sql_prevention
    
    # Get current user
    user = await get_current_user(credentials.credentials)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid authentication")
    
    client_ip = await get_client_ip(request)
    
    validation_results = {}
    overall_safe = True
    
    # Validate each field in the input data
    for field_name, field_value in data.items():
        if isinstance(field_value, str):
            is_safe, threats = sql_prevention.validate_input(field_value, field_name)
            validation_results[field_name] = {
                'is_safe': is_safe,
                'threats': threats
            }
            
            if not is_safe:
                overall_safe = False
                
                # Log security threat
                audit_logger.log_sql_injection_attempt(
                    user.id, client_ip, field_name, threats
                )
    
    return {
        'overall_safe': overall_safe,
        'field_results': validation_results,
        'timestamp': datetime.utcnow().isoformat()
    }