Repository navigation
Expand file tree
/
Copy pathControlItem.jsx
More file actions
667 lines (603 loc) · 28.3 KB
/
Copy pathControlItem.jsx
File metadata and controls
667 lines (603 loc) · 28.3 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
/**
* Copyright 2025 Adobe. All rights reserved.
* Copyright (c) 2025 Mukesh Kesharwani
*
* Licensed under the MIT License. See LICENSE file for details.
*/
import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { buildAuthenticatedJsonHeaders } from '../utils/authenticatedFetch.js';
import ControlSuggestions from './ControlSuggestions';
import { STATUS_OPTIONS } from '../constants/controlStatus.js';
import './ControlItem.css';
function ControlItem({ control, isExpanded, onToggle, onUpdate, allControls = [], databaseIntegrationEnabled = false, adobeTeamOptions = [] }) {
const { canEditImplementationStatus, getAuthConfig } = useAuth();
const [fetchingData, setFetchingData] = useState({});
const [credentials, setCredentials] = useState([]);
// Load credentials from localStorage
useEffect(() => {
const loadCredentials = () => {
const saved = localStorage.getItem('apiCredentials');
if (saved) {
try {
setCredentials(JSON.parse(saved));
} catch (e) {
console.error('Error loading credentials:', e);
setCredentials([{ id: 'default', name: 'Default Credential', headers: '', isDefault: true }]);
}
} else {
setCredentials([{ id: 'default', name: 'Default Credential', headers: '', isDefault: true }]);
}
};
loadCredentials();
// Listen for credential updates
const handleStorageChange = () => {
loadCredentials();
};
window.addEventListener('storage', handleStorageChange);
window.addEventListener('credentialsUpdated', handleStorageChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener('credentialsUpdated', handleStorageChange);
};
}, []);
const handleStatusChange = (e) => {
const newStatus = e.target.value;
onUpdate(control.id, 'status', newStatus);
// Auto-populate related fields when "Not Applicable" is selected
if (newStatus === 'not-applicable') {
// Set Responsible Party to "Not Applicable" if not already set
if (!control.responsibleParty || control.responsibleParty === '') {
onUpdate(control.id, 'responsibleParty', 'Not Applicable');
}
// Set Cloud Provider Responsibility to "Control Implementer" if not already set
if (!control.controlOwner || control.controlOwner === '') {
onUpdate(control.id, 'controlOwner', 'Control Implementer');
}
}
};
const handleImplementationChange = (e) => {
onUpdate(control.id, 'implementation', e.target.value);
};
const handleRemarksChange = (e) => {
onUpdate(control.id, 'remarks', e.target.value);
};
// Function to fetch API data and manage history
const handleFetchApiData = async (controlId, apiUrl) => {
if (!apiUrl) {
alert('Please enter an API URL first.');
return;
}
// Set fetching state
setFetchingData(prev => ({ ...prev, [controlId]: true }));
try {
// Check for API Gateway configuration - route ALL requests through gateway
const gatewaysConfig = localStorage.getItem('apiGateways');
let finalUrl = apiUrl;
let gatewayName = null;
if (gatewaysConfig) {
try {
const gateways = JSON.parse(gatewaysConfig);
// Prefer AWS Gateway if enabled, otherwise use Azure
if (gateways.aws && gateways.aws.enabled && gateways.aws.url) {
finalUrl = `${gateways.aws.url}?targetUrl=${encodeURIComponent(apiUrl)}`;
gatewayName = 'AWS';
console.log('🔄 Routing through AWS API Gateway:', gateways.aws.url);
} else if (gateways.azure && gateways.azure.enabled && gateways.azure.url) {
finalUrl = `${gateways.azure.url}?targetUrl=${encodeURIComponent(apiUrl)}`;
gatewayName = 'Azure';
console.log('🔄 Routing through Azure API Gateway:', gateways.azure.url);
}
} catch (e) {
console.warn('Error parsing API Gateway configuration:', e);
}
}
// Check if gateway is configured
if (!gatewayName) {
throw new Error('No API Gateway configured. Please configure AWS or Azure API Gateway in Settings.');
}
// Use backend proxy to avoid CORS issues
// API Gateway handles all authentication - no custom headers needed
const response = await fetch('/api/proxy-fetch', {
method: 'POST',
headers: buildAuthenticatedJsonHeaders(getAuthConfig),
credentials: 'include',
body: JSON.stringify({
url: finalUrl,
method: 'GET',
headers: {}, // API Gateway handles authentication
}),
});
const proxyResponse = await response.json();
// Check if proxy request was successful
if (!proxyResponse.success) {
throw new Error(proxyResponse.error || 'Failed to fetch data through proxy');
}
const data = proxyResponse.data;
const timestamp = new Date().toISOString();
const dateOnly = timestamp.split('T')[0]; // Get YYYY-MM-DD
// Get existing history or create new array
const existingHistory = control.apiDataHistory || [];
// Check if we already have an entry for today
const todayEntryIndex = existingHistory.findIndex(entry =>
entry.timestamp.split('T')[0] === dateOnly
);
// Create new entry
const newEntry = {
timestamp,
success: proxyResponse.success,
status: proxyResponse.status,
data: data,
};
let updatedHistory;
if (todayEntryIndex >= 0) {
// Replace today's entry with the new one (most current)
updatedHistory = [...existingHistory];
updatedHistory[todayEntryIndex] = newEntry;
} else {
// Add new entry at the beginning
updatedHistory = [newEntry, ...existingHistory];
}
// Keep only last 12 entries
updatedHistory = updatedHistory.slice(0, 12);
// Update control with new history
onUpdate(controlId, 'apiDataHistory', updatedHistory);
// Show success message
alert(`✅ Data fetched successfully from API!\nStatus: ${proxyResponse.status}\nTimestamp: ${new Date(timestamp).toLocaleString()}`);
} catch (error) {
console.error('Error fetching API data:', error);
// Provide more specific error messages
let errorMessage = error.message;
if (error.message.includes('Failed to fetch')) {
errorMessage = 'Network error. Please check your internet connection and verify the API URL is correct.';
} else if (error.message.includes('NetworkError')) {
errorMessage = 'Network connection failed. Please check your internet connection.';
}
// Store failed attempt in history
const timestamp = new Date().toISOString();
const dateOnly = timestamp.split('T')[0];
const existingHistory = control.apiDataHistory || [];
const todayEntryIndex = existingHistory.findIndex(entry =>
entry.timestamp.split('T')[0] === dateOnly
);
const newEntry = {
timestamp,
success: false,
error: errorMessage,
data: null,
};
let updatedHistory;
if (todayEntryIndex >= 0) {
updatedHistory = [...existingHistory];
updatedHistory[todayEntryIndex] = newEntry;
} else {
updatedHistory = [newEntry, ...existingHistory];
}
updatedHistory = updatedHistory.slice(0, 12);
onUpdate(controlId, 'apiDataHistory', updatedHistory);
alert(`❌ Failed to fetch data from API.\nError: ${errorMessage}\n\nTroubleshooting:\n1. Verify the API URL is correct and accessible\n2. If using authentication, ensure you're logged into SSO in this browser\n3. Check if the API endpoint is reachable\n4. Review browser console for detailed error information`);
} finally {
// Clear fetching state
setFetchingData(prev => ({ ...prev, [controlId]: false }));
}
};
const currentStatus = STATUS_OPTIONS.find(s => s.value === control.status) || STATUS_OPTIONS[3];
return (
<div className={`control-item ${isExpanded ? 'expanded' : ''}`}>
<div className="control-header" onClick={onToggle}>
<div className="control-info">
<div className="control-id-badge">{control.id}</div>
<div className="control-title-section">
<h4 className="control-title">{control.title}</h4>
{control.groupTitle && (
<span className="control-group">{control.groupTitle}</span>
)}
</div>
</div>
<div className="control-header-actions">
<span className={`status-badge status-${currentStatus.color}`}>
{currentStatus.label}
</span>
<button className="expand-btn" type="button">
{isExpanded ? '▼' : '▶'}
</button>
</div>
</div>
{isExpanded && (
<div className="control-body">
{control.parts && control.parts.length > 0 && (
<div className="control-details">
<h5>Control Details</h5>
{control.parts.map((part, idx) => (
<div key={idx} className="control-part">
{part.name && <strong>{part.name}:</strong>}
{part.prose && <p>{part.prose}</p>}
</div>
))}
</div>
)}
<ControlSuggestions
control={control}
existingControls={allControls.filter(c => c.id !== control.id && c.implementation)}
onApplySuggestion={onUpdate}
/>
<div className="control-form">
<div className="form-row-2">
<div className="form-group">
<label htmlFor={`status-${control.id}`}>
Implementation Status *
{!canEditImplementationStatus() && <span style={{ marginLeft: '0.5rem', color: '#d97706', fontSize: '0.85em' }}>🔒 Assessor Role Required</span>}
</label>
<select
id={`status-${control.id}`}
className={`form-control status-select status-${control.status || 'not-assessed'}`}
value={control.status}
onChange={handleStatusChange}
disabled={!canEditImplementationStatus()}
>
{STATUS_OPTIONS.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</div>
<div className="form-group">
<label htmlFor={`applicability-${control.id}`}>Applicability</label>
<select
id={`applicability-${control.id}`}
className="form-control"
value={control.applicability || 'applicable'}
onChange={(e) => onUpdate(control.id, 'applicability', e.target.value)}
>
<option value="applicable">Applicable</option>
<option value="not-applicable">Not Applicable</option>
<option value="conditional">Conditionally Applicable</option>
</select>
</div>
</div>
<div className="form-group">
<label htmlFor={`implementation-${control.id}`}>
Implementation Description *
</label>
<textarea
id={`implementation-${control.id}`}
className="form-control"
rows="4"
placeholder="Describe how this control is implemented in your system..."
value={control.implementation}
onChange={handleImplementationChange}
/>
</div>
<div className="form-row form-row-responsible-party">
<div className="form-group form-group-responsible-party">
<label htmlFor={`responsibleParty-${control.id}`}>Responsible Party</label>
<select
id={`responsibleParty-${control.id}`}
className="form-control"
value={control.responsibleParty || ''}
onChange={(e) => onUpdate(control.id, 'responsibleParty', e.target.value)}
>
<option value="">Select...</option>
<option value="Implemented By Adobe">Implemented By Adobe</option>
<option value="Inherited from CSP">Inherited from CSP</option>
<option value="Shared">Shared</option>
<option value="Consumer Responsibility">Consumer Responsibility</option>
<option value="Consumer Implementation Required">Consumer Implementation Required</option>
<option value="Consumer Configuration Required">Consumer Configuration Required</option>
<option value="Not Applicable">Not Applicable</option>
</select>
</div>
{databaseIntegrationEnabled && control.responsibleParty === 'Implemented By Adobe' && (
<>
{[0, 1, 2].map((slotIndex) => {
const arr = Array.isArray(control.adobeTeamResponsible) ? control.adobeTeamResponsible : [];
const value = arr[slotIndex] ?? '';
return (
<div key={slotIndex} className="form-group form-group-adobe-slot">
<label htmlFor={`adobe-team-slot-${slotIndex}-${control.id}`}>T{slotIndex + 1}</label>
<select
id={`adobe-team-slot-${slotIndex}-${control.id}`}
className="form-control"
value={value}
onChange={(e) => {
const newVal = e.target.value;
const prev = Array.isArray(control.adobeTeamResponsible) ? control.adobeTeamResponsible : [];
const newArr = [prev[0] ?? '', prev[1] ?? '', prev[2] ?? ''];
newArr[slotIndex] = newVal;
onUpdate(control.id, 'adobeTeamResponsible', newArr);
}}
>
<option value="">—</option>
{adobeTeamOptions.map((opt) => (
<option key={String(opt.id) + opt.label} value={opt.label}>{opt.label}</option>
))}
</select>
</div>
);
})}
</>
)}
</div>
<div className="form-row-3">
<div className="form-group">
<label htmlFor={`controlOwner-${control.id}`}>Cloud Provider Responsibility</label>
<select
id={`controlOwner-${control.id}`}
className="form-control"
value={control.controlOwner || ''}
onChange={(e) => onUpdate(control.id, 'controlOwner', e.target.value)}
>
<option value="">Select...</option>
<option value="Inherited from CSP">Inherited from CSP</option>
<option value="Control Implementer">Control Implementer</option>
<option value="Control Option Provider">Control Option Provider</option>
</select>
</div>
<div className="form-group">
<label htmlFor={`implementationDate-${control.id}`}>Implementation Date</label>
<input
type="date"
id={`implementationDate-${control.id}`}
className="form-control"
value={control.implementationDate || ''}
onChange={(e) => onUpdate(control.id, 'implementationDate', e.target.value)}
/>
</div>
</div>
{(control.responsibleParty === 'Consumer Implementation Required' ||
control.responsibleParty === 'Consumer Configuration Required') && (
<div className="form-group">
<label htmlFor={`consumerGuidance-${control.id}`}>Consumer Guidance</label>
<textarea
id={`consumerGuidance-${control.id}`}
className="form-control"
rows="3"
placeholder="Provide guidance for consumer implementation or configuration..."
value={control.consumerGuidance || ''}
onChange={(e) => onUpdate(control.id, 'consumerGuidance', e.target.value)}
/>
</div>
)}
<div className="form-row-3">
<div className="form-group">
<label htmlFor={`reviewDate-${control.id}`}>Last Review Date</label>
<input
type="date"
id={`reviewDate-${control.id}`}
className="form-control"
value={control.reviewDate || ''}
onChange={(e) => onUpdate(control.id, 'reviewDate', e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor={`nextReviewDate-${control.id}`}>Next Review Date</label>
<input
type="date"
id={`nextReviewDate-${control.id}`}
className="form-control"
value={control.nextReviewDate || ''}
onChange={(e) => onUpdate(control.id, 'nextReviewDate', e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor={`lastTestDate-${control.id}`}>Last Test Date</label>
<input
type="date"
id={`lastTestDate-${control.id}`}
className="form-control"
value={control.lastTestDate || ''}
onChange={(e) => onUpdate(control.id, 'lastTestDate', e.target.value)}
/>
</div>
</div>
<div className="form-group">
<label htmlFor={`controlType-${control.id}`}>Control Type</label>
<select
id={`controlType-${control.id}`}
className="form-control"
value={control.controlType || ''}
onChange={(e) => onUpdate(control.id, 'controlType', e.target.value)}
>
<option value="">Select...</option>
<option value="Policy">Policy</option>
<option value="Process (Isolated Implementation by Human)">Process (Isolated Implementation by Human)</option>
<option value="Orchestrated in Clusters or Pools by Tools">Orchestrated in Clusters or Pools by Tools</option>
<option value="Automated by Tools">Automated by Tools</option>
</select>
</div>
{control.controlType === 'Automated by Tools' ? (
<>
<div className="form-group">
<label htmlFor={`apiUrl-${control.id}`}>API URL for Real-time Data</label>
<div className="api-url-input-group">
<input
type="url"
id={`apiUrl-${control.id}`}
className="form-control api-url-input"
placeholder="https://api.example.com/control-status"
value={control.apiUrl || ''}
onChange={(e) => onUpdate(control.id, 'apiUrl', e.target.value)}
/>
<button
type="button"
className="fetch-data-btn"
onClick={() => handleFetchApiData(control.id, control.apiUrl)}
disabled={!control.apiUrl || fetchingData[control.id]}
title="Fetch data from API"
>
{fetchingData[control.id] ? '⏳' : '🔄'} Fetch Data
</button>
</div>
</div>
<div className="info-box" style={{marginTop: '12px', marginBottom: '12px'}}>
<strong>ℹ️ Authentication:</strong> All API calls are routed through your configured API Gateway (AWS or Azure).
No credentials are stored in this application. Configure your gateway in <strong>Settings</strong>.
</div>
{/* API Data History - Show last 12 entries */}
{control.apiDataHistory && control.apiDataHistory.length > 0 && (
<div className="form-group">
<label>API Data History (Last 12 Entries)</label>
<div className="api-history-container">
{control.apiDataHistory.slice(0, 12).map((entry, index) => (
<div key={index} className="api-history-entry">
<div className="api-history-header">
<span className="api-history-date">
📅 {new Date(entry.timestamp).toLocaleString()}
</span>
<span className="api-history-status">
{entry.success ? '✅ Success' : '❌ Failed'}
</span>
</div>
<div className="api-history-data">
<pre>{JSON.stringify(entry.data, null, 2)}</pre>
</div>
</div>
))}
</div>
</div>
)}
</>
) : (
<>
<div className="form-group">
<label htmlFor={`testingObjective-${control.id}`}>Assessment/Testing Objective</label>
<textarea
id={`testingObjective-${control.id}`}
className="form-control"
rows="2"
placeholder="Define the objective of assessing this control..."
value={control.testingObjective || ''}
onChange={(e) => onUpdate(control.id, 'testingObjective', e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor={`evidence-${control.id}`}>Evidence/Artifacts Location</label>
<input
type="text"
id={`evidence-${control.id}`}
className="form-control"
placeholder="e.g., SharePoint/Policies/AccessControl.pdf"
value={control.evidence || ''}
onChange={(e) => onUpdate(control.id, 'evidence', e.target.value)}
/>
</div>
<div className="form-row-2">
<div className="form-group">
<label htmlFor={`testingProcedure-${control.id}`}>Testing/Assessment Procedure</label>
<textarea
id={`testingProcedure-${control.id}`}
className="form-control"
rows="2"
placeholder="How is this control tested?"
value={control.testingProcedure || ''}
onChange={(e) => onUpdate(control.id, 'testingProcedure', e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor={`testingFrequency-${control.id}`}>Testing Frequency</label>
<select
id={`testingFrequency-${control.id}`}
className="form-control"
value={control.testingFrequency || 'annual'}
onChange={(e) => onUpdate(control.id, 'testingFrequency', e.target.value)}
>
<option value="">Not Set</option>
<option value="continuous">Continuous</option>
<option value="monthly">Monthly</option>
<option value="quarterly">Quarterly</option>
<option value="semi-annual">Semi-Annual</option>
<option value="annual">Annual</option>
</select>
</div>
</div>
</>
)}
{/* Risk & Compliance Section - Only show for Not Implemented or Ineffective status */}
{(control.status === 'not-implemented' || control.status === 'ineffective') && (
<>
<div className="form-row-2">
<div className="form-group">
<label htmlFor={`riskRating-${control.id}`}>Inherent Risk Level</label>
<select
id={`riskRating-${control.id}`}
className="form-control"
value={control.riskRating || ''}
onChange={(e) => onUpdate(control.id, 'riskRating', e.target.value)}
>
<option value="">Not Set</option>
<option value="critical">Critical</option>
<option value="high">High</option>
<option value="medium">Medium</option>
<option value="low">Low</option>
</select>
</div>
<div className="form-group">
<label htmlFor={`residualRisk-${control.id}`}>Residual Risk Level</label>
<select
id={`residualRisk-${control.id}`}
className="form-control"
value={control.residualRisk || ''}
onChange={(e) => onUpdate(control.id, 'residualRisk', e.target.value)}
>
<option value="">Not Set</option>
<option value="critical">Critical</option>
<option value="high">High</option>
<option value="medium">Medium</option>
<option value="low">Low</option>
</select>
</div>
</div>
<div className="form-group">
<label htmlFor={`compensatingControls-${control.id}`}>Compensating Controls</label>
<textarea
id={`compensatingControls-${control.id}`}
className="form-control"
rows="2"
placeholder="Alternative controls providing equivalent protection..."
value={control.compensatingControls || ''}
onChange={(e) => onUpdate(control.id, 'compensatingControls', e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor={`exceptions-${control.id}`}>Exceptions/Deviations</label>
<textarea
id={`exceptions-${control.id}`}
className="form-control"
rows="2"
placeholder="Approved exceptions from the control requirement..."
value={control.exceptions || ''}
onChange={(e) => onUpdate(control.id, 'exceptions', e.target.value)}
/>
</div>
</>
)}
<div className="form-group">
<label htmlFor={`frameworks-${control.id}`}>Mapped Frameworks</label>
<input
type="text"
id={`frameworks-${control.id}`}
className="form-control"
placeholder="e.g., NIST, ISO 27001, PCI-DSS"
value={control.frameworks || ''}
onChange={(e) => onUpdate(control.id, 'frameworks', e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor={`remarks-${control.id}`}>Notes/Remarks</label>
<textarea
id={`remarks-${control.id}`}
className="form-control"
rows="2"
placeholder="Additional notes or comments..."
value={control.remarks}
onChange={handleRemarksChange}
/>
</div>
</div>
</div>
)}
</div>
);
}
export default ControlItem;