Merge pull request #62 from scribe-security/fix-auth-issues
Browse files- api/evidence.py +46 -8
- api/syslog.py +91 -12
- storage.py +21 -1
- templates/logs.html +43 -0
- web/products.py +4 -3
api/evidence.py
CHANGED
|
@@ -14,7 +14,7 @@ from werkzeug.utils import secure_filename
|
|
| 14 |
from sqlalchemy import func, cast, String, Text, BigInteger, Numeric
|
| 15 |
from models import Attestation, UploadSession, User, Webhook, PolicyResult, Product
|
| 16 |
from app import db
|
| 17 |
-
from auth import jwt_required_with_logging, get_current_user_safe
|
| 18 |
from api.badges import is_admin_user
|
| 19 |
from storage import get_storage_backend
|
| 20 |
from logging_utils import log_event
|
|
@@ -236,11 +236,15 @@ def create_attestation():
|
|
| 236 |
|
| 237 |
except Exception as e:
|
| 238 |
db.session.rollback()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
log_event(
|
| 240 |
severity=3,
|
| 241 |
message=f"Failed to create attestation: {str(e)}",
|
| 242 |
event_type="attestation_error",
|
| 243 |
-
user_id=
|
| 244 |
)
|
| 245 |
return jsonify({'error': str(e)}), 500
|
| 246 |
|
|
@@ -355,11 +359,15 @@ def list_evidence():
|
|
| 355 |
})
|
| 356 |
|
| 357 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
log_event(
|
| 359 |
severity=3,
|
| 360 |
message=f"Failed to list evidences: {str(e)}",
|
| 361 |
event_type="list_error",
|
| 362 |
-
user_id=
|
| 363 |
)
|
| 364 |
return jsonify({'error': str(e)}), 500
|
| 365 |
|
|
@@ -396,11 +404,15 @@ def get_evidence_details(file_id):
|
|
| 396 |
return jsonify(data)
|
| 397 |
|
| 398 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
log_event(
|
| 400 |
severity=3,
|
| 401 |
message=f"Failed to get evidence details for {file_id}: {str(e)}",
|
| 402 |
event_type="evidence_details_error",
|
| 403 |
-
user_id=
|
| 404 |
)
|
| 405 |
return jsonify({'error': str(e)}), 500
|
| 406 |
|
|
@@ -447,17 +459,23 @@ def delete_evidence(file_id):
|
|
| 447 |
|
| 448 |
except Exception as e:
|
| 449 |
db.session.rollback()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
log_event(
|
| 451 |
severity=3,
|
| 452 |
message=f"Failed to delete evidence {file_id}: {str(e)}",
|
| 453 |
event_type="delete_error",
|
| 454 |
-
user_id=
|
| 455 |
)
|
| 456 |
return jsonify({'error': str(e)}), 500
|
| 457 |
|
| 458 |
@evidence_bp.route('/evidence/upload/<int:file_id>', methods=['PUT'])
|
| 459 |
def upload_file(file_id):
|
| 460 |
-
"""Handle file upload for local storage
|
|
|
|
|
|
|
| 461 |
try:
|
| 462 |
# Get upload session to verify the upload
|
| 463 |
upload_session = UploadSession.query.filter_by(session_id=str(file_id)).first()
|
|
@@ -482,6 +500,18 @@ def upload_file(file_id):
|
|
| 482 |
if hasattr(storage, 'storage_path'):
|
| 483 |
full_path = os.path.join(storage.storage_path, local_path)
|
| 484 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
# Ensure directory exists
|
| 486 |
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
| 487 |
|
|
@@ -669,11 +699,15 @@ def finish_attestation():
|
|
| 669 |
|
| 670 |
except Exception as e:
|
| 671 |
db.session.rollback()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 672 |
log_event(
|
| 673 |
severity=3,
|
| 674 |
message=f"Failed to finish attestation: {str(e)}",
|
| 675 |
event_type="finish_attestation_error",
|
| 676 |
-
user_id=
|
| 677 |
)
|
| 678 |
return jsonify({'error': str(e)}), 500
|
| 679 |
"""
|
|
@@ -904,11 +938,15 @@ def policy_results_csv():
|
|
| 904 |
return response
|
| 905 |
|
| 906 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 907 |
log_event(
|
| 908 |
severity=3,
|
| 909 |
message=f"Failed to generate policy results CSV: {str(e)}",
|
| 910 |
event_type="policy_results_csv_error",
|
| 911 |
-
user_id=
|
| 912 |
)
|
| 913 |
return jsonify({'error': str(e)}), 500
|
| 914 |
|
|
|
|
| 14 |
from sqlalchemy import func, cast, String, Text, BigInteger, Numeric
|
| 15 |
from models import Attestation, UploadSession, User, Webhook, PolicyResult, Product
|
| 16 |
from app import db
|
| 17 |
+
from auth import jwt_required_with_logging, optional_jwt_with_logging, get_current_user_safe
|
| 18 |
from api.badges import is_admin_user
|
| 19 |
from storage import get_storage_backend
|
| 20 |
from logging_utils import log_event
|
|
|
|
| 236 |
|
| 237 |
except Exception as e:
|
| 238 |
db.session.rollback()
|
| 239 |
+
try:
|
| 240 |
+
user_id = int(get_jwt_identity())
|
| 241 |
+
except:
|
| 242 |
+
user_id = None
|
| 243 |
log_event(
|
| 244 |
severity=3,
|
| 245 |
message=f"Failed to create attestation: {str(e)}",
|
| 246 |
event_type="attestation_error",
|
| 247 |
+
user_id=user_id
|
| 248 |
)
|
| 249 |
return jsonify({'error': str(e)}), 500
|
| 250 |
|
|
|
|
| 359 |
})
|
| 360 |
|
| 361 |
except Exception as e:
|
| 362 |
+
try:
|
| 363 |
+
user_id = int(get_jwt_identity())
|
| 364 |
+
except:
|
| 365 |
+
user_id = None
|
| 366 |
log_event(
|
| 367 |
severity=3,
|
| 368 |
message=f"Failed to list evidences: {str(e)}",
|
| 369 |
event_type="list_error",
|
| 370 |
+
user_id=user_id
|
| 371 |
)
|
| 372 |
return jsonify({'error': str(e)}), 500
|
| 373 |
|
|
|
|
| 404 |
return jsonify(data)
|
| 405 |
|
| 406 |
except Exception as e:
|
| 407 |
+
try:
|
| 408 |
+
user_id = int(get_jwt_identity())
|
| 409 |
+
except:
|
| 410 |
+
user_id = None
|
| 411 |
log_event(
|
| 412 |
severity=3,
|
| 413 |
message=f"Failed to get evidence details for {file_id}: {str(e)}",
|
| 414 |
event_type="evidence_details_error",
|
| 415 |
+
user_id=user_id
|
| 416 |
)
|
| 417 |
return jsonify({'error': str(e)}), 500
|
| 418 |
|
|
|
|
| 459 |
|
| 460 |
except Exception as e:
|
| 461 |
db.session.rollback()
|
| 462 |
+
try:
|
| 463 |
+
user_id = int(get_jwt_identity())
|
| 464 |
+
except:
|
| 465 |
+
user_id = None
|
| 466 |
log_event(
|
| 467 |
severity=3,
|
| 468 |
message=f"Failed to delete evidence {file_id}: {str(e)}",
|
| 469 |
event_type="delete_error",
|
| 470 |
+
user_id=user_id
|
| 471 |
)
|
| 472 |
return jsonify({'error': str(e)}), 500
|
| 473 |
|
| 474 |
@evidence_bp.route('/evidence/upload/<int:file_id>', methods=['PUT'])
|
| 475 |
def upload_file(file_id):
|
| 476 |
+
"""Handle file upload for local storage - uses file_id as authentication token
|
| 477 |
+
Note: This endpoint doesn't require JWT auth because it's called with a presigned URL pattern
|
| 478 |
+
where the file_id itself serves as the upload token"""
|
| 479 |
try:
|
| 480 |
# Get upload session to verify the upload
|
| 481 |
upload_session = UploadSession.query.filter_by(session_id=str(file_id)).first()
|
|
|
|
| 500 |
if hasattr(storage, 'storage_path'):
|
| 501 |
full_path = os.path.join(storage.storage_path, local_path)
|
| 502 |
|
| 503 |
+
# SECURITY: Verify the resolved path is within storage directory
|
| 504 |
+
real_storage_path = os.path.realpath(storage.storage_path)
|
| 505 |
+
real_full_path = os.path.realpath(full_path)
|
| 506 |
+
if not real_full_path.startswith(real_storage_path):
|
| 507 |
+
log_event(
|
| 508 |
+
severity=2,
|
| 509 |
+
message=f"Directory traversal attempt detected in upload: {local_path}",
|
| 510 |
+
event_type="security_traversal_upload",
|
| 511 |
+
user_id=upload_session.user_id
|
| 512 |
+
)
|
| 513 |
+
return jsonify({'error': 'Invalid file path'}), 400
|
| 514 |
+
|
| 515 |
# Ensure directory exists
|
| 516 |
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
| 517 |
|
|
|
|
| 699 |
|
| 700 |
except Exception as e:
|
| 701 |
db.session.rollback()
|
| 702 |
+
try:
|
| 703 |
+
user_id = int(get_jwt_identity())
|
| 704 |
+
except:
|
| 705 |
+
user_id = None
|
| 706 |
log_event(
|
| 707 |
severity=3,
|
| 708 |
message=f"Failed to finish attestation: {str(e)}",
|
| 709 |
event_type="finish_attestation_error",
|
| 710 |
+
user_id=user_id
|
| 711 |
)
|
| 712 |
return jsonify({'error': str(e)}), 500
|
| 713 |
"""
|
|
|
|
| 938 |
return response
|
| 939 |
|
| 940 |
except Exception as e:
|
| 941 |
+
try:
|
| 942 |
+
user_id = int(get_jwt_identity())
|
| 943 |
+
except:
|
| 944 |
+
user_id = None
|
| 945 |
log_event(
|
| 946 |
severity=3,
|
| 947 |
message=f"Failed to generate policy results CSV: {str(e)}",
|
| 948 |
event_type="policy_results_csv_error",
|
| 949 |
+
user_id=user_id
|
| 950 |
)
|
| 951 |
return jsonify({'error': str(e)}), 500
|
| 952 |
|
api/syslog.py
CHANGED
|
@@ -1,16 +1,20 @@
|
|
| 1 |
-
from flask import Blueprint, request, jsonify
|
| 2 |
-
from
|
|
|
|
|
|
|
|
|
|
| 3 |
from app import db
|
| 4 |
-
from auth import
|
| 5 |
from api.badges import is_admin_user
|
| 6 |
from logging_utils import log_event, parse_rfc5424_log
|
| 7 |
|
|
|
|
| 8 |
syslog_bp = Blueprint('syslog', __name__)
|
| 9 |
|
| 10 |
@syslog_bp.route('/syslog', methods=['POST'])
|
| 11 |
-
@
|
| 12 |
def receive_syslog():
|
| 13 |
-
"""Receive RFC 5424 syslog messages"""
|
| 14 |
try:
|
| 15 |
content_type = request.content_type or 'text/plain'
|
| 16 |
|
|
@@ -44,7 +48,7 @@ def receive_syslog():
|
|
| 44 |
msg_id=parsed['msg_id'],
|
| 45 |
structured_data=parsed['structured_data'],
|
| 46 |
message=parsed['message'],
|
| 47 |
-
user_id=
|
| 48 |
source_ip=request.remote_addr,
|
| 49 |
event_type='syslog_received'
|
| 50 |
)
|
|
@@ -58,7 +62,7 @@ def receive_syslog():
|
|
| 58 |
severity=4,
|
| 59 |
message=f"Failed to parse syslog message: {str(e)}",
|
| 60 |
event_type="syslog_parse_error",
|
| 61 |
-
user_id=
|
| 62 |
)
|
| 63 |
|
| 64 |
db.session.commit()
|
|
@@ -91,7 +95,7 @@ def receive_syslog():
|
|
| 91 |
msg_id=parsed['msg_id'],
|
| 92 |
structured_data=parsed['structured_data'],
|
| 93 |
message=parsed['message'],
|
| 94 |
-
user_id=
|
| 95 |
source_ip=request.remote_addr,
|
| 96 |
event_type='syslog_received'
|
| 97 |
)
|
|
@@ -108,21 +112,25 @@ def receive_syslog():
|
|
| 108 |
severity=4,
|
| 109 |
message=f"Failed to process syslog message: {str(e)}",
|
| 110 |
event_type="syslog_error",
|
| 111 |
-
user_id=
|
| 112 |
)
|
| 113 |
return jsonify({'error': 'Failed to process log message'}), 500
|
| 114 |
|
| 115 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
log_event(
|
| 117 |
severity=3,
|
| 118 |
message=f"Syslog endpoint error: {str(e)}",
|
| 119 |
event_type="syslog_endpoint_error",
|
| 120 |
-
user_id=
|
| 121 |
)
|
| 122 |
return jsonify({'error': 'Internal server error'}), 500
|
| 123 |
|
| 124 |
@syslog_bp.route('/logs', methods=['GET'])
|
| 125 |
-
@
|
| 126 |
def get_logs():
|
| 127 |
"""Get system logs with filtering"""
|
| 128 |
try:
|
|
@@ -206,7 +214,7 @@ def get_logs():
|
|
| 206 |
return jsonify({'error': str(e)}), 500
|
| 207 |
|
| 208 |
@syslog_bp.route('/logs/stats', methods=['GET'])
|
| 209 |
-
@
|
| 210 |
def get_log_stats():
|
| 211 |
"""Get log statistics"""
|
| 212 |
try:
|
|
@@ -279,3 +287,74 @@ def get_log_stats():
|
|
| 279 |
user_id=get_current_user_safe().id if get_current_user_safe() else None
|
| 280 |
)
|
| 281 |
return jsonify({'error': str(e)}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Blueprint, request, Response, jsonify
|
| 2 |
+
from flask_jwt_extended import get_jwt_identity
|
| 3 |
+
import csv
|
| 4 |
+
|
| 5 |
+
from models import SystemLog, User
|
| 6 |
from app import db
|
| 7 |
+
from auth import jwt_required_with_logging, get_current_user_safe
|
| 8 |
from api.badges import is_admin_user
|
| 9 |
from logging_utils import log_event, parse_rfc5424_log
|
| 10 |
|
| 11 |
+
|
| 12 |
syslog_bp = Blueprint('syslog', __name__)
|
| 13 |
|
| 14 |
@syslog_bp.route('/syslog', methods=['POST'])
|
| 15 |
+
@jwt_required_with_logging
|
| 16 |
def receive_syslog():
|
| 17 |
+
"""Receive RFC 5424 syslog messages - requires JWT authentication per OpenAPI spec"""
|
| 18 |
try:
|
| 19 |
content_type = request.content_type or 'text/plain'
|
| 20 |
|
|
|
|
| 48 |
msg_id=parsed['msg_id'],
|
| 49 |
structured_data=parsed['structured_data'],
|
| 50 |
message=parsed['message'],
|
| 51 |
+
user_id=int(get_jwt_identity()),
|
| 52 |
source_ip=request.remote_addr,
|
| 53 |
event_type='syslog_received'
|
| 54 |
)
|
|
|
|
| 62 |
severity=4,
|
| 63 |
message=f"Failed to parse syslog message: {str(e)}",
|
| 64 |
event_type="syslog_parse_error",
|
| 65 |
+
user_id=int(get_jwt_identity())
|
| 66 |
)
|
| 67 |
|
| 68 |
db.session.commit()
|
|
|
|
| 95 |
msg_id=parsed['msg_id'],
|
| 96 |
structured_data=parsed['structured_data'],
|
| 97 |
message=parsed['message'],
|
| 98 |
+
user_id=int(get_jwt_identity()),
|
| 99 |
source_ip=request.remote_addr,
|
| 100 |
event_type='syslog_received'
|
| 101 |
)
|
|
|
|
| 112 |
severity=4,
|
| 113 |
message=f"Failed to process syslog message: {str(e)}",
|
| 114 |
event_type="syslog_error",
|
| 115 |
+
user_id=int(get_jwt_identity())
|
| 116 |
)
|
| 117 |
return jsonify({'error': 'Failed to process log message'}), 500
|
| 118 |
|
| 119 |
except Exception as e:
|
| 120 |
+
try:
|
| 121 |
+
user_id = int(get_jwt_identity())
|
| 122 |
+
except:
|
| 123 |
+
user_id = None
|
| 124 |
log_event(
|
| 125 |
severity=3,
|
| 126 |
message=f"Syslog endpoint error: {str(e)}",
|
| 127 |
event_type="syslog_endpoint_error",
|
| 128 |
+
user_id=user_id
|
| 129 |
)
|
| 130 |
return jsonify({'error': 'Internal server error'}), 500
|
| 131 |
|
| 132 |
@syslog_bp.route('/logs', methods=['GET'])
|
| 133 |
+
@jwt_required_with_logging
|
| 134 |
def get_logs():
|
| 135 |
"""Get system logs with filtering"""
|
| 136 |
try:
|
|
|
|
| 214 |
return jsonify({'error': str(e)}), 500
|
| 215 |
|
| 216 |
@syslog_bp.route('/logs/stats', methods=['GET'])
|
| 217 |
+
@jwt_required_with_logging
|
| 218 |
def get_log_stats():
|
| 219 |
"""Get log statistics"""
|
| 220 |
try:
|
|
|
|
| 287 |
user_id=get_current_user_safe().id if get_current_user_safe() else None
|
| 288 |
)
|
| 289 |
return jsonify({'error': str(e)}), 500
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@syslog_bp.route('/logs/csv', methods=['GET'])
|
| 293 |
+
@jwt_required_with_logging
|
| 294 |
+
def download_logs_csv():
|
| 295 |
+
"""Download all filtered logs as CSV (ignores paging)"""
|
| 296 |
+
try:
|
| 297 |
+
severity = request.args.get('severity')
|
| 298 |
+
app_name = request.args.get('app_name')
|
| 299 |
+
event_type = request.args.get('event_type')
|
| 300 |
+
hostname = request.args.get('hostname')
|
| 301 |
+
search = request.args.get('search')
|
| 302 |
+
|
| 303 |
+
query = SystemLog.query
|
| 304 |
+
current_user = get_current_user_safe()
|
| 305 |
+
if current_user:
|
| 306 |
+
is_admin = is_admin_user(current_user)
|
| 307 |
+
if not is_admin:
|
| 308 |
+
query = query.filter(SystemLog.user_id == current_user.id)
|
| 309 |
+
if severity is not None:
|
| 310 |
+
query = query.filter(SystemLog.severity == int(severity))
|
| 311 |
+
if app_name:
|
| 312 |
+
query = query.filter(SystemLog.app_name == app_name)
|
| 313 |
+
if event_type:
|
| 314 |
+
query = query.filter(SystemLog.event_type == event_type)
|
| 315 |
+
if hostname:
|
| 316 |
+
query = query.filter(SystemLog.hostname == hostname)
|
| 317 |
+
if search:
|
| 318 |
+
query = query.filter(SystemLog.message.contains(search))
|
| 319 |
+
|
| 320 |
+
logs = query.order_by(SystemLog.timestamp.desc()).all()
|
| 321 |
+
|
| 322 |
+
# Prepare CSV
|
| 323 |
+
output = csv.StringIO() if hasattr(csv, 'StringIO') else __import__('io').StringIO()
|
| 324 |
+
writer = csv.writer(output)
|
| 325 |
+
headers = [
|
| 326 |
+
'Timestamp', 'Severity', 'Event Type', 'App Name', 'Hostname', 'Message', 'User', 'Source IP'
|
| 327 |
+
]
|
| 328 |
+
writer.writerow(headers)
|
| 329 |
+
for log in logs:
|
| 330 |
+
username = None
|
| 331 |
+
if log.user_id:
|
| 332 |
+
user = User.query.get(log.user_id)
|
| 333 |
+
username = user.username if user else None
|
| 334 |
+
writer.writerow([
|
| 335 |
+
log.timestamp.isoformat() if log.timestamp else '',
|
| 336 |
+
log.severity,
|
| 337 |
+
log.event_type,
|
| 338 |
+
log.app_name,
|
| 339 |
+
log.hostname,
|
| 340 |
+
log.message,
|
| 341 |
+
username or '',
|
| 342 |
+
log.source_ip or ''
|
| 343 |
+
])
|
| 344 |
+
|
| 345 |
+
output.seek(0)
|
| 346 |
+
return Response(
|
| 347 |
+
output.getvalue(),
|
| 348 |
+
mimetype='text/csv',
|
| 349 |
+
headers={
|
| 350 |
+
'Content-Disposition': 'attachment; filename="logs.csv"'
|
| 351 |
+
}
|
| 352 |
+
)
|
| 353 |
+
except Exception as e:
|
| 354 |
+
log_event(
|
| 355 |
+
severity=3,
|
| 356 |
+
message=f"Failed to download logs CSV: {str(e)}",
|
| 357 |
+
event_type="download_logs_csv_error",
|
| 358 |
+
user_id=get_current_user_safe().id if get_current_user_safe() else None
|
| 359 |
+
)
|
| 360 |
+
return jsonify({'error': str(e)}), 500
|
storage.py
CHANGED
|
@@ -36,9 +36,21 @@ class FileStorageBackend(StorageBackend):
|
|
| 36 |
|
| 37 |
def generate_upload_url(self, file_name, content_type=None, session_id=None):
|
| 38 |
"""For file storage, return a local path and upload endpoint (full URL)"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
file_id = session_id or str(uuid.uuid4())
|
| 40 |
-
storage_key = f"{file_id}/{
|
| 41 |
local_path = os.path.join(self.storage_path, storage_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
# Create directory
|
| 44 |
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
|
@@ -62,6 +74,14 @@ class FileStorageBackend(StorageBackend):
|
|
| 62 |
def delete_file(self, storage_path):
|
| 63 |
"""Delete local file"""
|
| 64 |
local_path = os.path.join(self.storage_path, storage_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
try:
|
| 66 |
if os.path.exists(local_path):
|
| 67 |
os.remove(local_path)
|
|
|
|
| 36 |
|
| 37 |
def generate_upload_url(self, file_name, content_type=None, session_id=None):
|
| 38 |
"""For file storage, return a local path and upload endpoint (full URL)"""
|
| 39 |
+
# Sanitize file_name to prevent directory traversal
|
| 40 |
+
# Remove any path separators and normalize
|
| 41 |
+
safe_file_name = os.path.basename(file_name.replace('\\', '/').split('/')[-1])
|
| 42 |
+
if not safe_file_name or safe_file_name.startswith('.'):
|
| 43 |
+
safe_file_name = 'file.bin'
|
| 44 |
+
|
| 45 |
file_id = session_id or str(uuid.uuid4())
|
| 46 |
+
storage_key = f"{file_id}/{safe_file_name}"
|
| 47 |
local_path = os.path.join(self.storage_path, storage_key)
|
| 48 |
+
|
| 49 |
+
# Verify the resolved path is within storage_path (prevent traversal)
|
| 50 |
+
real_storage_path = os.path.realpath(self.storage_path)
|
| 51 |
+
real_local_path = os.path.realpath(local_path)
|
| 52 |
+
if not real_local_path.startswith(real_storage_path):
|
| 53 |
+
raise ValueError(f"Invalid file path: directory traversal detected")
|
| 54 |
|
| 55 |
# Create directory
|
| 56 |
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
|
|
|
| 74 |
def delete_file(self, storage_path):
|
| 75 |
"""Delete local file"""
|
| 76 |
local_path = os.path.join(self.storage_path, storage_path)
|
| 77 |
+
|
| 78 |
+
# SECURITY: Verify the resolved path is within storage directory
|
| 79 |
+
real_storage_path = os.path.realpath(self.storage_path)
|
| 80 |
+
real_local_path = os.path.realpath(local_path)
|
| 81 |
+
if not real_local_path.startswith(real_storage_path):
|
| 82 |
+
logger.error(f"Directory traversal attempt detected in delete: {storage_path}")
|
| 83 |
+
return False
|
| 84 |
+
|
| 85 |
try:
|
| 86 |
if os.path.exists(local_path):
|
| 87 |
os.remove(local_path)
|
templates/logs.html
CHANGED
|
@@ -18,10 +18,53 @@
|
|
| 18 |
<i data-feather="refresh-cw" class="me-1"></i>
|
| 19 |
Refresh
|
| 20 |
</button>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
<button class="btn btn-outline-danger" onclick="confirmDeleteAllLogs()">
|
| 22 |
<i data-feather="trash-2" class="me-1"></i>
|
| 23 |
{% if current_user and current_user.username == 'admin' %}Delete All Logs{% else %}Delete My Logs{% endif %}
|
| 24 |
</button>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
</div>
|
| 26 |
</div>
|
| 27 |
</div>
|
|
|
|
| 18 |
<i data-feather="refresh-cw" class="me-1"></i>
|
| 19 |
Refresh
|
| 20 |
</button>
|
| 21 |
+
<button class="btn btn-outline-success" onclick="downloadLogsCSV()">
|
| 22 |
+
<i data-feather="download" class="me-1"></i>
|
| 23 |
+
Download CSV
|
| 24 |
+
</button>
|
| 25 |
<button class="btn btn-outline-danger" onclick="confirmDeleteAllLogs()">
|
| 26 |
<i data-feather="trash-2" class="me-1"></i>
|
| 27 |
{% if current_user and current_user.username == 'admin' %}Delete All Logs{% else %}Delete My Logs{% endif %}
|
| 28 |
</button>
|
| 29 |
+
<script>
|
| 30 |
+
async function downloadLogsCSV() {
|
| 31 |
+
// Collect current filter values
|
| 32 |
+
const severity = document.getElementById('severityFilter').value;
|
| 33 |
+
const eventType = document.getElementById('eventTypeFilter').value;
|
| 34 |
+
const search = document.getElementById('searchFilter').value;
|
| 35 |
+
let params = [];
|
| 36 |
+
if (severity) params.push(`severity=${encodeURIComponent(severity)}`);
|
| 37 |
+
if (eventType) params.push(`event_type=${encodeURIComponent(eventType)}`);
|
| 38 |
+
if (search) params.push(`search=${encodeURIComponent(search)}`);
|
| 39 |
+
const url = `/logs/csv${params.length ? '?' + params.join('&') : ''}`;
|
| 40 |
+
|
| 41 |
+
try {
|
| 42 |
+
const response = await fetch(url, {
|
| 43 |
+
method: 'GET',
|
| 44 |
+
headers: {
|
| 45 |
+
'Authorization': `Bearer ${window.sessionStorage.getItem('access_token') || '{{ session.get("access_token", "") }}'}`
|
| 46 |
+
}
|
| 47 |
+
});
|
| 48 |
+
if (response.status === 401) {
|
| 49 |
+
// Require relogin
|
| 50 |
+
window.location.href = '/login?next=' + encodeURIComponent(window.location.pathname);
|
| 51 |
+
return;
|
| 52 |
+
}
|
| 53 |
+
if (!response.ok) {
|
| 54 |
+
throw new Error('Failed to download logs: ' + response.statusText);
|
| 55 |
+
}
|
| 56 |
+
const blob = await response.blob();
|
| 57 |
+
const link = document.createElement('a');
|
| 58 |
+
link.href = window.URL.createObjectURL(blob);
|
| 59 |
+
link.download = 'logs.csv';
|
| 60 |
+
document.body.appendChild(link);
|
| 61 |
+
link.click();
|
| 62 |
+
document.body.removeChild(link);
|
| 63 |
+
} catch (error) {
|
| 64 |
+
alert('Failed to download logs: ' + (error.message || error));
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
</script>
|
| 68 |
</div>
|
| 69 |
</div>
|
| 70 |
</div>
|
web/products.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
from flask import Blueprint, render_template, request, redirect, url_for, session
|
| 2 |
from models import db, Attestation, PolicyResult, Product
|
| 3 |
from sqlalchemy import func, text
|
| 4 |
-
|
| 5 |
from sqlalchemy.orm import joinedload
|
| 6 |
|
| 7 |
-
from
|
|
|
|
| 8 |
|
| 9 |
def get_products_with_stats(filter_query=None, version_filter=None, user_id=None, show_all=False, badge_filter=None, paginate=True):
|
| 10 |
# Only consume data from products table
|
|
@@ -64,7 +64,8 @@ def get_products_with_stats(filter_query=None, version_filter=None, user_id=None
|
|
| 64 |
'last_update': last_update
|
| 65 |
})
|
| 66 |
# Sort products by last_update descending
|
| 67 |
-
|
|
|
|
| 68 |
# Paginate if needed
|
| 69 |
if paginate:
|
| 70 |
page = request.args.get('page', 1, type=int)
|
|
|
|
| 1 |
from flask import Blueprint, render_template, request, redirect, url_for, session
|
| 2 |
from models import db, Attestation, PolicyResult, Product
|
| 3 |
from sqlalchemy import func, text
|
|
|
|
| 4 |
from sqlalchemy.orm import joinedload
|
| 5 |
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
|
| 9 |
def get_products_with_stats(filter_query=None, version_filter=None, user_id=None, show_all=False, badge_filter=None, paginate=True):
|
| 10 |
# Only consume data from products table
|
|
|
|
| 64 |
'last_update': last_update
|
| 65 |
})
|
| 66 |
# Sort products by last_update descending
|
| 67 |
+
# Use datetime.min for None values to ensure consistent sorting
|
| 68 |
+
products.sort(key=lambda x: x['last_update'] if x['last_update'] else datetime.min, reverse=True)
|
| 69 |
# Paginate if needed
|
| 70 |
if paginate:
|
| 71 |
page = request.args.get('page', 1, type=int)
|