-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_routes.py
More file actions
535 lines (445 loc) · 19 KB
/
Copy pathadmin_routes.py
File metadata and controls
535 lines (445 loc) · 19 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
from flask import Blueprint, request, jsonify
import os
import json
import logging
from datetime import datetime, timezone, timedelta
from apscheduler.triggers.cron import CronTrigger
from pixelprobe.models import db, ScanResult, IgnoredErrorPattern, ScanConfiguration, ScanSchedule
from pixelprobe.scheduler import MediaScheduler
from pixelprobe.utils.security import validate_json_input, AuditLogger, validate_directory_path
from pixelprobe.auth import auth_required
logger = logging.getLogger(__name__)
admin_bp = Blueprint('admin', __name__, url_prefix='/api')
from flask import current_app
from pixelprobe.utils.rate_limiting import rate_limit
# Get scheduler instance (will be initialized in app context)
scheduler = None
def set_scheduler(sched):
"""Set the scheduler instance"""
global scheduler
scheduler = sched
def calculate_next_run(cron_expression: str, last_run=None):
"""
Calculate next run time from cron/interval expression.
Works without requiring a running APScheduler instance, allowing any
Gunicorn worker to calculate the correct next_run time.
Args:
cron_expression: Either a cron expression (e.g., "*/5 * * * *")
or interval format (e.g., "interval:hours:6")
last_run: Optional last run time (used for interval calculations)
Returns:
Next run time as timezone-aware datetime (UTC)
"""
now = datetime.now(timezone.utc)
if cron_expression.startswith('interval:'):
# Parse interval format: interval:unit:value
parts = cron_expression.split(':')
if len(parts) == 3:
unit = parts[1]
value = int(parts[2])
interval = timedelta(**{unit: value})
if last_run:
# Ensure timezone-aware
if last_run.tzinfo is None:
last_run = last_run.replace(tzinfo=timezone.utc)
next_time = last_run + interval
# If calculated time is in past, schedule from now
if next_time < now:
next_time = now + interval
return next_time
return now + interval
raise ValueError(f"Invalid interval format: {cron_expression}")
else:
# Standard cron format - use APScheduler's trigger
parts = cron_expression.split()
if len(parts) != 5:
raise ValueError(f"Invalid cron expression: {cron_expression}")
trigger = CronTrigger(
minute=parts[0], hour=parts[1], day=parts[2],
month=parts[3], day_of_week=parts[4],
timezone='UTC'
)
return trigger.get_next_fire_time(None, now)
@admin_bp.route('/mark-as-good', methods=['POST'])
@rate_limit("10 per minute")
@auth_required
@validate_json_input({
'file_ids': {'required': True, 'type': list}
})
def mark_as_good():
"""Mark files as good/healthy"""
data = request.get_json()
file_ids = data.get('file_ids', [])
# Validate file IDs are integers
try:
file_ids = [int(fid) for fid in file_ids]
except (ValueError, TypeError):
return {'error': 'Invalid file ID format'}, 400
if len(file_ids) > 1000: # Prevent excessive updates
return {'error': 'Too many file IDs (max 1000)'}, 400
try:
for file_id in file_ids:
result = db.session.get(ScanResult, file_id)
if result:
result.marked_as_good = True
result.is_corrupted = False
logger.info(f"Marked file as good (healthy): {result.file_path}")
AuditLogger.log_action('mark_as_good', {'file_id': file_id, 'file_path': result.file_path})
db.session.commit()
logger.info(f"Successfully marked {len(file_ids)} files as good")
return {
'message': f'Successfully marked {len(file_ids)} files as good',
'marked_files': len(file_ids)
}
except Exception as e:
logger.error(f"Error marking files as good: {str(e)}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/ignored-patterns')
@auth_required
def get_ignored_patterns():
"""Get all ignored error patterns"""
patterns = IgnoredErrorPattern.query.filter_by(is_active=True).all()
return [{
'id': p.id,
'pattern': p.pattern,
'description': p.description,
'created_at': p.created_at.isoformat() if p.created_at else None
} for p in patterns]
@admin_bp.route('/ignored-patterns', methods=['POST'])
@auth_required
@validate_json_input({
'pattern': {'required': True, 'type': str, 'max_length': 200},
'description': {'required': False, 'type': str, 'max_length': 500}
})
def add_ignored_pattern():
"""Add a new ignored error pattern"""
data = request.get_json()
pattern = data.get('pattern')
description = data.get('description', '')
# Validate pattern doesn't contain dangerous regex
dangerous_patterns = [r'\(\?[imsxXU]', r'\(\?P<', r'\(\?#']
for dp in dangerous_patterns:
if dp in pattern:
return {'error': 'Pattern contains potentially dangerous regex syntax'}, 400
try:
# Check for duplicate pattern
existing = IgnoredErrorPattern.query.filter_by(pattern=pattern, is_active=True).first()
if existing:
return {'error': f'Pattern "{pattern}" already exists'}, 400
new_pattern = IgnoredErrorPattern(
pattern=pattern,
description=description,
is_active=True,
created_at=datetime.now(timezone.utc)
)
db.session.add(new_pattern)
db.session.commit()
AuditLogger.log_action('add_ignored_pattern', {'pattern': pattern})
return {
'id': new_pattern.id,
'pattern': new_pattern.pattern,
'description': new_pattern.description,
'message': 'Pattern added successfully'
}, 201
except Exception as e:
logger.error(f"Error adding ignored pattern: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/ignored-patterns/<int:pattern_id>', methods=['DELETE'])
@auth_required
def delete_ignored_pattern(pattern_id):
"""Delete an ignored error pattern"""
pattern = db.session.get(IgnoredErrorPattern, pattern_id)
if not pattern:
return {'error': 'Pattern not found'}, 404
try:
pattern_text = pattern.pattern
pattern.is_active = False # Soft delete
db.session.commit()
AuditLogger.log_action('delete_ignored_pattern', {'pattern_id': pattern_id, 'pattern': pattern_text})
return {'message': 'Pattern deleted successfully'}
except Exception as e:
logger.error(f"Error deleting ignored pattern: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/configurations')
@auth_required
def get_configurations():
"""Get all scan configurations"""
configs = ScanConfiguration.query.all()
return [{
'id': c.id,
'path': c.path,
'is_active': c.is_active,
'created_at': c.created_at.isoformat() if c.created_at else None
} for c in configs]
@admin_bp.route('/configurations', methods=['POST'])
@auth_required
@validate_json_input({
'path': {'required': True, 'type': str, 'max_length': 1000}
})
def add_configuration():
"""Add or update a scan configuration"""
data = request.get_json()
path = data.get('path')
# Admin is defining a new allowlist entry, so skip the allowlist check.
# Traversal tokens and symlink resolution still run.
try:
path = validate_directory_path(path, allowed_paths=[])
AuditLogger.log_action('add_configuration', {'path': path})
except Exception as e:
AuditLogger.log_security_event('invalid_directory_path', str(e), 'warning')
return {'error': 'Invalid directory path'}, 400
try:
# Check if configuration already exists
existing_config = ScanConfiguration.query.filter_by(path=path).first()
if existing_config:
# Reactivate if it was deactivated
existing_config.is_active = True
message = 'Configuration reactivated'
else:
# Create new configuration with backward compatibility
new_config = ScanConfiguration(
path=path,
is_active=True,
created_at=datetime.now(timezone.utc),
# Add legacy fields to satisfy old schema
key=f'scan_dir_{len(ScanConfiguration.query.all()) + 1}',
value=path,
description=f'Scan directory: {path}'
)
db.session.add(new_config)
message = 'Configuration added successfully'
db.session.commit()
return {
'path': path,
'message': message
}
except Exception as e:
logger.error(f"Error adding configuration: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/schedules', methods=['GET'])
@auth_required
def get_schedules():
"""Get all scan schedules"""
# Return all schedules (active and inactive) so they can be toggled
# DELETE endpoint does hard delete, so truly deleted ones won't appear
schedules = ScanSchedule.query.all()
return {'schedules': [schedule.to_dict() for schedule in schedules]}
@admin_bp.route('/schedules/<int:schedule_id>', methods=['GET'])
@auth_required
def get_schedule(schedule_id):
"""Get a specific scan schedule by ID"""
schedule = db.get_or_404(ScanSchedule, schedule_id)
return jsonify(schedule.to_dict())
@admin_bp.route('/schedules', methods=['POST'])
@auth_required
def create_schedule():
"""Create a new scan schedule"""
data = request.get_json()
try:
# Check for duplicate name
name = data.get('name', 'Unnamed Schedule')
existing = ScanSchedule.query.filter_by(name=name, is_active=True).first()
if existing:
return {'error': f'Schedule with name "{name}" already exists'}, 400
schedule = ScanSchedule(
name=name,
cron_expression=data['cron_expression'],
scan_paths=json.dumps(data.get('scan_paths', [])),
scan_type=data.get('scan_type', 'full'),
force_rescan=data.get('force_rescan', False),
is_active=True,
created_at=datetime.now(timezone.utc)
)
db.session.add(schedule)
db.session.commit()
# Trigger schedule reload in Celery worker (where scheduler runs)
# Import lazily to avoid circular import (tasks.py -> app.py -> admin_routes.py)
try:
from pixelprobe.tasks import reload_schedules_task
reload_schedules_task.delay()
except Exception as e:
# May fail if Celery/Redis unavailable (ImportError, ConnectionError, etc.)
logger.warning(f"Could not trigger schedule reload: {e}")
return schedule.to_dict(), 201
except Exception as e:
logger.error(f"Error creating schedule: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/schedules/<int:schedule_id>', methods=['PUT'])
@auth_required
def update_schedule(schedule_id):
"""Update a scan schedule"""
schedule = db.get_or_404(ScanSchedule, schedule_id)
data = request.get_json()
try:
# Track if schedule is being re-enabled or cron changed
was_inactive = not schedule.is_active
new_is_active = data.get('is_active', schedule.is_active)
being_reactivated = was_inactive and new_is_active
new_cron = data.get('cron_expression', schedule.cron_expression)
cron_changed = new_cron != schedule.cron_expression
# Update fields
schedule.name = data.get('name', schedule.name)
schedule.cron_expression = new_cron
if 'scan_paths' in data:
schedule.scan_paths = json.dumps(data['scan_paths'])
schedule.scan_type = data.get('scan_type', schedule.scan_type)
schedule.force_rescan = data.get('force_rescan', schedule.force_rescan)
schedule.is_active = new_is_active
# Recalculate next_run when:
# 1. Schedule is being re-enabled, OR
# 2. Cron expression changed while schedule is active
if being_reactivated or (cron_changed and new_is_active):
try:
schedule.next_run = calculate_next_run(schedule.cron_expression, schedule.last_run)
logger.info(f"Recalculated next_run for schedule {schedule_id}: {schedule.next_run}")
except Exception as e:
logger.warning(f"Could not calculate next_run for schedule {schedule_id}: {e}")
db.session.commit()
# Trigger schedule reload in Celery worker (where scheduler runs)
try:
from pixelprobe.tasks import reload_schedules_task
reload_schedules_task.delay()
except Exception as e:
logger.warning(f"Could not trigger schedule reload: {e}")
return schedule.to_dict()
except Exception as e:
logger.error(f"Error updating schedule: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/schedules/<int:schedule_id>', methods=['DELETE'])
@auth_required
def delete_schedule(schedule_id):
"""Delete a scan schedule"""
schedule = db.get_or_404(ScanSchedule, schedule_id)
try:
# Actually delete the schedule from database instead of soft delete
db.session.delete(schedule)
db.session.commit()
# Trigger schedule reload in Celery worker (where scheduler runs)
try:
from pixelprobe.tasks import reload_schedules_task
reload_schedules_task.delay()
except Exception as e:
logger.warning(f"Could not trigger schedule reload: {e}")
return '', 204
except Exception as e:
logger.error(f"Error deleting schedule: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/exclusions', methods=['GET'])
@auth_required
def get_exclusions():
"""Get current exclusion settings from database"""
try:
from pixelprobe.models import Exclusion
# Get all active exclusions
path_exclusions = Exclusion.query.filter_by(
exclusion_type='path',
is_active=True
).all()
extension_exclusions = Exclusion.query.filter_by(
exclusion_type='extension',
is_active=True
).all()
return {
'paths': [e.value for e in path_exclusions],
'extensions': [e.value for e in extension_exclusions]
}
except Exception as e:
logger.error(f"Error reading exclusions: {e}")
return {'paths': [], 'extensions': []}
@admin_bp.route('/exclusions', methods=['PUT'])
@auth_required
def update_exclusions():
"""Update all exclusion settings in database"""
data = request.get_json()
try:
from pixelprobe.models import Exclusion
# Validate data structure
if not isinstance(data.get('paths', []), list) or not isinstance(data.get('extensions', []), list):
return {'error': 'Invalid data format'}, 400
# Clear existing exclusions
Exclusion.query.update({'is_active': False})
# Add new exclusions
for path in data.get('paths', []):
exclusion = Exclusion(exclusion_type='path', value=path, is_active=True)
db.session.add(exclusion)
for extension in data.get('extensions', []):
exclusion = Exclusion(exclusion_type='extension', value=extension, is_active=True)
db.session.add(exclusion)
db.session.commit()
return {'message': 'Exclusions updated successfully'}
except Exception as e:
logger.error(f"Error updating exclusions: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/exclusions/<exclusion_type>', methods=['POST'])
@auth_required
def add_exclusion(exclusion_type):
"""Add a single exclusion (path or extension) to database"""
# Validate exclusion type
if exclusion_type not in ['path', 'extension']:
return {'error': 'Invalid exclusion type'}, 400
data = request.get_json()
value = data.get('item') or data.get('value') # Support both 'item' and 'value'
if not value:
return {'error': 'Value is required'}, 400
try:
from pixelprobe.models import Exclusion
# Check if already exists
existing = Exclusion.query.filter_by(
exclusion_type=exclusion_type,
value=value,
is_active=True
).first()
if existing:
return {'error': f'{exclusion_type.capitalize()} already exists'}, 400
# Add new exclusion
exclusion = Exclusion(
exclusion_type=exclusion_type,
value=value,
is_active=True
)
db.session.add(exclusion)
db.session.commit()
AuditLogger.log_action('add_exclusion', {'type': exclusion_type, 'value': value})
return {'message': f'{exclusion_type.capitalize()} added successfully'}
except Exception as e:
logger.error(f"Error adding exclusion: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500
@admin_bp.route('/exclusions/<exclusion_type>', methods=['DELETE'])
@auth_required
def remove_exclusion(exclusion_type):
"""Remove a single exclusion (path or extension) from database"""
# Validate exclusion type
if exclusion_type not in ['path', 'extension']:
return {'error': 'Invalid exclusion type'}, 400
data = request.get_json()
value = data.get('item') or data.get('value') # Support both 'item' and 'value'
if not value:
return {'error': 'Value is required'}, 400
try:
from pixelprobe.models import Exclusion
# Find the exclusion
exclusion = Exclusion.query.filter_by(
exclusion_type=exclusion_type,
value=value,
is_active=True
).first()
if not exclusion:
return {'error': f'{exclusion_type.capitalize()} not found'}, 404
# Soft delete
exclusion.is_active = False
db.session.commit()
AuditLogger.log_action('remove_exclusion', {'type': exclusion_type, 'value': value})
return {'message': f'{exclusion_type.capitalize()} removed successfully'}
except Exception as e:
logger.error(f"Error removing exclusion: {e}", exc_info=True)
db.session.rollback()
return {'error': 'Internal server error'}, 500