-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmcp_prompts.py
More file actions
1421 lines (1244 loc) · 48.9 KB
/
mcp_prompts.py
File metadata and controls
1421 lines (1244 loc) · 48.9 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
# Copyright (c) 2025 Jascha Wanger / Tarnover, LLC
# SPDX-License-Identifier: MIT
#
# This file is part of the MockLoop project. (https://mockloop.com)
# You may obtain a copy of the license at https://opensource.org/licenses/MIT
"""
MCP Prompts Module for AI-driven scenario generation.
This module provides MCP prompts that enable AI agents to generate test scenarios
dynamically based on OpenAPI specifications. All prompts are integrated with the
comprehensive audit logging infrastructure for regulatory compliance.
Features:
- OpenAPI analysis for testable scenario identification
- Dynamic scenario configuration generation
- Performance optimization for load testing
- Error simulation scenario creation
- Security testing scenario generation
- Full audit logging integration
- JSON schema validation for outputs
"""
import logging
import time
from functools import wraps
from typing import Any
from datetime import datetime
# Handle imports for different execution contexts
if __package__ is None or __package__ == "":
from mcp_audit_logger import create_audit_logger
else:
from .mcp_audit_logger import create_audit_logger
# Import FastMCP for prompt decorators
# Configure logger for this module
logger = logging.getLogger(__name__)
# JSON Schema definitions for prompt outputs
SCENARIO_CONFIG_SCHEMA = {
"type": "object",
"properties": {
"scenario_name": {"type": "string"},
"description": {"type": "string"},
"scenario_type": {
"type": "string",
"enum": [
"load_testing",
"error_simulation",
"security_testing",
"functional_testing",
],
},
"endpoints": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": {"type": "string"},
"method": {"type": "string"},
"response_config": {
"type": "object",
"properties": {
"status_code": {"type": "integer"},
"response_time_ms": {"type": "integer"},
"response_data": {"type": "object"},
"headers": {"type": "object"},
},
"required": ["status_code"],
},
},
"required": ["path", "method", "response_config"],
},
},
"test_parameters": {
"type": "object",
"properties": {
"concurrent_users": {"type": "integer"},
"duration_seconds": {"type": "integer"},
"ramp_up_time": {"type": "integer"},
"error_rate_threshold": {"type": "number"},
},
},
"validation_rules": {
"type": "array",
"items": {
"type": "object",
"properties": {
"rule_type": {"type": "string"},
"condition": {"type": "string"},
"expected_value": {"type": ["string", "number", "boolean"]},
},
},
},
},
"required": ["scenario_name", "description", "scenario_type", "endpoints"],
}
OPENAPI_ANALYSIS_SCHEMA = {
"type": "object",
"properties": {
"api_summary": {
"type": "object",
"properties": {
"title": {"type": "string"},
"version": {"type": "string"},
"total_endpoints": {"type": "integer"},
"authentication_methods": {
"type": "array",
"items": {"type": "string"},
},
"data_models": {"type": "array", "items": {"type": "string"}},
},
},
"testable_scenarios": {
"type": "array",
"items": {
"type": "object",
"properties": {
"scenario_type": {"type": "string"},
"priority": {"type": "string", "enum": ["high", "medium", "low"]},
"description": {"type": "string"},
"endpoints_involved": {
"type": "array",
"items": {"type": "string"},
},
"test_complexity": {
"type": "string",
"enum": ["simple", "moderate", "complex"],
},
"estimated_duration": {"type": "string"},
},
},
},
"risk_areas": {
"type": "array",
"items": {
"type": "object",
"properties": {
"area": {"type": "string"},
"risk_level": {
"type": "string",
"enum": ["low", "medium", "high", "critical"],
},
"description": {"type": "string"},
"mitigation_suggestions": {
"type": "array",
"items": {"type": "string"},
},
},
},
},
},
"required": ["api_summary", "testable_scenarios", "risk_areas"],
}
def mcp_prompt_audit(prompt_name: str):
"""
Decorator to add MCP audit logging to prompt functions.
Args:
prompt_name: Name of the MCP prompt being audited
"""
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
audit_logger = create_audit_logger(
db_path="mcp_audit.db",
session_id=f"mcp_prompt_{prompt_name}",
user_id="mcp_system",
)
start_time = time.time()
entry_id = None
try:
# Log prompt invocation start
if audit_logger:
entry_id = audit_logger.log_prompt_invocation(
prompt_name=prompt_name,
input_parameters=kwargs,
data_sources=["openapi_specification"],
compliance_tags=["mcp_prompt", "ai_generation"],
processing_purpose="ai_scenario_generation",
legal_basis="legitimate_interests",
)
# Execute the original function
result = await func(*args, **kwargs)
# Log successful completion
if audit_logger and entry_id:
execution_time_ms = (time.time() - start_time) * 1000
audit_logger.log_prompt_invocation(
prompt_name=f"{prompt_name}_completion",
input_parameters={"original_entry_id": entry_id},
generated_output=result,
execution_time_ms=execution_time_ms,
data_sources=["openapi_specification"],
compliance_tags=["mcp_prompt", "ai_generation", "completion"],
processing_purpose="ai_scenario_generation_completion",
legal_basis="legitimate_interests",
)
return result
except Exception as e:
# Log error
if audit_logger and entry_id:
execution_time_ms = (time.time() - start_time) * 1000
audit_logger.log_prompt_invocation(
prompt_name=f"{prompt_name}_error",
input_parameters={"original_entry_id": entry_id},
generated_output={"error": str(e)},
execution_time_ms=execution_time_ms,
data_sources=["openapi_specification"],
compliance_tags=["mcp_prompt", "ai_generation", "error"],
processing_purpose="ai_scenario_generation_error",
legal_basis="legitimate_interests",
)
raise
return wrapper
return decorator
def validate_json_schema(
data: dict[str, Any], schema: dict[str, Any]
) -> tuple[bool, str | None]:
"""
Validate JSON data against a schema.
Args:
data: JSON data to validate
schema: JSON schema to validate against
Returns:
Tuple of (is_valid, error_message)
"""
try:
import jsonschema
jsonschema.validate(data, schema)
return True, None
except ImportError:
# Fallback validation without jsonschema
logger.warning("jsonschema not available, performing basic validation")
return _basic_schema_validation(data, schema)
except Exception as e:
return False, str(e)
def _basic_schema_validation(
data: dict[str, Any], schema: dict[str, Any]
) -> tuple[bool, str | None]:
"""
Basic schema validation fallback when jsonschema is not available.
Args:
data: JSON data to validate
schema: JSON schema to validate against
Returns:
Tuple of (is_valid, error_message)
"""
try:
# Check required fields
if "required" in schema:
for field in schema["required"]:
if field not in data:
return False, f"Missing required field: {field}"
# Check field types
if "properties" in schema:
for field, field_schema in schema["properties"].items():
if field in data:
expected_type = field_schema.get("type")
if expected_type == "string" and not isinstance(data[field], str):
return False, f"Field {field} must be a string"
elif expected_type == "integer" and not isinstance(
data[field], int
):
return False, f"Field {field} must be an integer"
elif expected_type == "array" and not isinstance(data[field], list):
return False, f"Field {field} must be an array"
elif expected_type == "object" and not isinstance(
data[field], dict
):
return False, f"Field {field} must be an object"
return True, None
except Exception as e:
return False, str(e)
# MCP Prompt Functions
@mcp_prompt_audit("analyze_openapi_for_testing")
async def analyze_openapi_for_testing(
openapi_spec: dict[str, Any],
testing_focus: str = "comprehensive",
risk_assessment: bool = True,
) -> dict[str, Any]:
"""
Analyze an OpenAPI specification to identify testable scenarios and risk areas.
This prompt analyzes the provided OpenAPI specification and generates a comprehensive
report of testable scenarios, risk areas, and testing recommendations.
Args:
openapi_spec: The OpenAPI specification to analyze
testing_focus: Focus area for testing ("performance", "security", "functional", "comprehensive")
risk_assessment: Whether to include risk assessment in the analysis
Returns:
Structured analysis with testable scenarios and risk areas
"""
try:
# Extract basic API information
info = openapi_spec.get("info", {})
paths = openapi_spec.get("paths", {})
components = openapi_spec.get("components", {})
security = openapi_spec.get("security", [])
# Analyze API structure
api_summary = {
"title": info.get("title", "Unknown API"),
"version": info.get("version", "1.0.0"),
"total_endpoints": len(paths),
"authentication_methods": _extract_auth_methods(security, components),
"data_models": list(components.get("schemas", {}).keys()),
}
# Generate testable scenarios based on endpoints
testable_scenarios = []
# Functional testing scenarios
if testing_focus in ["functional", "comprehensive"]:
testable_scenarios.extend(_generate_functional_scenarios(paths))
# Performance testing scenarios
if testing_focus in ["performance", "comprehensive"]:
testable_scenarios.extend(_generate_performance_scenarios(paths))
# Security testing scenarios
if testing_focus in ["security", "comprehensive"]:
testable_scenarios.extend(_generate_security_scenarios(paths, security))
# Risk assessment
risk_areas = []
if risk_assessment:
risk_areas = _assess_api_risks(openapi_spec)
result = {
"api_summary": api_summary,
"testable_scenarios": testable_scenarios,
"risk_areas": risk_areas,
}
# Validate result against schema
is_valid, error = validate_json_schema(result, OPENAPI_ANALYSIS_SCHEMA)
if not is_valid:
logger.warning(f"Generated analysis failed schema validation: {error}")
# Return a minimal valid structure
result = {
"api_summary": api_summary,
"testable_scenarios": [
{
"scenario_type": "basic_functional",
"priority": "high",
"description": "Basic endpoint functionality testing",
"endpoints_involved": list(paths.keys())[:5],
"test_complexity": "simple",
"estimated_duration": "30 minutes",
}
],
"risk_areas": [
{
"area": "general_testing",
"risk_level": "medium",
"description": "General API testing required",
"mitigation_suggestions": [
"Implement comprehensive test suite"
],
}
],
}
return result
except Exception as e:
logger.exception("Error analyzing OpenAPI specification")
# Return minimal valid structure on error
return {
"api_summary": {
"title": "Error in Analysis",
"version": "1.0.0",
"total_endpoints": 0,
"authentication_methods": [],
"data_models": [],
},
"testable_scenarios": [
{
"scenario_type": "error_recovery",
"priority": "high",
"description": "Analysis failed, manual testing required",
"endpoints_involved": [],
"test_complexity": "complex",
"estimated_duration": "Manual assessment needed",
}
],
"risk_areas": [
{
"area": "analysis_failure",
"risk_level": "high",
"description": f"Automated analysis failed: {e!s}",
"mitigation_suggestions": ["Manual specification review required"],
}
],
}
@mcp_prompt_audit("generate_scenario_config")
async def generate_scenario_config(
scenario_type: str,
endpoints: list[dict[str, Any]],
test_parameters: dict[str, Any] | None = None,
scenario_name: str | None = None,
) -> dict[str, Any]:
"""
Generate a specific scenario configuration for MockLoop testing.
This prompt creates detailed scenario configurations that can be directly
used with MockLoop servers for dynamic testing scenarios.
Args:
scenario_type: Type of scenario ("load_testing", "error_simulation", "security_testing", "functional_testing")
endpoints: List of endpoint configurations
test_parameters: Optional test parameters for the scenario
scenario_name: Optional custom name for the scenario
Returns:
Complete scenario configuration ready for MockLoop
"""
try:
# Generate scenario name if not provided
if not scenario_name:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
scenario_name = f"{scenario_type}_{timestamp}"
# Set default test parameters based on scenario type
if not test_parameters:
test_parameters = _get_default_test_parameters(scenario_type)
# Process endpoints and generate response configurations
processed_endpoints = []
for endpoint in endpoints:
processed_endpoint = _process_endpoint_for_scenario(endpoint, scenario_type)
processed_endpoints.append(processed_endpoint)
# Generate validation rules
validation_rules = _generate_validation_rules(
scenario_type, processed_endpoints
)
# Create scenario configuration
scenario_config = {
"scenario_name": scenario_name,
"description": _generate_scenario_description(
scenario_type, len(processed_endpoints)
),
"scenario_type": scenario_type,
"endpoints": processed_endpoints,
"test_parameters": test_parameters,
"validation_rules": validation_rules,
}
# Validate result against schema
is_valid, error = validate_json_schema(scenario_config, SCENARIO_CONFIG_SCHEMA)
if not is_valid:
logger.warning(
f"Generated scenario config failed schema validation: {error}"
)
# Fix common validation issues
scenario_config = _fix_scenario_config(scenario_config)
return scenario_config
except Exception as e:
logger.exception("Error generating scenario configuration")
# Return minimal valid configuration on error
return {
"scenario_name": scenario_name or "error_scenario",
"description": f"Error generating scenario: {e!s}",
"scenario_type": scenario_type,
"endpoints": [
{
"path": "/health",
"method": "GET",
"response_config": {
"status_code": 200,
"response_time_ms": 100,
"response_data": {"status": "ok"},
"headers": {"Content-Type": "application/json"},
},
}
],
"test_parameters": {
"concurrent_users": 1,
"duration_seconds": 60,
"ramp_up_time": 10,
"error_rate_threshold": 0.05,
},
"validation_rules": [],
}
@mcp_prompt_audit("optimize_scenario_for_load")
async def optimize_scenario_for_load(
base_scenario: dict[str, Any],
target_load: int,
performance_requirements: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
Optimize a scenario configuration for load testing performance.
This prompt takes a base scenario and optimizes it for high-load testing
by adjusting response times, concurrency settings, and resource usage.
Args:
base_scenario: Base scenario configuration to optimize
target_load: Target number of concurrent users
performance_requirements: Optional performance requirements
Returns:
Optimized scenario configuration for load testing
"""
try:
# Copy base scenario
optimized_scenario = base_scenario.copy()
# Set default performance requirements
if not performance_requirements:
performance_requirements = {
"max_response_time_ms": 2000,
"target_throughput_rps": target_load * 2,
"error_rate_threshold": 0.01,
"memory_usage_limit_mb": 1024,
}
# Optimize test parameters for load
optimized_scenario["test_parameters"] = {
"concurrent_users": target_load,
"duration_seconds": max(300, target_load * 2), # Scale duration with load
"ramp_up_time": max(60, target_load // 10), # Gradual ramp-up
"error_rate_threshold": performance_requirements.get(
"error_rate_threshold", 0.01
),
}
# Optimize endpoint configurations
optimized_endpoints = []
for endpoint in optimized_scenario.get("endpoints", []):
optimized_endpoint = _optimize_endpoint_for_load(
endpoint, target_load, performance_requirements
)
optimized_endpoints.append(optimized_endpoint)
optimized_scenario["endpoints"] = optimized_endpoints
# Update scenario metadata
optimized_scenario["scenario_name"] = (
f"load_optimized_{optimized_scenario.get('scenario_name', 'scenario')}"
)
optimized_scenario["description"] = (
f"Load-optimized scenario for {target_load} concurrent users"
)
optimized_scenario["scenario_type"] = "load_testing"
# Add load-specific validation rules
load_validation_rules = [
{
"rule_type": "response_time",
"condition": "max_response_time_ms",
"expected_value": performance_requirements.get(
"max_response_time_ms", 2000
),
},
{
"rule_type": "throughput",
"condition": "min_requests_per_second",
"expected_value": performance_requirements.get(
"target_throughput_rps", target_load
),
},
{
"rule_type": "error_rate",
"condition": "max_error_rate",
"expected_value": performance_requirements.get(
"error_rate_threshold", 0.01
),
},
]
optimized_scenario["validation_rules"] = load_validation_rules
# Validate result
is_valid, error = validate_json_schema(
optimized_scenario, SCENARIO_CONFIG_SCHEMA
)
if not is_valid:
logger.warning(f"Optimized scenario failed schema validation: {error}")
optimized_scenario = _fix_scenario_config(optimized_scenario)
return optimized_scenario
except Exception:
logger.exception("Error optimizing scenario for load")
# Return the base scenario with minimal load optimizations
fallback_scenario = base_scenario.copy()
fallback_scenario["test_parameters"] = {
"concurrent_users": target_load,
"duration_seconds": 300,
"ramp_up_time": 60,
"error_rate_threshold": 0.05,
}
return fallback_scenario
@mcp_prompt_audit("generate_error_scenarios")
async def generate_error_scenarios(
api_endpoints: list[dict[str, Any]],
error_types: list[str] | None = None,
severity_level: str = "medium",
) -> dict[str, Any]:
"""
Generate error simulation scenarios for testing error handling.
This prompt creates scenarios that simulate various error conditions
to test API resilience and error handling capabilities.
Args:
api_endpoints: List of API endpoints to test
error_types: Optional list of specific error types to simulate
severity_level: Severity level of errors ("low", "medium", "high")
Returns:
Error simulation scenario configuration
"""
try:
# Default error types if not specified
if not error_types:
error_types = _get_default_error_types(severity_level)
# Generate error endpoints
error_endpoints = []
for endpoint in api_endpoints:
for error_type in error_types:
error_endpoint = _create_error_endpoint(
endpoint, error_type, severity_level
)
error_endpoints.append(error_endpoint)
# Create error scenario configuration
scenario_name = f"error_simulation_{severity_level}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
error_scenario = {
"scenario_name": scenario_name,
"description": f"Error simulation scenario with {severity_level} severity errors",
"scenario_type": "error_simulation",
"endpoints": error_endpoints,
"test_parameters": {
"concurrent_users": 10,
"duration_seconds": 180,
"ramp_up_time": 30,
"error_rate_threshold": 1.0, # Expect errors in this scenario
},
"validation_rules": [
{
"rule_type": "error_handling",
"condition": "proper_error_responses",
"expected_value": True,
},
{
"rule_type": "response_format",
"condition": "valid_error_format",
"expected_value": True,
},
],
}
# Validate result
is_valid, error = validate_json_schema(error_scenario, SCENARIO_CONFIG_SCHEMA)
if not is_valid:
logger.warning(f"Error scenario failed schema validation: {error}")
error_scenario = _fix_scenario_config(error_scenario)
return error_scenario
except Exception:
logger.exception("Error generating error scenarios")
# Return minimal error scenario
return {
"scenario_name": "basic_error_simulation",
"description": "Basic error simulation scenario",
"scenario_type": "error_simulation",
"endpoints": [
{
"path": "/error-test",
"method": "GET",
"response_config": {
"status_code": 500,
"response_time_ms": 100,
"response_data": {"error": "Internal server error"},
"headers": {"Content-Type": "application/json"},
},
}
],
"test_parameters": {
"concurrent_users": 5,
"duration_seconds": 60,
"ramp_up_time": 10,
"error_rate_threshold": 1.0,
},
"validation_rules": [],
}
@mcp_prompt_audit("generate_security_test_scenarios")
async def generate_security_test_scenarios(
api_spec: dict[str, Any],
security_focus: list[str] | None = None,
compliance_requirements: list[str] | None = None,
) -> dict[str, Any]:
"""
Generate security testing scenarios for API vulnerability assessment.
This prompt creates scenarios that test for common security vulnerabilities
and compliance with security standards.
Args:
api_spec: OpenAPI specification to analyze for security testing
security_focus: Optional list of security areas to focus on
compliance_requirements: Optional list of compliance standards to test
Returns:
Security testing scenario configuration
"""
try:
# Default security focus areas
if not security_focus:
security_focus = [
"authentication",
"authorization",
"input_validation",
"rate_limiting",
"data_exposure",
]
# Extract security-relevant information from API spec
paths = api_spec.get("paths", {})
security_schemes = api_spec.get("components", {}).get("securitySchemes", {})
global_security = api_spec.get("security", [])
# Generate security test endpoints
security_endpoints = []
for focus_area in security_focus:
endpoints = _generate_security_endpoints_for_area(
focus_area, paths, security_schemes, global_security
)
security_endpoints.extend(endpoints)
# Create security scenario configuration
scenario_name = f"security_test_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
security_scenario = {
"scenario_name": scenario_name,
"description": f"Security testing scenario covering: {', '.join(security_focus)}",
"scenario_type": "security_testing",
"endpoints": security_endpoints,
"test_parameters": {
"concurrent_users": 5,
"duration_seconds": 300,
"ramp_up_time": 60,
"error_rate_threshold": 0.8, # Expect many security-related errors
},
"validation_rules": _generate_security_validation_rules(
security_focus, compliance_requirements
),
}
# Validate result
is_valid, error = validate_json_schema(
security_scenario, SCENARIO_CONFIG_SCHEMA
)
if not is_valid:
logger.warning(f"Security scenario failed schema validation: {error}")
security_scenario = _fix_scenario_config(security_scenario)
return security_scenario
except Exception:
logger.exception("Error generating security test scenarios")
# Return minimal security scenario
return {
"scenario_name": "basic_security_test",
"description": "Basic security testing scenario",
"scenario_type": "security_testing",
"endpoints": [
{
"path": "/unauthorized-test",
"method": "GET",
"response_config": {
"status_code": 401,
"response_time_ms": 100,
"response_data": {"error": "Unauthorized"},
"headers": {"Content-Type": "application/json"},
},
}
],
"test_parameters": {
"concurrent_users": 3,
"duration_seconds": 120,
"ramp_up_time": 30,
"error_rate_threshold": 0.9,
},
"validation_rules": [],
}
# Helper functions for prompt implementations
def _extract_auth_methods(security: list[dict], components: dict) -> list[str]:
"""Extract authentication methods from OpenAPI security configuration."""
auth_methods = []
security_schemes = components.get("securitySchemes", {})
for scheme_name, scheme_config in security_schemes.items():
scheme_type = scheme_config.get("type", "unknown")
auth_methods.append(f"{scheme_name} ({scheme_type})")
return auth_methods
def _generate_functional_scenarios(paths: dict) -> list[dict]:
"""Generate functional testing scenarios from API paths."""
scenarios = []
# Basic CRUD operations scenario
crud_endpoints = []
for path, methods in paths.items():
for method in methods:
if method.upper() in ["GET", "POST", "PUT", "DELETE"]:
crud_endpoints.append(f"{method.upper()} {path}")
if crud_endpoints:
scenarios.append(
{
"scenario_type": "crud_operations",
"priority": "high",
"description": "Test basic CRUD operations across all endpoints",
"endpoints_involved": crud_endpoints[:10], # Limit to first 10
"test_complexity": "moderate",
"estimated_duration": "45 minutes",
}
)
# Data validation scenario
post_put_endpoints = []
for path, methods in paths.items():
for method in methods:
if method.upper() in ["POST", "PUT", "PATCH"]:
post_put_endpoints.append(f"{method.upper()} {path}")
if post_put_endpoints:
scenarios.append(
{
"scenario_type": "data_validation",
"priority": "medium",
"description": "Test input validation and data integrity",
"endpoints_involved": post_put_endpoints[:5],
"test_complexity": "moderate",
"estimated_duration": "30 minutes",
}
)
return scenarios
def _generate_performance_scenarios(paths: dict) -> list[dict]:
"""Generate performance testing scenarios from API paths."""
scenarios = []
# High-frequency endpoints
get_endpoints = []
for path, methods in paths.items():
if "get" in methods:
get_endpoints.append(f"GET {path}")
if get_endpoints:
scenarios.append(
{
"scenario_type": "load_testing",
"priority": "high",
"description": "Load testing for high-frequency read operations",
"endpoints_involved": get_endpoints[:5],
"test_complexity": "complex",
"estimated_duration": "60 minutes",
}
)
# Stress testing scenario
scenarios.append(
{
"scenario_type": "stress_testing",
"priority": "medium",
"description": "Stress testing to find breaking points",
"endpoints_involved": list(paths.keys())[:3],
"test_complexity": "complex",
"estimated_duration": "90 minutes",
}
)
return scenarios
def _generate_security_scenarios(paths: dict, security: list) -> list[dict]:
"""Generate security testing scenarios from API paths and security config."""
scenarios = []
# Authentication testing
if security:
scenarios.append(
{
"scenario_type": "authentication_testing",
"priority": "high",
"description": "Test authentication mechanisms and unauthorized access",
"endpoints_involved": list(paths.keys())[:5],
"test_complexity": "moderate",
"estimated_duration": "45 minutes",
}
)
# Input validation security
post_endpoints = [
path
for path in paths
if any(method in ["post", "put", "patch"] for method in paths[path])
]
if post_endpoints:
scenarios.append(
{
"scenario_type": "input_security_testing",
"priority": "high",
"description": "Test for injection attacks and malicious input handling",
"endpoints_involved": post_endpoints[:5],
"test_complexity": "moderate",
"estimated_duration": "30 minutes",
}
)
return scenarios
def _assess_api_risks(openapi_spec: dict[str, Any]) -> list[dict[str, Any]]:
"""Assess API risks based on OpenAPI specification."""
risks = []
paths = openapi_spec.get("paths", {})
security = openapi_spec.get("security", [])
components = openapi_spec.get("components", {})
# Check for missing authentication
if not security and not components.get("securitySchemes"):
risks.append(
{
"area": "authentication",
"risk_level": "high",
"description": "No authentication mechanisms defined",
"mitigation_suggestions": [
"Implement authentication",
"Add security schemes",
],
}
)
# Check for sensitive data exposure
for path in paths:
if any(
sensitive in path.lower()
for sensitive in ["password", "token", "secret", "key"]
):
risks.append(