Yaswanth-Bolla commited on
Commit
d46032a
·
1 Parent(s): 289aa0d

Added endpoints for both the features

Browse files
Files changed (3) hide show
  1. .gitignore +4 -1
  2. README.md +424 -10
  3. app.py +323 -2
.gitignore CHANGED
@@ -1 +1,4 @@
1
- .env
 
 
 
 
1
+ .env
2
+ .venv
3
+ __pycache__
4
+ *.pyc
README.md CHANGED
@@ -1,11 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
- title: Ey Catalyst
3
- emoji: 📊
4
- colorFrom: yellow
5
- colorTo: purple
6
- sdk: docker
7
- pinned: false
8
- license: mit
9
- ---
10
- See if push works
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ # EY Catalyst - Business Impact Assessment & Risk Management API
2
+
3
+ An advanced AI-powered FastAPI application for Business Impact Assessment (BIA), threat identification, and risk mitigation analysis. This tool helps organizations identify, assess, and mitigate risks across their business processes using sophisticated AI models.
4
+
5
+ ## 🚀 Features
6
+
7
+ - **Process Risk Assessment**: Generate comprehensive threat analyses for business processes
8
+ - **Risk Mitigation Planning**: Create actionable mitigation strategies with revised risk ratings
9
+ - **Geographic Threat Assessment**: Analyze location-specific threats and risks
10
+ - **AI-Powered Analysis**: Uses advanced language models (Groq/Llama) for intelligent risk assessment
11
+ - **RESTful API**: Easy integration with existing systems and frontends
12
+ - **Interactive Documentation**: Built-in Swagger UI for API exploration
13
+
14
+ ## 📋 Table of Contents
15
+
16
+ - [Installation](#installation)
17
+ - [Configuration](#configuration)
18
+ - [API Endpoints](#api-endpoints)
19
+ - [Use Cases](#use-cases)
20
+ - [Request/Response Examples](#requestresponse-examples)
21
+ - [Error Handling](#error-handling)
22
+ - [Contributing](#contributing)
23
+
24
+ ## 🛠️ Installation
25
+
26
+ ### Prerequisites
27
+
28
+ - Python 3.8+
29
+ - GROQ API Key (for AI model access)
30
+
31
+ ### Setup
32
+
33
+ 1. **Clone the repository**
34
+ ```bash
35
+ git clone <repository-url>
36
+ cd ey-catalyst
37
+ ```
38
+
39
+ 2. **Install dependencies**
40
+ ```bash
41
+ pip install -r requirements.txt
42
+ ```
43
+
44
+ 3. **Set environment variables**
45
+ ```bash
46
+ export GROQ_API_KEY=your_groq_api_key_here
47
+ ```
48
+
49
+ 4. **Run the application**
50
+ ```bash
51
+ uvicorn app:app --reload --port 8000
52
+ ```
53
+
54
+ 5. **Access the API**
55
+ - API Documentation: http://localhost:8000/docs
56
+ - Base URL: http://localhost:8000
57
+
58
+ ## ⚙️ Configuration
59
+
60
+ ### Environment Variables
61
+
62
+ | Variable | Description | Required |
63
+ |----------|-------------|----------|
64
+ | `GROQ_API_KEY` | API key for Groq language model service | Yes |
65
+
66
+ ### Supported Models
67
+
68
+ - **llama3-8b-8192**: Primary model for risk analysis and threat assessment
69
+
70
+ ## 🔗 API Endpoints
71
+
72
+ ### 1. Process Threat Generation
73
+
74
+ **Endpoint**: `POST /api/generate-threats`
75
+
76
+ Generates comprehensive threat assessments for business processes.
77
+
78
+ **Use Cases**:
79
+ - Business continuity planning
80
+ - Risk register development
81
+ - Process vulnerability assessment
82
+ - Compliance risk analysis
83
+
84
+ **Request Body**:
85
+ ```json
86
+ {
87
+ "processName": "Financial Transaction Processing",
88
+ "department": "Finance",
89
+ "description": "Handles all daily banking transactions",
90
+ "owner": "John Doe",
91
+ "businessContext": "Supports daily liquidity tracking",
92
+ "rto": "1hour",
93
+ "mtpd": "24hours",
94
+ "minTolerableDowntime": "15minutes"
95
+ }
96
+ ```
97
+
98
+ **Response**:
99
+ ```json
100
+ {
101
+ "threats": [
102
+ {
103
+ "id": 1,
104
+ "name": "Cyber Attack",
105
+ "description": "Malicious attack disrupting core operations",
106
+ "likelihood": 3,
107
+ "impact": 4,
108
+ "category": "Security",
109
+ "mitigation": "Use firewalls and real-time monitoring"
110
+ }
111
+ ]
112
+ }
113
+ ```
114
+
115
+ ### 2. Risk Mitigation Analysis
116
+
117
+ **Endpoint**: `POST /api/risk-mitigation`
118
+
119
+ Provides mitigation strategies and revised risk assessments for identified threats.
120
+
121
+ **Use Cases**:
122
+ - Risk treatment planning
123
+ - Control effectiveness assessment
124
+ - Residual risk calculation
125
+ - Mitigation cost-benefit analysis
126
+
127
+ **Request Body**:
128
+ ```json
129
+ [
130
+ {
131
+ "enablerType": "Technology",
132
+ "enablerDomain": "Hardware",
133
+ "majorCategory": "Fire",
134
+ "mappedThreat": "Fire at HQ",
135
+ "existingControls": "Data centre equipped with handheld fire extinguishers",
136
+ "complianceStatus": "Yes, inspected monthly and tagged",
137
+ "impact": "4",
138
+ "likelihood": "3",
139
+ "riskValue": "12"
140
+ }
141
+ ]
142
+ ```
143
+
144
+ **Response**:
145
+ ```json
146
+ {
147
+ "mitigatedRisks": [
148
+ {
149
+ "revisedImpact": 2,
150
+ "revisedLikelihood": 2,
151
+ "revisedRiskValue": 4,
152
+ "mitigationPlan": "• Install fire suppression systems • Conduct quarterly training • Implement monitoring alerts",
153
+ "ownership": "Facilities Management Team"
154
+ }
155
+ ]
156
+ }
157
+ ```
158
+
159
+ ### 3. Geographic Threat Assessment
160
+
161
+ **Endpoint**: `POST /bia/threat-assessment`
162
+
163
+ Analyzes location-specific threats and geopolitical risks.
164
+
165
+ **Use Cases**:
166
+ - International expansion risk assessment
167
+ - Supply chain geographical risk analysis
168
+ - Office location security evaluation
169
+ - Political stability assessment
170
+
171
+ **Request Body**:
172
+ ```json
173
+ {
174
+ "message": "Our company is planning to establish operations in Southeast Asia, specifically in Singapore and Bangkok."
175
+ }
176
+ ```
177
+
178
+ **Response**:
179
+ ```json
180
+ {
181
+ "place": "Southeast Asia (Singapore, Bangkok)",
182
+ "threats": [
183
+ {
184
+ "name": "Political Instability",
185
+ "likelihood": 2,
186
+ "severity": 4,
187
+ "impact": "Potential disruption to business operations",
188
+ "threat_rating": 8
189
+ }
190
+ ]
191
+ }
192
+ ```
193
+
194
+ ### 4. Impact Analysis (Placeholder)
195
+
196
+ **Endpoint**: `POST /bia/impact-analysis`
197
+
198
+ Reserved for future Business Impact Analysis functionality.
199
+
200
+ ## 🎯 Use Cases
201
+
202
+ ### 1. Enterprise Risk Management
203
+
204
+ **Scenario**: Large corporation conducting annual risk assessment
205
+
206
+ **Process**:
207
+ 1. Use `/api/generate-threats` for each critical business process
208
+ 2. Consolidate identified threats into risk register
209
+ 3. Use `/api/risk-mitigation` to develop treatment plans
210
+ 4. Monitor and update mitigation strategies quarterly
211
+
212
+ **Benefits**:
213
+ - Comprehensive threat identification
214
+ - Consistent risk assessment methodology
215
+ - Actionable mitigation strategies
216
+ - Regulatory compliance support
217
+
218
+ ### 2. Business Continuity Planning
219
+
220
+ **Scenario**: Financial services firm developing BCP
221
+
222
+ **Process**:
223
+ 1. Map critical processes and dependencies
224
+ 2. Generate threat assessments using AI analysis
225
+ 3. Determine recovery objectives (RTO/MTPD)
226
+ 4. Develop mitigation and recovery strategies
227
+
228
+ **Benefits**:
229
+ - Reduced business disruption
230
+ - Faster recovery times
231
+ - Improved stakeholder confidence
232
+ - Regulatory compliance
233
+
234
+ ### 3. Vendor Risk Assessment
235
+
236
+ **Scenario**: Evaluating third-party service providers
237
+
238
+ **Process**:
239
+ 1. Assess vendor-specific threats and controls
240
+ 2. Generate mitigation recommendations
241
+ 3. Calculate residual risk post-mitigation
242
+ 4. Develop ongoing monitoring strategies
243
+
244
+ **Benefits**:
245
+ - Informed vendor selection
246
+ - Reduced supply chain risks
247
+ - Clear accountability frameworks
248
+ - Continuous risk monitoring
249
+
250
+ ### 4. Geographic Expansion Planning
251
+
252
+ **Scenario**: Multinational expanding to new markets
253
+
254
+ **Process**:
255
+ 1. Use geographic threat assessment for target locations
256
+ 2. Evaluate political, economic, and security risks
257
+ 3. Develop location-specific risk mitigation plans
258
+ 4. Establish local risk monitoring capabilities
259
+
260
+ **Benefits**:
261
+ - Informed market entry decisions
262
+ - Reduced operational risks
263
+ - Better resource allocation
264
+ - Enhanced stakeholder confidence
265
+
266
+ ## 📊 Request/Response Examples
267
+
268
+ ### Complete Process Risk Assessment
269
+
270
+ **Request**:
271
+ ```bash
272
+ curl -X POST "http://localhost:8000/api/generate-threats" \
273
+ -H "Content-Type: application/json" \
274
+ -d '{
275
+ "processName": "Customer Data Processing",
276
+ "department": "IT Operations",
277
+ "description": "Manages customer personal and financial data",
278
+ "owner": "Data Protection Officer",
279
+ "businessContext": "Critical for customer service and compliance",
280
+ "rto": "2hours",
281
+ "mtpd": "8hours",
282
+ "minTolerableDowntime": "30minutes"
283
+ }'
284
+ ```
285
+
286
+ **Response**:
287
+ ```json
288
+ {
289
+ "threats": [
290
+ {
291
+ "id": 1,
292
+ "name": "Data Breach",
293
+ "description": "Unauthorized access to customer personal and financial data could result in regulatory fines, legal action, and reputational damage",
294
+ "likelihood": 3,
295
+ "impact": 5,
296
+ "category": "Security",
297
+ "mitigation": "Implement encryption, access controls, and regular security audits"
298
+ },
299
+ {
300
+ "id": 2,
301
+ "name": "System Outage",
302
+ "description": "Hardware or software failure could disrupt customer service operations beyond acceptable RTO",
303
+ "likelihood": 4,
304
+ "impact": 4,
305
+ "category": "Operational",
306
+ "mitigation": "Deploy redundant systems and automated failover mechanisms"
307
+ }
308
+ ]
309
+ }
310
+ ```
311
+
312
+ ### Risk Mitigation Planning
313
+
314
+ **Request**:
315
+ ```bash
316
+ curl -X POST "http://localhost:8000/api/risk-mitigation" \
317
+ -H "Content-Type: application/json" \
318
+ -d '[
319
+ {
320
+ "enablerType": "Process",
321
+ "enablerDomain": "Information Security",
322
+ "majorCategory": "Cyber Security",
323
+ "mappedThreat": "Ransomware Attack",
324
+ "existingControls": "Antivirus software and email filtering",
325
+ "complianceStatus": "Partially compliant - needs updates",
326
+ "impact": "5",
327
+ "likelihood": "4",
328
+ "riskValue": "20"
329
+ }
330
+ ]'
331
+ ```
332
+
333
+ **Response**:
334
+ ```json
335
+ {
336
+ "mitigatedRisks": [
337
+ {
338
+ "revisedImpact": 3,
339
+ "revisedLikelihood": 2,
340
+ "revisedRiskValue": 6,
341
+ "mitigationPlan": "• Deploy endpoint detection response systems • Implement network segmentation controls • Conduct regular penetration testing",
342
+ "ownership": "Information Security Team"
343
+ }
344
+ ]
345
+ }
346
+ ```
347
+
348
+ ## 🚨 Error Handling
349
+
350
+ ### Common Error Responses
351
+
352
+ **400 Bad Request**:
353
+ ```json
354
+ {
355
+ "detail": "Invalid request format or missing required fields"
356
+ }
357
+ ```
358
+
359
+ **422 Validation Error**:
360
+ ```json
361
+ {
362
+ "detail": [
363
+ {
364
+ "loc": ["body", "processName"],
365
+ "msg": "field required",
366
+ "type": "value_error.missing"
367
+ }
368
+ ]
369
+ }
370
+ ```
371
+
372
+ **500 Internal Server Error**:
373
+ ```json
374
+ {
375
+ "detail": "AI service temporarily unavailable. Fallback response provided."
376
+ }
377
+ ```
378
+
379
+ ### Fallback Mechanisms
380
+
381
+ The API includes intelligent fallback responses when AI services are unavailable:
382
+
383
+ - **Threat Generation**: Returns common business process threats
384
+ - **Risk Mitigation**: Provides category-based mitigation strategies
385
+ - **Geographic Assessment**: Returns general location risk factors
386
+
387
+ ## 🔧 Technical Architecture
388
+
389
+ ### Components
390
+
391
+ 1. **FastAPI Framework**: RESTful API with automatic documentation
392
+ 2. **Pydantic Models**: Request/response validation and serialization
393
+ 3. **Groq Integration**: AI-powered analysis using Llama models
394
+ 4. **Fallback Logic**: Intelligent responses when AI is unavailable
395
+ 5. **JSON Processing**: Robust parsing of AI-generated responses
396
+
397
+ ### Security Considerations
398
+
399
+ - **API Key Management**: Secure handling of external service credentials
400
+ - **Input Validation**: Comprehensive request validation using Pydantic
401
+ - **Error Handling**: Graceful degradation with meaningful error messages
402
+ - **Rate Limiting**: Consider implementing for production deployments
403
+
404
+ ## 🤝 Contributing
405
+
406
+ 1. Fork the repository
407
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
408
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
409
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
410
+ 5. Open a Pull Request
411
+
412
+ ## 📄 License
413
+
414
+ This project is licensed under the MIT License - see the LICENSE file for details.
415
+
416
+ ## 🆘 Support
417
+
418
+ For support and questions:
419
+ - Create an issue in the repository
420
+ - Contact the development team
421
+ - Check the API documentation at `/docs`
422
+
423
  ---
424
+
425
+ **Built with ❤️ for enterprise risk management and business continuity**
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,8 +1,10 @@
1
  # app.py
2
  from fastapi import FastAPI
3
  from pydantic import BaseModel
 
4
  import os
5
  import openai
 
6
 
7
  app = FastAPI()
8
 
@@ -13,7 +15,7 @@ GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
13
  def generate_response(system_prompt: str, user_message: str):
14
  client = openai.OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
15
  response = client.chat.completions.create(
16
- model="mixtral-8x7b-32768",
17
  messages=[
18
  {"role": "system", "content": system_prompt},
19
  {"role": "user", "content": user_message}
@@ -22,10 +24,149 @@ def generate_response(system_prompt: str, user_message: str):
22
  )
23
  return response.choices[0].message.content
24
 
25
- # Request model
26
  class Message(BaseModel):
27
  message: str
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  @app.post("/bia/threat-assessment")
30
  def bia_threat_assessment(req: Message):
31
  prompt = """
@@ -63,3 +204,183 @@ def bia_impact_analysis(req: Message):
63
  "status": "placeholder",
64
  "note": "This endpoint is reserved for BIA impact analysis logic."
65
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
  from fastapi import FastAPI
3
  from pydantic import BaseModel
4
+ from typing import List, Optional
5
  import os
6
  import openai
7
+ import json
8
 
9
  app = FastAPI()
10
 
 
15
  def generate_response(system_prompt: str, user_message: str):
16
  client = openai.OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
17
  response = client.chat.completions.create(
18
+ model="llama3-8b-8192", # Try this supported model
19
  messages=[
20
  {"role": "system", "content": system_prompt},
21
  {"role": "user", "content": user_message}
 
24
  )
25
  return response.choices[0].message.content
26
 
27
+ # Request models
28
  class Message(BaseModel):
29
  message: str
30
 
31
+ class ProcessData(BaseModel):
32
+ processName: str
33
+ department: str
34
+ description: str
35
+ owner: str
36
+ businessContext: str
37
+ rto: str
38
+ mtpd: str
39
+ minTolerableDowntime: str
40
+
41
+ # Response models
42
+ class Threat(BaseModel):
43
+ id: int
44
+ name: str
45
+ description: str
46
+ likelihood: int
47
+ impact: int
48
+ category: str
49
+ mitigation: str
50
+
51
+ class ThreatsResponse(BaseModel):
52
+ threats: List[Threat]
53
+
54
+ @app.post("/api/generate-threats", response_model=ThreatsResponse)
55
+ def generate_threats(process_data: ProcessData):
56
+ """
57
+ Generate threats for a given business process based on its characteristics
58
+ """
59
+ system_prompt = """
60
+ You are an expert cybersecurity and business continuity risk analyst. Your task is to analyze business processes and identify potential threats that could disrupt operations.
61
+
62
+ Given the process information, generate a comprehensive list of threats that could affect this specific business process. Consider:
63
+ - Cybersecurity threats (malware, ransomware, phishing, insider threats)
64
+ - Operational threats (system failures, human error, supply chain disruption)
65
+ - Natural disasters and environmental threats
66
+ - Regulatory and compliance risks
67
+ - Third-party and vendor risks
68
+ - Physical security threats
69
+
70
+ For each threat, provide:
71
+ - A unique sequential ID
72
+ - A clear, specific name
73
+ - A detailed description of how it could impact this process
74
+ - Likelihood rating (1-5, where 1=very unlikely, 5=very likely)
75
+ - Impact rating (1-5, where 1=minimal impact, 5=catastrophic impact)
76
+ - A relevant category
77
+ - Practical mitigation strategies
78
+
79
+ Consider the process's RTO, MTPD, and minimum tolerable downtime when assessing impact.
80
+
81
+ Respond strictly in this JSON format:
82
+ {
83
+ "threats": [
84
+ {
85
+ "id": 1,
86
+ "name": "Threat Name",
87
+ "description": "Detailed description of the threat and its potential impact",
88
+ "likelihood": 3,
89
+ "impact": 4,
90
+ "category": "Security/Operational/Environmental/Regulatory",
91
+ "mitigation": "Specific mitigation strategies"
92
+ }
93
+ ]
94
+ }
95
+ """
96
+
97
+ user_message = f"""
98
+ Process Details:
99
+ - Process Name: {process_data.processName}
100
+ - Department: {process_data.department}
101
+ - Description: {process_data.description}
102
+ - Process Owner: {process_data.owner}
103
+ - Business Context: {process_data.businessContext}
104
+ - Recovery Time Objective (RTO): {process_data.rto}
105
+ - Maximum Tolerable Period of Disruption (MTPD): {process_data.mtpd}
106
+ - Minimum Tolerable Downtime: {process_data.minTolerableDowntime}
107
+
108
+ Please analyze this process and generate 8-12 relevant threats with their risk assessments and mitigation strategies.
109
+ """
110
+
111
+ try:
112
+ result = generate_response(system_prompt, user_message)
113
+
114
+ # Extract JSON from the response (AI sometimes adds explanatory text)
115
+ json_start = result.find('{')
116
+ json_end = result.rfind('}') + 1
117
+
118
+ if json_start != -1 and json_end > json_start:
119
+ json_str = result[json_start:json_end]
120
+ threats_data = json.loads(json_str)
121
+ return ThreatsResponse(**threats_data)
122
+ else:
123
+ raise ValueError("No valid JSON found in response")
124
+
125
+ except (json.JSONDecodeError, ValueError) as e:
126
+ # Fallback response if JSON parsing fails
127
+ return ThreatsResponse(threats=[
128
+ Threat(
129
+ id=1,
130
+ name="System Unavailability",
131
+ description="Critical system failure affecting process execution",
132
+ likelihood=3,
133
+ impact=4,
134
+ category="Operational",
135
+ mitigation="Implement redundant systems and regular backups"
136
+ ),
137
+ Threat(
138
+ id=2,
139
+ name="Cyber Attack",
140
+ description="Malicious attack disrupting core operations",
141
+ likelihood=3,
142
+ impact=4,
143
+ category="Security",
144
+ mitigation="Use firewalls and real-time monitoring"
145
+ ),
146
+ Threat(
147
+ id=3,
148
+ name="Data Breach",
149
+ description="Unauthorized access to sensitive process data",
150
+ likelihood=2,
151
+ impact=5,
152
+ category="Security",
153
+ mitigation="Implement encryption and access controls"
154
+ )
155
+ ])
156
+ except Exception as e:
157
+ # Fallback response for any other errors
158
+ return ThreatsResponse(threats=[
159
+ Threat(
160
+ id=1,
161
+ name="Process Disruption",
162
+ description="General process disruption due to unforeseen circumstances",
163
+ likelihood=3,
164
+ impact=3,
165
+ category="Operational",
166
+ mitigation="Develop comprehensive business continuity plans"
167
+ )
168
+ ])
169
+
170
  @app.post("/bia/threat-assessment")
171
  def bia_threat_assessment(req: Message):
172
  prompt = """
 
204
  "status": "placeholder",
205
  "note": "This endpoint is reserved for BIA impact analysis logic."
206
  }
207
+
208
+ class RiskItem(BaseModel):
209
+ enablerType: str
210
+ enablerDomain: str
211
+ majorCategory: str
212
+ mappedThreat: str
213
+ existingControls: str
214
+ complianceStatus: str
215
+ impact: str
216
+ likelihood: str
217
+ riskValue: str
218
+
219
+ class MitigationResponse(BaseModel):
220
+ revisedImpact: int
221
+ revisedLikelihood: int
222
+ revisedRiskValue: int
223
+ mitigationPlan: str
224
+ ownership: str
225
+
226
+ class RiskMitigationResponse(BaseModel):
227
+ mitigatedRisks: List[MitigationResponse]
228
+
229
+ @app.post("/api/risk-mitigation", response_model=RiskMitigationResponse)
230
+ def generate_risk_mitigation(risk_items: List[RiskItem]):
231
+ """
232
+ Generate mitigation plans and revised risk assessments for identified threats
233
+ """
234
+ system_prompt = """
235
+ You are an expert risk management and business continuity analyst. Your task is to analyze existing risk items and provide comprehensive mitigation strategies that will reduce the overall risk.
236
+
237
+ For each risk item provided, you need to:
238
+ 1. Analyze the current risk assessment (impact, likelihood, risk value)
239
+ 2. Evaluate existing controls and compliance status
240
+ 3. Recommend additional mitigation measures
241
+ 4. Provide revised risk ratings after implementing the mitigation plan
242
+ 5. Assign appropriate ownership for the mitigation activities
243
+
244
+ Consider:
245
+ - Current controls effectiveness and compliance status
246
+ - Industry best practices for the specific threat type
247
+ - Cost-effective mitigation strategies
248
+ - Realistic timeline for implementation
249
+ - Appropriate ownership based on enabler type and domain
250
+
251
+ For revised ratings:
252
+ - Impact (1-5): Consider how mitigation reduces potential damage
253
+ - Likelihood (1-5): Consider how mitigation reduces probability of occurrence
254
+ - Risk Value: Calculate as revised impact × revised likelihood
255
+
256
+ For mitigation plans:
257
+ - Maximum 3 bullet points
258
+ - Each point maximum 10 words
259
+ - Be concise and actionable
260
+
261
+ Respond strictly in this JSON format (no newlines within strings):
262
+ {
263
+ "mitigatedRisks": [
264
+ {
265
+ "revisedImpact": 2,
266
+ "revisedLikelihood": 2,
267
+ "revisedRiskValue": 4,
268
+ "mitigationPlan": "• Install fire suppression systems • Conduct quarterly training • Implement monitoring alerts",
269
+ "ownership": "Responsible party/department"
270
+ }
271
+ ]
272
+ }
273
+ """
274
+
275
+ # Format the risk items for the AI
276
+ risk_data = []
277
+ for i, item in enumerate(risk_items, 1):
278
+ risk_data.append(f"""
279
+ Risk Item {i}:
280
+ - Enabler Type: {item.enablerType}
281
+ - Enabler Domain: {item.enablerDomain}
282
+ - Major Category: {item.majorCategory}
283
+ - Mapped Threat: {item.mappedThreat}
284
+ - Existing Controls: {item.existingControls}
285
+ - Compliance Status: {item.complianceStatus}
286
+ - Current Impact: {item.impact}
287
+ - Current Likelihood: {item.likelihood}
288
+ - Current Risk Value: {item.riskValue}
289
+ """)
290
+
291
+ user_message = f"""
292
+ Please analyze the following risk items and provide mitigation strategies:
293
+
294
+ {''.join(risk_data)}
295
+
296
+ For each risk item, provide:
297
+ 1. Revised impact rating (1-5) after implementing mitigation
298
+ 2. Revised likelihood rating (1-5) after implementing mitigation
299
+ 3. Revised risk value (impact × likelihood)
300
+ 4. Concise mitigation plan (max 3 points, 10 words each)
301
+ 5. Appropriate ownership assignment (department/role responsible)
302
+
303
+ Consider the existing controls and compliance status when developing mitigation plans.
304
+ """
305
+
306
+ try:
307
+ result = generate_response(system_prompt, user_message)
308
+
309
+ # Extract JSON from the response
310
+ json_start = result.find('{')
311
+ json_end = result.rfind('}') + 1
312
+
313
+ if json_start != -1 and json_end > json_start:
314
+ json_str = result[json_start:json_end]
315
+ # The AI returns properly formatted JSON with newlines, just parse it directly
316
+ try:
317
+ mitigation_data = json.loads(json_str)
318
+ return RiskMitigationResponse(**mitigation_data)
319
+ except json.JSONDecodeError as e:
320
+ # If direct parsing fails, try cleaning the JSON
321
+ import re
322
+ json_str = re.sub(r'\n\s*', ' ', json_str)
323
+ json_str = re.sub(r'\r\s*', ' ', json_str)
324
+ json_str = re.sub(r'\t+', ' ', json_str)
325
+ json_str = re.sub(r'\s+', ' ', json_str)
326
+ mitigation_data = json.loads(json_str)
327
+ return RiskMitigationResponse(**mitigation_data)
328
+ else:
329
+ raise ValueError("No valid JSON found in response")
330
+
331
+ except (json.JSONDecodeError, ValueError) as e:
332
+ # Fallback response if JSON parsing fails - provide intelligent mitigation
333
+ fallback_risks = []
334
+ for i, item in enumerate(risk_items):
335
+ # Intelligent fallback logic based on threat category and existing controls
336
+ current_impact = int(item.impact)
337
+ current_likelihood = int(item.likelihood)
338
+
339
+ # Risk reduction logic based on category
340
+ impact_reduction = 1
341
+ likelihood_reduction = 1
342
+
343
+ if item.majorCategory.lower() in ['fire', 'natural disaster']:
344
+ impact_reduction = 2
345
+ likelihood_reduction = 2
346
+ elif item.majorCategory.lower() in ['cyber security', 'security']:
347
+ impact_reduction = 1
348
+ likelihood_reduction = 2
349
+
350
+ revised_impact = max(1, current_impact - impact_reduction)
351
+ revised_likelihood = max(1, current_likelihood - likelihood_reduction)
352
+
353
+ # Generate category-specific mitigation plans
354
+ if item.majorCategory.lower() == 'fire':
355
+ mitigation_plan = "• Install automatic fire suppression systems • Conduct quarterly safety training • Implement 24/7 monitoring alerts"
356
+ ownership = "Facilities Management Team"
357
+ elif item.majorCategory.lower() in ['cyber security', 'security']:
358
+ mitigation_plan = "• Deploy endpoint detection response systems • Implement network segmentation controls • Conduct regular penetration testing"
359
+ ownership = "Information Security Team"
360
+ else:
361
+ mitigation_plan = f"• Enhance existing {item.majorCategory.lower()} controls • Implement continuous monitoring systems • Establish incident response procedures"
362
+ ownership = f"{item.enablerDomain} Team"
363
+
364
+ fallback_risks.append(MitigationResponse(
365
+ revisedImpact=revised_impact,
366
+ revisedLikelihood=revised_likelihood,
367
+ revisedRiskValue=revised_impact * revised_likelihood,
368
+ mitigationPlan=mitigation_plan,
369
+ ownership=ownership
370
+ ))
371
+
372
+ return RiskMitigationResponse(mitigatedRisks=fallback_risks)
373
+
374
+ except Exception as e:
375
+ # General fallback for any other errors
376
+ fallback_risks = []
377
+ for i, item in enumerate(risk_items):
378
+ fallback_risks.append(MitigationResponse(
379
+ revisedImpact=2,
380
+ revisedLikelihood=2,
381
+ revisedRiskValue=4,
382
+ mitigationPlan="• Implement enhanced risk controls • Establish monitoring procedures • Conduct regular assessments",
383
+ ownership="Risk Management Team"
384
+ ))
385
+
386
+ return RiskMitigationResponse(mitigatedRisks=fallback_risks)