-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmock_server_g.py
More file actions
2157 lines (1811 loc) · 91.4 KB
/
mock_server_g.py
File metadata and controls
2157 lines (1811 loc) · 91.4 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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Mock API Server for Domain-Driven OpenAPI Testing
Creates a mock server that responds to all OpenAPI endpoints with
valid responses based on your domain model schemas.
"""
from flask import Flask, request, jsonify, redirect, Response
import json
import random
import re
import time
import logging
from datetime import datetime, timezone
print("Mock server script started.") # Debug print
app = Flask(__name__)
# Configure Flask to return JSON errors instead of HTML
app.config['JSON_AS_ASCII'] = False
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
# Disable HTML error pages for better API compliance
app.config['TRAP_HTTP_EXCEPTIONS'] = True
app.config['TESTING'] = False
# Enhanced security middleware to handle malformed headers and protect against attacks
import time
import logging
import threading
from collections import defaultdict, deque
from webob import Request
class SafeWSGIMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
try:
Request(environ) # безопасный парсер
return self.app(environ, start_response)
except Exception as e:
# Return JSON error instead of HTML for API compliance
start_response("400 Bad Request", [("Content-Type", "application/json")])
return [b'{"error": {"code": "BAD_REQUEST", "message": "Invalid HTTP header"}}']
# Apply enhanced security middleware
app.wsgi_app = SafeWSGIMiddleware(app.wsgi_app)
# Custom error handlers to ensure JSON responses
@app.errorhandler(400)
def bad_request_error(error):
return jsonify({"error": {"code": "BAD_REQUEST", "message": "Bad request"}}), 400
@app.errorhandler(404)
def not_found_error(error):
return jsonify({"error": {"code": "NOT_FOUND", "message": "Endpoint not found"}}), 404
@app.errorhandler(405)
def method_not_allowed_error(error):
# Determine supported methods for the current endpoint
supported_methods = set()
if request.url_rule:
# Get methods supported by the current route
supported_methods = request.url_rule.methods.copy()
# Remove OPTIONS and HEAD if present (OPTIONS is handled separately, HEAD is automatic)
supported_methods.discard('OPTIONS')
supported_methods.discard('HEAD')
else:
# Fallback - assume common methods for unknown routes
supported_methods = {'GET', 'POST', 'PUT', 'DELETE'}
# Sort methods for consistent output
allow_header = ', '.join(sorted(supported_methods))
response = jsonify({"error": {"code": "METHOD_NOT_ALLOWED", "message": "Method not allowed"}})
response.headers['Allow'] = allow_header
return response, 405
@app.errorhandler(406)
def not_acceptable_error(error):
return jsonify({"error": {"code": "NOT_ACCEPTABLE", "message": "Not acceptable"}}), 406
@app.errorhandler(422)
def unprocessable_entity_error(error):
return jsonify({"error": {"code": "VALIDATION_ERROR", "message": "Unprocessable entity"}}), 422
@app.errorhandler(500)
def internal_error(error):
return jsonify({"error": {"code": "INTERNAL_ERROR", "message": "Internal server error"}}), 500
# Global error handler for all exceptions
@app.errorhandler(Exception)
def handle_exception(error):
# Log the error
app.logger.error(f"Unhandled exception: {error}")
return jsonify({"error": {"code": "INTERNAL_ERROR", "message": "Internal server error"}}), 500
# Add comprehensive headers for ads server compatibility
@app.after_request
def add_cors_headers(response):
# Enhanced CORS headers
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-API-Key, X-Requested-With'
response.headers['Access-Control-Allow-Credentials'] = 'false'
response.headers['Access-Control-Max-Age'] = '86400'
# Security headers for ads server
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()'
# Cache control for ad serving (short cache for dynamic content)
if request.path.startswith('/mock-'):
response.headers['Cache-Control'] = 'private, max-age=300' # 5 minutes for ad pages
else:
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
# Mobile and ad-specific headers
response.headers['Mobile-Web-App-Capable'] = 'yes'
response.headers['Apple-Mobile-Web-App-Capable'] = 'yes'
response.headers['Apple-Mobile-Web-App-Status-Bar-Style'] = 'default'
# Performance headers
response.headers['Connection'] = 'close'
return response
# Global regex patterns
date_time_pattern = r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$'
date_pattern = r'^\d{4}-\d{2}-\d{2}$'
# ============================================================================
# MOCK DATA MANAGEMENT
# ============================================================================
# Simple in-memory storage to simulate state management
mock_storage = {
"campaigns": {},
"deleted_campaigns": set(),
"landing_pages": {},
"analytics_cache": {},
"clicks": [] # Initialize clicks storage
}
def reset_storage():
"""Reset all mock storage"""
global mock_storage
mock_storage = {
"campaigns": {},
"deleted_campaigns": set(),
"landing_pages": {},
"analytics_cache": {},
"clicks": [] # Initialize clicks storage
}
# Create some initial mock campaigns for testing
mock_campaigns = [
{
"id": "camp_123", # Used in security tests
"name": "Summer Sale Campaign",
"description": "High-converting summer promotion",
"status": "active",
"schedule": {
"startDate": "2024-01-01T00:00:00Z",
"endDate": "2024-12-31T23:59:59Z",
},
"urls": {
"safePage": "https://example.com/safe-landing",
"offerPage": "https://example.com/offer",
},
"financial": {
"costModel": "CPA",
"payout": {"amount": 25.50, "currency": "USD"},
"dailyBudget": {"amount": 500.00, "currency": "USD"},
"totalBudget": {"amount": 15000.00, "currency": "USD"},
"spent": {"amount": 1250.75, "currency": "USD"},
},
"performance": {
"clicks": 5000,
"conversions": 150,
"ctr": 0.025,
"cr": 0.03,
"epc": {"amount": 8.35, "currency": "USD"},
"roi": 2.15,
},
"createdAt": "2024-01-01T10:00:00Z",
"updatedAt": "2024-01-15T15:00:00Z",
"_links": {
"self": "/api/v1/campaigns/camp_123",
"landingPages": "/api/v1/campaigns/camp_123/landing-pages",
"offers": "/api/v1/campaigns/camp_123/offers",
"analytics": "/api/v1/campaigns/camp_123/analytics",
}
},
{
"id": "camp_456",
"name": "Winter Promotion",
"description": "Holiday season marketing campaign",
"status": "active",
"schedule": {
"startDate": "2024-11-01T00:00:00Z",
"endDate": "2024-12-31T23:59:59Z",
},
"urls": {
"safePage": "https://example.com/winter-landing",
"offerPage": "https://example.com/winter-offer",
},
"financial": {
"costModel": "CPC",
"payout": {"amount": 15.00, "currency": "USD"},
"dailyBudget": {"amount": 300.00, "currency": "USD"},
"totalBudget": {"amount": 9000.00, "currency": "USD"},
"spent": {"amount": 2100.00, "currency": "USD"},
},
"performance": {
"clicks": 8000,
"conversions": 240,
"ctr": 0.032,
"cr": 0.03,
"epc": {"amount": 6.25, "currency": "USD"},
"roi": 1.85,
},
"createdAt": "2024-11-01T08:00:00Z",
"updatedAt": "2024-11-20T12:00:00Z",
"_links": {
"self": "/api/v1/campaigns/camp_456",
"landingPages": "/api/v1/campaigns/camp_456/landing-pages",
"offers": "/api/v1/campaigns/camp_456/offers",
"analytics": "/api/v1/campaigns/camp_456/analytics",
}
}
]
# Add mock campaigns to storage
for campaign in mock_campaigns:
mock_storage["campaigns"][campaign["id"]] = campaign
# Create some initial mock clicks for testing
mock_clicks = [
{
'id': '123e4567-e89b-12d3-a456-426614174000', # Used in tests
'cid': 123,
'ip': '192.168.1.100',
'ua': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'ref': 'https://facebook.com/ad/123',
'isValid': 1,
'ts': 1640995200,
'sub1': 'fb_ad_15',
'sub2': 'facebook',
'sub3': 'adset_12',
'sub4': 'video1',
'sub5': 'lookalike78',
'clickId': 'USERCLICK123',
'affSub': 'aff_sub_123',
'affSub2': None,
'affSub3': None,
'affSub4': None,
'affSub5': None,
'fraudScore': 0.0,
'fraudReason': None,
'landingPageId': 456,
'campaignOfferId': 789,
'trafficSourceId': 101,
'conversionType': 'sale'
},
{
'id': '456e7890-e89b-12d3-a456-426614174001',
'cid': 456,
'ip': '10.0.0.50',
'ua': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)',
'ref': 'https://google.com/search?q=test',
'isValid': 1,
'ts': 1641081600,
'sub1': 'google_search',
'sub2': 'google',
'sub3': 'brand_campaign',
'sub4': 'text_ad',
'sub5': 'keyword_123',
'clickId': 'GOOGLE_CLICK_456',
'affSub': 'network_a',
'affSub2': 'sub_a1',
'affSub3': None,
'affSub4': None,
'affSub5': None,
'fraudScore': 0.1,
'fraudReason': None,
'landingPageId': 457,
'campaignOfferId': 790,
'trafficSourceId': 102,
'conversionType': 'lead'
}
]
# Add mock clicks to storage
mock_storage["clicks"] = mock_clicks
# Initialize storage with mock data
reset_storage()
def is_campaign_deleted(campaign_id):
"""Check if campaign was deleted"""
return campaign_id in mock_storage["deleted_campaigns"]
def mark_campaign_deleted(campaign_id):
"""Mark campaign as deleted"""
if campaign_id in mock_storage["campaigns"]:
del mock_storage["campaigns"][campaign_id]
mock_storage["deleted_campaigns"].add(campaign_id)
# ============================================================================
# AUTHENTICATION VALIDATION
# ============================================================================
def validate_auth(request):
"""Validate Authorization header according to HTTP standards"""
auth_header = request.headers.get('Authorization', '')
# No auth header
if not auth_header:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Authentication required"}}, 401
# Check for control characters or invalid bytes
try:
for c in auth_header:
if ord(c) < 32 or ord(c) > 126:
return False, {"error": {"code": "VALIDATION_ERROR", "message": "Invalid characters in authentication header"}}, 401
except (UnicodeDecodeError, TypeError):
return False, {"error": {"code": "VALIDATION_ERROR", "message": "Invalid authentication header encoding"}}, 401
# Check header length
if len(auth_header) > 1000:
return False, {"error": {"code": "VALIDATION_ERROR", "message": "Authentication header too long"}}, 401
# Authorization header must contain scheme and credentials separated by space
if ' ' not in auth_header:
return False, {"error": {"code": "VALIDATION_ERROR", "message": "Invalid authentication format - missing scheme"}}, 401
scheme, credentials = auth_header.split(' ', 1)
scheme = scheme.strip()
credentials = credentials.strip()
# Empty scheme or credentials
if not scheme or not credentials:
return False, {"error": {"code": "VALIDATION_ERROR", "message": "Invalid authentication format"}}, 401
# Validate scheme (case-insensitive for common schemes, but we'll accept various)
valid_schemes = {'Bearer', 'Basic', 'Token', 'Api-Key', 'ApiKey', 'Digest', 'Negotiate', 'AWS4-HMAC-SHA256'}
if scheme not in valid_schemes and not scheme.isalpha():
return False, {"error": {"code": "VALIDATION_ERROR", "message": f"Unsupported authentication scheme: {scheme}"}}, 401
# Validate credentials based on scheme
if scheme.upper() == 'BEARER':
# Bearer tokens (JWT, API keys, etc.)
if len(credentials) < 8: # Minimum reasonable token length
return False, {"error": {"code": "UNAUTHORIZED", "message": "Token too short"}}, 401
# Reject obviously invalid tokens
invalid_patterns = ['[filtered]', 'schemathesis', 'null', 'undefined', 'test', 'invalid']
if any(pattern in credentials.lower() for pattern in invalid_patterns):
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid token"}}, 401
# For JWT-like tokens (contain dots), basic structure validation
if '.' in credentials and len(credentials.split('.')) != 3:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid JWT format"}}, 401
elif scheme.upper() == 'BASIC':
# Basic auth - should be base64 encoded
import base64
try:
decoded = base64.b64decode(credentials)
if b':' not in decoded:
return False, {"error": {"code": "VALIDATION_ERROR", "message": "Invalid Basic auth format"}}, 401
except Exception:
return False, {"error": {"code": "VALIDATION_ERROR", "message": "Invalid Base64 encoding in Basic auth"}}, 401
# For other schemes (Token, Api-Key, etc.), just ensure credentials are present and not obviously invalid
else:
if len(credentials) < 4:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Credentials too short"}}, 401
invalid_patterns = ['[filtered]', 'schemathesis', 'null', 'undefined']
if any(pattern in credentials.lower() for pattern in invalid_patterns):
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid credentials"}}, 401
# Check for valid test tokens (for testing purposes only)
valid_test_tokens = {
# Bearer tokens
'test_jwt_token_12345': True,
'valid_api_key_abcdef': True,
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c': True,
# Basic auth (user:pass)
'dXNlcjpwYXNz': True, # base64('user:pass')
'YWRtaW46c2VjcmV0': True, # base64('admin:secret')
# Token scheme
'my_test_token_123': True,
# Api-Key
'test_api_key_abcdef123': True,
}
# Check if credentials are in our valid test tokens
if credentials in valid_test_tokens:
# For mock server, we accept these test tokens
return True, None, None
# If we reach here, the format is valid, but credentials are not in our test set
# (since this is a mock server without real authentication)
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid credentials"}}, 401
def endpoint_supports_api_key(request):
"""Check if current endpoint supports API key authentication based on OpenAPI spec"""
path = request.path
# Endpoints that support apiKey according to OpenAPI spec
# /v1/campaigns/{campaignId}/analytics - GET
# Must have at least one character between /campaigns/ and /analytics
if (path.startswith('/v1/campaigns/') and path.endswith('/analytics') and
'/campaigns//' not in path and len(path.split('/')) >= 4 and request.method == 'GET'):
return True
# /v1/click/{clickId} - GET
if path.startswith('/v1/click/') and len(path.split('/')) == 4 and request.method == 'GET':
return True
# /v1/clicks - GET
if path == '/v1/clicks' and request.method == 'GET':
return True
return False
def validate_scopes(request, required_scopes):
"""Validate that the request has the required OAuth2 scopes"""
import jwt
import sys
from security_middleware_fixed import VALID_API_KEYS
# Check for Authorization header first
auth_header = request.headers.get('Authorization', '')
has_auth_header = bool(auth_header)
# Check for API key authentication (only for endpoints that support it)
api_key = request.headers.get('X-API-Key')
has_api_key = bool(api_key)
endpoint_expects_api_key = endpoint_supports_api_key(request)
# Check for valid test tokens first (for testing purposes)
valid_test_tokens = {
# Bearer tokens
'test_jwt_token_12345': ['admin'], # Admin has all scopes
'valid_api_key_abcdef': ['campaign:read', 'campaign:write', 'analytics:read'],
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c': ['campaign:read'],
# Basic auth (user:pass) - base64 encoded
'dXNlcjpwYXNz': ['campaign:read'], # base64('user:pass')
'YWRtaW46c2VjcmV0': ['admin'], # base64('admin:secret')
# Token scheme
'my_test_token_123': ['campaign:read', 'campaign:write'],
# Api-Key
'test_api_key_abcdef123': ['analytics:read', 'traffic:read'],
}
# Case 1: Authorization header present
if has_auth_header:
# Check if it's a Bearer token with our test credentials
if auth_header.startswith('Bearer '):
token = auth_header[7:] # Remove 'Bearer '
if token in valid_test_tokens:
token_scopes = valid_test_tokens[token]
if "admin" in token_scopes or all(scope in token_scopes for scope in required_scopes):
return True, None, None
else:
return False, {"error": {"code": "FORBIDDEN", "message": f"Missing required scope(s): {required_scopes}"}}, 403
# Check if it's Basic auth with our test credentials
elif auth_header.startswith('Basic '):
import base64
try:
credentials = auth_header[6:] # Remove 'Basic '
if credentials in valid_test_tokens:
token_scopes = valid_test_tokens[credentials]
if "admin" in token_scopes or all(scope in token_scopes for scope in required_scopes):
return True, None, None
else:
return False, {"error": {"code": "FORBIDDEN", "message": f"Missing required scope(s): {required_scopes}"}}, 403
except:
pass
# Check if it's Token/Api-Key scheme with our test credentials
else:
# Extract scheme and credentials
if ' ' in auth_header:
scheme, credentials = auth_header.split(' ', 1)
if credentials.strip() in valid_test_tokens:
token_scopes = valid_test_tokens[credentials.strip()]
if "admin" in token_scopes or all(scope in token_scopes for scope in required_scopes):
return True, None, None
else:
return False, {"error": {"code": "FORBIDDEN", "message": f"Missing required scope(s): {required_scopes}"}}, 403
# Try JWT validation for non-test tokens
if auth_header.startswith('Bearer '):
try:
token = auth_header[7:] # Remove 'Bearer '
if not token or '[Filtered]' in token or 'schemathesis' in token.lower() or len(token.strip()) == 0:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid or missing token"}}, 401
payload = jwt.decode(token, options={"verify_signature": False}, algorithms=["HS256"])
token_scopes = payload.get('scopes', [])
if "admin" in token_scopes:
return True, None, None # Admin scope grants all access
# Validate token scopes
if not isinstance(token_scopes, list):
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid token scopes format"}}, 401
invalid_scopes = []
for scope in token_scopes:
if scope is None or (isinstance(scope, str) and not scope.strip()):
invalid_scopes.append(scope)
if not token_scopes or invalid_scopes:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid or empty token scopes"}}, 401
if all(scope in token_scopes for scope in required_scopes):
return True, None, None
else:
return False, {"error": {"code": "FORBIDDEN", "message": f"Missing required scope(s): {required_scopes}"}}, 403
except jwt.ExpiredSignatureError:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Token has expired"}}, 401
except jwt.InvalidTokenError:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid token"}}, 401
except Exception as e:
# Catch any other unexpected errors during token processing
app.logger.error(f"Token processing error: {e}")
return False, {"error": {"code": "UNAUTHORIZED", "message": f"Token processing error"}}, 401
# Case 2: No Authorization header, but API Key is expected and present
elif not has_auth_header and endpoint_expects_api_key and has_api_key:
if api_key == '[Filtered]' or not api_key.strip():
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid or missing API Key"}}, 401
key_info = VALID_API_KEYS.get(api_key.strip())
if key_info:
api_key_scopes = key_info.get('scopes', [])
if "admin" in api_key_scopes:
return True, None, None
elif all(scope in api_key_scopes for scope in required_scopes):
return True, None, None
else:
return False, {"error": {"code": "FORBIDDEN", "message": f"API key missing required scope(s): {required_scopes}"}}, 403
else:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid API Key"}}, 401
# Case 3: No Authorization header, API Key is expected but missing
elif not has_auth_header and endpoint_expects_api_key and not has_api_key:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Authentication required"}}, 401
# Case 4: No Authorization header, API Key not expected or not provided (and not expected)
# This implies that a bearer token or OAuth2 is required but not provided.
return False, {"error": {"code": "UNAUTHORIZED", "message": "Authentication required"}}, 401
# JWT validation (for Authorization header)
if auth_header.startswith('Bearer '):
token = auth_header[7:]
try:
# Decode JWT token (using the same secret as the test token generator)
payload = jwt.decode(token, "your-secret-key-change-in-production", algorithms=["HS256"])
# Check for scopes
token_scopes = payload.get('scopes', [])
if not isinstance(token_scopes, list):
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid token scopes format"}}, 401
# Validate scope format - check for None, empty strings, or invalid types
invalid_scopes = []
for scope in token_scopes:
if scope is None or (isinstance(scope, str) and not scope.strip()):
invalid_scopes.append(scope)
# Empty scopes list is also invalid for access control
if not token_scopes or invalid_scopes:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid or empty token scopes"}}, 401
# Check scope hierarchy (admin includes all scopes)
if "admin" in token_scopes:
# Admin has all permissions
return True, None, None
# Check if all required scopes are present
for scope in required_scopes:
if scope not in token_scopes:
return False, {"error": {"code": "FORBIDDEN", "message": f"Missing required scope: {scope}"}}, 403
return True, None, None
except jwt.ExpiredSignatureError:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Token has expired"}}, 401
except jwt.InvalidTokenError:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid token"}}, 401
except Exception as e:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Token validation failed"}}, 401
# No valid authentication method found
return False, {"error": {"code": "UNAUTHORIZED", "message": "Authentication required"}}, 401
# For Bearer tokens, validate scopes
auth_header = request.headers.get('Authorization', '')
if auth_header.startswith('Bearer '):
token = auth_header[7:]
try:
# Decode JWT token (using the same secret as the test token generator)
payload = jwt.decode(token, "your-secret-key-change-in-production", algorithms=["HS256"])
# Check for scopes
token_scopes = payload.get('scopes', [])
if not isinstance(token_scopes, list):
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid token scopes format"}}, 401
# Validate scope format - check for None, empty strings, or invalid types
invalid_scopes = []
for scope in token_scopes:
if scope is None or (isinstance(scope, str) and not scope.strip()):
invalid_scopes.append(scope)
# Empty scopes list is also invalid for access control
if not token_scopes or invalid_scopes:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid or empty token scopes"}}, 401
# Check scope hierarchy (admin includes all scopes)
if "admin" in token_scopes:
# Admin has all permissions
return True, None, None
# Check if all required scopes are present
for scope in required_scopes:
if scope not in token_scopes:
return False, {"error": {"code": "FORBIDDEN", "message": f"Missing required scope: {scope}"}}, 403
return True, None, None
except jwt.ExpiredSignatureError:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Token has expired"}}, 401
except jwt.InvalidTokenError:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Invalid token"}}, 401
except Exception as e:
return False, {"error": {"code": "UNAUTHORIZED", "message": "Token validation failed"}}, 401
# No valid authentication method found
return False, {"error": {"code": "UNAUTHORIZED", "message": "Authentication required"}}, 401
# ============================================================================
# INPUT VALIDATION
# ============================================================================
def convert_validation_errors_to_object(validation_errors):
"""Convert validation errors from array format to object format for OpenAPI compliance"""
details = {}
for error in validation_errors:
field = error.get('field', 'general')
message = error.get('message', 'Invalid value')
details[field] = message
return details
def validate_campaign_data(data):
"""Validate campaign creation data"""
errors = []
# Type validation - data must be a dict
if not isinstance(data, dict):
errors.append({"field": "request", "message": "Request body must be a JSON object"})
return errors
# Required fields validation
name = data.get('name', '')
if not name:
errors.append({"field": "name", "message": "Campaign name is required"})
elif not isinstance(name, str):
errors.append({"field": "name", "message": "Campaign name must be a string"})
elif len(name) > 255:
errors.append({"field": "name", "message": "Campaign name must be at most 255 characters"})
# Required fields for campaign creation
required_fields = ['name', 'whiteUrl', 'blackUrl', 'costModel', 'payout']
for field in required_fields:
if field not in data or data[field] is None:
errors.append({"field": field, "message": f"{field} is required"})
return validate_campaign_fields(data, errors)
def validate_campaign_update_data(data):
"""Validate campaign update data (no required fields)"""
errors = []
# Type validation - data must be a dict
if not isinstance(data, dict):
errors.append({"field": "request", "message": "Request body must be a JSON object"}), 400
return errors
# For updates, only validate provided fields
if 'name' in data and not data.get('name', '').strip():
errors.append({"field": "name", "message": "Campaign name cannot be empty"})
return validate_campaign_fields(data, errors)
def validate_pagination_params(request):
"""Validate pagination query parameters"""
errors = []
# Validate page
page_str = request.args.get("page")
if page_str is not None:
try:
page = int(page_str)
if page < 1:
errors.append({"field": "page", "message": "Page must be >= 1"})
except (ValueError, TypeError):
errors.append({"field": "page", "message": "Page must be a valid integer"})
# Validate pageSize
page_size_str = request.args.get("pageSize")
if page_size_str is not None:
try:
page_size = int(page_size_str)
if page_size < 1 or page_size > 100:
errors.append({"field": "pageSize", "message": "Page size must be between 1 and 100"})
except (ValueError, TypeError):
errors.append({"field": "pageSize", "message": "Page size must be a valid integer"})
# Validate sort (optional string)
sort = request.args.get("sort")
if sort is not None and not isinstance(sort, str):
errors.append({"field": "sort", "message": "Sort must be a string"})
# Validate filter (optional string)
filter_param = request.args.get("filter")
if filter_param is not None and not isinstance(filter_param, str):
errors.append({"field": "filter", "message": "Filter must be a string"})
return errors
def validate_analytics_params(request):
"""Validate analytics query parameters"""
errors = []
# Validate startDate
start_date = request.args.get("startDate")
if start_date is not None:
if not isinstance(start_date, str):
errors.append({"field": "startDate", "message": "Start date must be a string"})
elif not re.match(date_pattern, start_date):
errors.append({"field": "startDate", "message": "Start date must be a valid date string"})
# Validate endDate
end_date = request.args.get("endDate")
if end_date is not None:
if not isinstance(end_date, str):
errors.append({"field": "endDate", "message": "End date must be a string"})
elif not re.match(date_pattern, end_date):
errors.append({"field": "endDate", "message": "End date must be a valid date string"})
# Validate breakdown
breakdown = request.args.get("breakdown")
if breakdown is not None:
if not isinstance(breakdown, str):
errors.append({"field": "breakdown", "message": "Breakdown must be a string"})
elif breakdown not in ["date", "traffic_source", "landing_page", "offer", "geography", "device"]:
errors.append({"field": "breakdown", "message": "Breakdown must be one of: date, traffic_source, landing_page, offer, geography, device"})
# Validate granularity
granularity = request.args.get("granularity")
if granularity is not None:
if not isinstance(granularity, str):
errors.append({"field": "granularity", "message": "Granularity must be a string"})
elif granularity not in ["hour", "day", "week", "month"]:
errors.append({"field": "granularity", "message": "Granularity must be one of: hour, day, week, month"})
return errors
def validate_campaign_fields(data, errors):
"""Common validation logic for campaign fields"""
white_url = data.get('whiteUrl')
black_url = data.get('blackUrl')
if white_url is not None:
if not isinstance(white_url, str) or not white_url.startswith(('http://', 'https://')):
errors.append({"field": "whiteUrl", "message": "White URL must be a valid HTTP/HTTPS URL"})
if black_url is not None:
if not isinstance(black_url, str) or not black_url.startswith(('http://', 'https://')):
errors.append({"field": "blackUrl", "message": "Black URL must be a valid HTTP/HTTPS URL"})
cost_model = data.get('costModel')
if cost_model is not None:
if not isinstance(cost_model, str):
errors.append({"field": "costModel", "message": "Cost model must be a string"})
elif cost_model not in ['CPA', 'CPC', 'CPM']:
errors.append({"field": "costModel", "message": "Cost model must be CPA, CPC, or CPM"})
description = data.get('description')
if 'description' in data:
if description is None:
errors.append({"field": "description", "message": "Description cannot be null"})
elif not isinstance(description, str):
errors.append({"field": "description", "message": "Description must be a string"})
elif len(description) > 1000:
errors.append({"field": "description", "message": "Description must be at most 1000 characters"})
start_date = data.get('startDate')
if 'startDate' in data:
if start_date is None:
errors.append({"field": "startDate", "message": "Start date cannot be null"})
elif start_date == "":
errors.append({"field": "startDate", "message": "Start date cannot be empty"})
elif not isinstance(start_date, str):
errors.append({"field": "startDate", "message": "Start date must be a string"})
elif not re.match(date_time_pattern, start_date):
errors.append({"field": "startDate", "message": "Start date must be a valid date-time string"})
end_date = data.get('endDate')
if 'endDate' in data:
if end_date is None:
errors.append({"field": "endDate", "message": "End date cannot be null"})
elif end_date == "":
errors.append({"field": "endDate", "message": "End date cannot be empty"})
elif not isinstance(end_date, str):
errors.append({"field": "endDate", "message": "End date must be a string"})
elif not re.match(date_time_pattern, end_date):
errors.append({"field": "endDate", "message": "End date must be a valid date-time string"})
payout = data.get('payout')
if payout is not None:
if not isinstance(payout, dict):
errors.append({"field": "payout", "message": "Payout must be an object"})
else:
# Money schema requires both amount and currency
if 'amount' not in payout:
errors.append({"field": "payout", "message": "Payout amount is required"})
if 'currency' not in payout:
errors.append({"field": "payout", "message": "Payout currency is required"})
# Validate amount if present
if 'amount' in payout:
amount = payout.get('amount')
# Strict type checking - reject booleans and other non-numeric types
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
errors.append({"field": "payout.amount", "message": "Payout amount must be a number"})
elif isinstance(amount, float) and (amount == float('inf') or amount == float('-inf') or str(amount) == 'nan'):
errors.append({"field": "payout.amount", "message": "Payout amount must be a finite number"})
elif abs(amount) > 1e400: # Allow extremely large numbers for testing edge cases
errors.append({"field": "payout.amount", "message": "Payout amount is unreasonably large"})
# Validate currency if present
if 'currency' in payout:
currency = payout.get('currency')
if not isinstance(currency, str):
errors.append({"field": "payout.currency", "message": "Payout currency must be a string"})
# Check for extra properties in Money object (should only have amount and currency)
allowed_money_fields = {'amount', 'currency'}
extra_fields = set(payout.keys()) - allowed_money_fields
if extra_fields:
errors.append({"field": "payout", "message": f"Money object must not contain additional properties: {', '.join(extra_fields)}"})
# Validate dailyBudget if present
if 'dailyBudget' in data:
daily_budget = data['dailyBudget']
if daily_budget is None: # Explicitly reject null values
errors.append({"field": "dailyBudget", "message": "Daily budget cannot be null"})
elif not isinstance(daily_budget, dict):
errors.append({"field": "dailyBudget", "message": "Daily budget must be an object"})
else:
# Money schema requires both amount and currency
if 'amount' in daily_budget:
amount = daily_budget.get('amount')
# Strict type checking - reject booleans and other non-numeric types
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
errors.append({"field": "dailyBudget.amount", "message": "Daily budget amount must be a number"})
elif isinstance(amount, float) and (amount == float('inf') or amount == float('-inf') or str(amount) == 'nan'):
errors.append({"field": "dailyBudget.amount", "message": "Daily budget amount must be a finite number"})
elif abs(amount) > 1e400:
errors.append({"field": "dailyBudget.amount", "message": "Daily budget amount is unreasonably large"})
# If amount is present, currency must also be present
if 'currency' not in daily_budget:
errors.append({"field": "dailyBudget", "message": "Daily budget currency is required when amount is provided"})
else:
currency = daily_budget.get('currency')
if not isinstance(currency, str):
errors.append({"field": "dailyBudget.currency", "message": "Daily budget currency must be a string"})
elif 'currency' in daily_budget:
# If currency is present without amount, that's also invalid for Money schema
errors.append({"field": "dailyBudget", "message": "Daily budget amount is required when currency is provided"})
# Check for extra properties in Money object (should only have amount and currency)
allowed_money_fields = {'amount', 'currency'}
extra_fields = set(daily_budget.keys()) - allowed_money_fields
if extra_fields:
errors.append({"field": "dailyBudget", "message": f"Money object must not contain additional properties: {', '.join(extra_fields)}"})
# Validate totalBudget if present
if 'totalBudget' in data:
total_budget = data['totalBudget']
if total_budget is None: # Explicitly reject null values
errors.append({"field": "totalBudget", "message": "Total budget cannot be null"})
elif not isinstance(total_budget, dict):
errors.append({"field": "totalBudget", "message": "Total budget must be an object"})
else:
# Money schema requires both amount and currency
if 'amount' in total_budget:
amount = total_budget.get('amount')
# Strict type checking - reject booleans and other non-numeric types
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
errors.append({"field": "totalBudget.amount", "message": "Total budget amount must be a number"})
elif isinstance(amount, float) and (amount == float('inf') or amount == float('-inf') or str(amount) == 'nan'):
errors.append({"field": "totalBudget.amount", "message": "Total budget amount must be a finite number"})
elif abs(amount) > 1e400:
errors.append({"field": "totalBudget.amount", "message": "Total budget amount is unreasonably large"})
# If amount is present, currency must also be present
if 'currency' not in total_budget:
errors.append({"field": "totalBudget", "message": "Total budget currency is required when amount is provided"})
else:
currency = total_budget.get('currency')
if not isinstance(currency, str):
errors.append({"field": "totalBudget.currency", "message": "Total budget currency must be a string"})
elif 'currency' in total_budget:
# If currency is present without amount, that's also invalid for Money schema
errors.append({"field": "totalBudget", "message": "Total budget amount is required when currency is provided"})
# Check for extra properties in Money object (should only have amount and currency)
allowed_money_fields = {'amount', 'currency'}
extra_fields = set(total_budget.keys()) - allowed_money_fields
if extra_fields:
errors.append({"field": "totalBudget", "message": f"Money object must not contain additional properties: {', '.join(extra_fields)}"})
return errors
def validate_landing_page_data(data):
"""Validate landing page data"""
errors = []
# Required fields validation
if not data.get('name', '').strip():
errors.append({"field": "name", "message": "Landing page name is required"})
if 'url' not in data or not data.get('url', '').strip():
errors.append({"field": "url", "message": "Landing page URL is required"})
if 'pageType' not in data or not data.get('pageType', '').strip():
errors.append({"field": "pageType", "message": "Landing page type is required"})
# Additional validation
url = data.get('url', '')
if url and (not isinstance(url, str) or not url.startswith(('http://', 'https://'))):
errors.append({"field": "url", "message": "URL must be a valid HTTP/HTTPS URL"})
page_type = data.get('pageType', '')
if page_type and page_type not in ['direct', 'squeeze', 'bridge', 'thank_you']:
errors.append({"field": "pageType", "message": "Invalid page type"})
weight = data.get('weight', 100)
if not isinstance(weight, int) or not (0 <= weight <= 100):
errors.append({"field": "weight", "message": "Weight must be an integer between 0 and 100"})
return errors
# ============================================================================
# MOCK DATA GENERATORS
# ============================================================================
def generate_campaign_id():
return f"camp_{random.randint(1000, 9999)}"
def generate_landing_page_id():
return f"lp_{random.randint(1000, 9999)}"
def generate_offer_id():
return f"offer_{random.randint(1000, 9999)}"
def generate_money(amount=None):
if amount is None: