Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
6626 lines (6039 loc) · 242 KB
/
Copy pathserver.js
File metadata and controls
6626 lines (6039 loc) · 242 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 2025 Adobe. All rights reserved.
* Copyright (c) 2025 Mukesh Kesharwani
*
* Licensed under the MIT License. See LICENSE file for details.
*/
import express from 'express';
import { getDefaultSystemStatus } from './utils/constants.js';
import rateLimit from 'express-rate-limit';
import cors from 'cors';
import axios from './utils/safeAxios.js';
import https from 'https';
import { v4 as uuidv4 } from 'uuid';
import { generateAcscExcelExport } from './acscExcelExport.js';
import { complianceReportContentDisposition } from './utils/complianceReportFileName.js';
import { generatePDFReport } from './pdfExport.js';
import { compareWithExistingSSP, extractControlsFromSSP, prepareSspExportPayload } from './sspComparisonV3.js';
import { parseCCMExcel } from './ccmImport.js';
import { validateOSCAL, getValidatorStatus } from './oscalValidator.js';
import { loadConfig, getResolvedConfig, getResolvedDatabaseConfigForTest, saveConfig, validateConfig, prepareConfigForSave, getConfigDir, applyDatabaseEnvOverrides, applyGenericSsoEnvOverrides, ensureConfigSecretsProtected } from './configManager.js';
import { testConnection, connectPgClient, ensureAdobeTeamsTable, getAdobeTeamOptions } from './database/dbClient.js';
import { syncExportToDatabase } from './database/exportSync.js';
import { mergeControlsFromExtendedData } from './database/mergeExtendedDataOnLoad.js';
import { applyDefaultOidcGroupMappingsToConfig, mergeDefaultOidcGroupToRoleMapping } from './utils/defaultOidcGroupRoleMapping.js';
import { initializeSecretsCache, resolveSecretPointer, isAwsSmMode } from './utils/secretsManager.js';
import { evaluateReadiness } from './utils/healthReady.js';
import { isSecretPointer } from './utils/sensitiveConfigKeys.js';
import { isCfgEncPointer, decryptConfigSecret } from './utils/configFieldCrypto.js';
import {
applyRoleBasedConfigRedaction,
coalesceSecretForTest,
maskSensitiveConfigForClient,
} from './utils/resolveStoredSecret.js';
import {
buildAdminSettingsResponse,
buildRuntimeSettingsResponse,
logSettingsAccess,
sanitizeSettingsSaveResponse,
} from './utils/settingsClientResponse.js';
import { oidcAxiosRequestOptions } from './utils/oidcHttpsAgent.js';
import { suggestControlImplementation, suggestMultipleControls } from './controlSuggestionEngine.js';
import { checkMistralAvailability, loadMistralConfig } from './mistralService.js';
import { checkGemmaAvailability, loadGemmaConfig } from './gemmaService.js';
import { checkAIAvailability, detectModelFamily } from './aiModelRouter.js';
import { addIntegrityHash, verifyIntegrityHash, getIntegrityInfo } from './integrityService.js';
import { getLogStats, cleanupOldLogs } from './aiLogger.js';
import { isUserAllowedForAISuggestions } from './utils/aiAllowedUsers.js';
import {
bedrockCredentialsConfigured,
buildBedrockAiConfigFromRequest,
createBedrockControlPlaneClient,
createBedrockRuntimeClient,
normalizeBedrockAuthMode
} from './utils/bedrockCredentials.js';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Read once at startup so /health can report which build a given Blue/Green instance is running,
// without relying on the UI footer. readFileSync (not a JSON import) avoids ESM import-attribute
// dependency; never block startup if package.json is somehow unreadable.
let SERVICE_VERSION = 'unknown';
try {
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
SERVICE_VERSION = pkg.version || 'unknown';
} catch (_) {
// leave as 'unknown'
}
// Load .env from repo root only in development (laptop). Docker and EC2 use their own USERS_PATH/CONFIG_PATH from entrypoint or systemd.
if (process.env.NODE_ENV !== 'production') {
dotenv.config({ path: path.join(__dirname, '..', '.env') });
}
import {
initializeDefaultUsers,
authenticateUser,
createSessionForOidcUser,
findOrCreateOidcUser,
validateSession,
logout as logoutUser,
getAllUsers,
getUserById,
createUser,
updateUser,
deleteUser,
deactivateUser,
hardDeleteUser,
autoCleanupDeactivatedUsers,
getDaysSinceDeactivation,
changePassword,
generatePassword,
getLegacyPasswordHashMigrationStats,
} from './auth/userManager.js';
import { generateDefaultPasswordFromEnv } from './auth/passwordGenerator.js';
import {
GENERIC_OIDC_PROVIDER_ID,
fetchOidcDiscovery as fetchGenericOidcDiscovery,
probeOidcDiscovery,
normalizeGenericOidcScope,
genericAuthorizeScope,
isGenericOidcTlsRelaxed,
generateCodeVerifier as generateGenericCodeVerifier,
computeCodeChallenge as computeGenericCodeChallenge,
createSignedOidcState as createSignedGenericOidcState,
verifySignedOidcState as verifySignedGenericOidcState,
resolveGenericOidcRedirectUri,
isRedirectUriAllowed,
diagnoseGenericOidcConfig,
discoveryFailureToLoginError,
genericOidcLoginErrorQuery,
getEffectiveGenericOidcClientSecret,
decodeGroupsFromJwt as decodeGenericGroupsFromJwt,
postAuthorizationCodeToken as postGenericAuthorizationCodeToken,
stripTrailingSlashes as stripGenericTrailingSlashes,
} from './auth/genericOidc.js';
import { authenticate, authorize, requireRole, optionalAuth } from './auth/middleware.js';
import { guardianService } from './guardianService.js';
import { guardianAssessmentService } from './guardianAssessments.js';
import { guardianJsonMiddleware, registerGuardianRoutes } from './guardianRoutes.js';
import { ROLES, PERMISSIONS } from './auth/roles.js';
import {
createJob,
getJob,
getJobResult,
listJobs,
deleteJob,
cleanupOldJobs,
countActiveJobsForUser,
MAX_CONCURRENT_JOBS_PER_USER,
JOB_TYPE,
JOB_STATUS
} from './jobQueue.js';
import {
saveState,
getState,
listStates,
deleteState,
cleanupOldStates,
getStateStats
} from './debugStateManager.js';
import { scheduleUserCleanup } from './jobs/userCleanup.js';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import { csrfProtection } from './middleware/csrfProtection.js';
import { validateUrl, validateUrlMiddleware } from './utils/urlValidator.js';
import { fetchCatalogueFromUrl } from './utils/fetchCatalogueFromUrl.js';
import { extractCatalogUrlFromSsp, isValidCatalogHref } from './utils/extractCatalogUrlFromSsp.js';
import { SECURITY_CONFIG, CSRF_EXEMPT_PATHS, CSRF_PROTECTED_PATHS, getSsrfValidationOptions } from './utils/securityConfig.js';
import { validateExportGenerationLimits } from './utils/exportLimits.js';
import {
buildProxyFetchHeaders,
isAllowedProxyFetchMethod,
sanitizeProxyResponseHeaders,
} from './utils/proxyFetchHelpers.js';
import {
canAccessJob,
isJobAdmin,
logJobSecurityEvent,
sanitizeJobForClient,
} from './utils/jobAccess.js';
const app = express();
const PORT = process.env.PORT || 3020;
// Set server timeout to 240 seconds (4 minutes) to allow for AI processing
// This is longer than the AI service timeout (180s) to account for overhead
const serverTimeout = 240000; // 240 seconds
// Trust proxy headers when behind reverse proxy (SQUID, Nginx, etc.)
// This ensures correct IP address detection and proper header handling
app.set('trust proxy', true);
/** Throttle GET /api/system/volume-status (sync fs + exec) before optionalAuth and handler. */
const volumeStatusRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 30,
standardHeaders: true,
legacyHeaders: false,
validate: { trustProxy: true },
handler: (req, res) => {
res.status(429).json({
error: 'Too many requests',
message: 'Volume status checks are rate limited. Try again later.',
});
},
});
/** Throttle OIDC exchange-token endpoints before IdP/network and session work. */
const oidcExchangeTokenRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 20,
standardHeaders: true,
legacyHeaders: false,
validate: { trustProxy: true },
handler: (req, res) => {
res.status(429).json({
success: false,
error: 'Too many sign-in attempts. Try again in a few minutes.',
});
},
});
const oktaExchangeTokenRateLimiter = oidcExchangeTokenRateLimiter;
/** Per-user throttle for expensive async job creation (VULN-37000). Runs after authenticate. */
const jobCreationRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 10,
standardHeaders: true,
legacyHeaders: false,
validate: { trustProxy: true },
keyGenerator: (req) => req.user.id,
handler: (req, res) => {
logJobSecurityEvent('job_create_rate_limited', req.user, 'failure', {
'client.address': req.ip,
reason: 'window_limit',
});
res.status(429).json({
success: false,
error: 'Too many job creation requests',
message: 'Job creation is rate limited. Try again later.',
});
},
});
function enforceJobConcurrencyLimit(req, res, next) {
const activeCount = countActiveJobsForUser(req.user?.id);
if (activeCount >= MAX_CONCURRENT_JOBS_PER_USER) {
logJobSecurityEvent('job_create_rate_limited', req.user, 'failure', {
'client.address': req.ip,
reason: 'concurrent_limit',
'job.active.count': activeCount,
});
return res.status(429).json({
success: false,
error: 'Too many active jobs',
message: `Maximum ${MAX_CONCURRENT_JOBS_PER_USER} concurrent jobs allowed. Wait for existing jobs to finish.`,
});
}
return next();
}
function denyJobAccess(req, res, access) {
logJobSecurityEvent('job_access_denied', req.user, 'failure', {
'job.id': req.params.jobId,
'http.status_code': access.status,
'client.address': req.ip,
});
return res.status(access.status).json({
success: false,
error: access.error,
});
}
function buildJobOwnerMetadata(req) {
return {
userId: req.user.id,
username: req.user.username,
};
}
// Configure CORS to allow authentication headers through reverse proxy
app.use(cors({
origin: true, // Allow all origins (can be restricted to specific domains if needed)
credentials: true, // Allow cookies and authentication headers
exposedHeaders: ['Authorization', 'X-Session-Token'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Session-Token', 'X-Requested-With'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH']
}));
app.use('/api/guardian', guardianJsonMiddleware);
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
// Security Middleware
// Cookie parser (required for CSRF)
app.use(cookieParser());
// Session management (required for CSRF)
app.use(session(SECURITY_CONFIG.session));
// ============================================================================
// CSRF PROTECTION CONFIGURATION (v1.6.5 Architectural Decision)
// ============================================================================
//
// KODIAK SECURITY SCANNER NOTICE:
// Adobe Kodiak scanner flags all /api/ endpoints with "UseCsurfForExpress" findings.
// These are FALSE POSITIVES based on our v1.6.5 architectural decision.
//
// ARCHITECTURAL DECISION: All /api/ endpoints are EXEMPT from CSRF protection
//
// WHY THIS IS SECURE:
// 1. Bearer Token Authentication is Immune to CSRF
// - Protected endpoints use "Authorization: Bearer <token>" header
// - Browsers do NOT automatically send Authorization headers in cross-origin requests
// - Attackers CANNOT force a victim's browser to send valid Bearer tokens
// - This is fundamentally different from cookie-based auth (which IS vulnerable to CSRF)
//
// 2. Public Endpoints by Design
// - Core functionality (catalogue loading, report generation) is intentionally public
// - These endpoints do not modify user account state
// - Input validation and SSRF protection remain active
//
// 3. Defense-in-Depth Layers Remain Active:
// ✅ Bearer token authentication (authenticate middleware)
// ✅ Role-Based Access Control (requireRole(), authorize())
// ✅ SSRF protection (validateUrl())
// ✅ Rate limiting (all endpoints)
// ✅ Input validation (per-endpoint)
// ✅ Session cookies use sameSite: 'strict'
//
// INDUSTRY STANDARD:
// This pattern is used by all major REST APIs (GitHub, AWS, Azure, Google Cloud)
//
// REFERENCES:
// - Documentation: docs/SECURITY.md
// - OWASP CSRF Prevention: https://cheatsheetsecurity.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
// - Auth0 Cookies vs Tokens: https://auth0.com/blog/cookies-vs-tokens-definitive-guide/
// - Test Coverage: test_cases/backend/integration/csrf-api.test.js (60+ security tests)
//
// KODIAK SUPPRESSION JUSTIFICATION:
// Scanner cannot recognize that Bearer token authentication makes CSRF irrelevant.
// This is a tool limitation, not a security vulnerability.
// ============================================================================
// CSRF Protection (csrf package — replaces deprecated csurf) - exempt certain paths, enforce on CSRF_PROTECTED_PATHS
app.use((req, res, next) => {
// Skip CSRF for GET/HEAD/OPTIONS requests (safe methods)
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
return next();
}
// Always apply CSRF for explicitly protected paths (e.g. Okta exchange-token)
if (CSRF_PROTECTED_PATHS.some(p => req.path === p)) {
if (SECURITY_CONFIG.csrf.enabled) {
return csrfProtection(req, res, next);
}
return next();
}
// Skip CSRF for exempted paths
if (CSRF_EXEMPT_PATHS.some(path => req.path.startsWith(path))) {
return next();
}
// Apply CSRF protection for other state-changing requests
if (SECURITY_CONFIG.csrf.enabled) {
csrfProtection(req, res, next);
} else {
next();
}
});
// CSRF token endpoint
app.get('/api/csrf-token', csrfProtection, (req, res) => {
res.json({ csrfToken: req.csrfToken() });
});
// Serve static files from the public folder (warning page for backend)
registerGuardianRoutes(app, authenticate);
app.use(express.static('public'));
// Health check endpoint for Docker (liveness — process listening)
app.get('/health', (req, res) => {
res.status(200).json({ status: 'healthy', service: 'Keekar\'s OSCAL SOA/SSP/CCM Generator', version: SERVICE_VERSION });
});
// Readiness: SPA, config, and (on EC2) Secrets Manager cache for enabled SSO providers
app.get('/health/ready', (req, res) => {
const result = evaluateReadiness();
if (result.ready) {
return res.status(200).json({ status: 'ready', version: SERVICE_VERSION, checks: result.checks });
}
return res.status(503).json({ status: 'not_ready', version: SERVICE_VERSION, checks: result.checks });
});
/**
* Volume status endpoint - Check persistent storage health
* GET /api/system/volume-status
*
* Returns information about the persistent data volume:
* - Whether /data directory exists and is writable
* - Config and users file locations and status
* - File sizes and last modified timestamps
*
* Authentication optional - shows public info if not authenticated,
* detailed info if authenticated as Platform Admin
*/
app.get('/api/system/volume-status', volumeStatusRateLimiter, optionalAuth, async (req, res) => {
try {
const fs = await import('fs');
const path = await import('path');
const status = {
timestamp: new Date().toISOString(),
volumeMount: {
path: '/data',
exists: false,
writable: false,
type: 'unknown'
},
config: {
path: 'unknown',
exists: false,
size: 0,
lastModified: null
},
users: {
path: 'unknown',
exists: false,
size: 0,
lastModified: null,
userCount: 0
},
persistence: {
enabled: false,
recommendation: ''
}
};
// Check /data volume mount
if (fs.existsSync('/data')) {
status.volumeMount.exists = true;
try {
fs.accessSync('/data', fs.constants.W_OK);
status.volumeMount.writable = true;
// Try to determine if it's a volume or directory
const stats = fs.statSync('/data');
status.volumeMount.type = stats.isDirectory() ? 'directory' : 'other';
} catch (err) {
status.volumeMount.writable = false;
}
}
// Check config file (align with configManager getConfigPath ordering)
const repoRoot = path.join(__dirname, '..');
const siblingData = path.join(repoRoot, '..', 'OSCAL_Reports_data');
const configPaths = [
process.env.CONFIG_PATH,
'/data/config.json',
process.env.USERS_PATH ? path.join(path.dirname(process.env.USERS_PATH), 'config.json') : null,
process.env.OSCAL_DATA_DIR ? path.join(process.env.OSCAL_DATA_DIR, 'config.json') : null,
fs.existsSync(siblingData) ? path.join(siblingData, 'config.json') : null,
path.join(repoRoot, 'config', 'app', 'config.json')
].filter(Boolean);
for (const configPath of configPaths) {
if (fs.existsSync(configPath)) {
status.config.path = configPath;
status.config.exists = true;
const stats = fs.statSync(configPath);
status.config.size = stats.size;
status.config.lastModified = stats.mtime.toISOString();
break;
}
}
// Check users file (align with userManager getUsersPath)
const usersPaths = [
process.env.USERS_PATH,
'/data/users.json',
process.env.CONFIG_PATH ? path.join(path.dirname(process.env.CONFIG_PATH), 'users.json') : null,
process.env.OSCAL_DATA_DIR ? path.join(process.env.OSCAL_DATA_DIR, 'users.json') : null,
fs.existsSync(siblingData) ? path.join(siblingData, 'users.json') : null,
path.join(repoRoot, 'config', 'app', 'users.json')
].filter(Boolean);
for (const usersPath of usersPaths) {
if (fs.existsSync(usersPath)) {
status.users.path = usersPath;
status.users.exists = true;
const stats = fs.statSync(usersPath);
status.users.size = stats.size;
status.users.lastModified = stats.mtime.toISOString();
// Count users (only if authenticated as admin)
if (req.user && req.user.role === ROLES.PLATFORM_ADMIN) {
try {
const data = fs.readFileSync(usersPath, 'utf-8');
const users = JSON.parse(data);
status.users.userCount = users.length;
} catch (err) {
status.users.userCount = -1; // Error reading
}
}
break;
}
}
// Determine persistence status
if (status.config.path.startsWith('/data') && status.users.path.startsWith('/data')) {
status.persistence.enabled = true;
status.persistence.recommendation = 'Volume persistence is properly configured';
} else if (status.volumeMount.exists && status.volumeMount.writable) {
status.persistence.enabled = false;
status.persistence.recommendation = 'Volume mount exists but files are not using it. Restart container to initialize.';
} else {
status.persistence.enabled = false;
status.persistence.recommendation = 'No persistent volume detected. Data will be lost on container updates. Mount a volume to /data';
}
// Add disk usage if available and user is admin
if (req.user && req.user.role === ROLES.PLATFORM_ADMIN) {
try {
const { execSync } = await import('child_process');
const dfOutput = execSync('df -h /data 2>/dev/null || echo "N/A"').toString();
status.diskUsage = dfOutput.trim();
} catch (err) {
status.diskUsage = 'Unable to determine disk usage';
}
}
res.json(status);
} catch (error) {
console.error('❌ Volume status check error:', error);
res.status(500).json({
error: 'Failed to check volume status',
message: error.message
});
}
});
// Test endpoint to verify suggestion engine is loaded (for debugging)
app.get('/api/test-suggestions', (req, res) => {
try {
const testControl = {
id: 'AC-1',
title: 'Access Control Policy',
description: 'Test control for suggestion engine'
};
const suggestions = suggestControlImplementation(testControl, []);
res.json({
success: true,
message: 'Suggestion engine is working',
testControl: testControl.id,
suggestions: suggestions
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
});
}
});
// Debug endpoint for integrity hash troubleshooting
app.post('/api/debug-integrity', async (req, res) => {
try {
const { oscalData } = req.body;
if (!oscalData) {
return res.status(400).json({ error: 'OSCAL data is required' });
}
// Get integrity info
const integrityInfo = getIntegrityInfo(oscalData);
// Verify hash
const verificationResult = verifyIntegrityHash(oscalData);
// Get metadata props for inspection
const metadata = oscalData['system-security-plan']?.metadata || oscalData.metadata;
const props = metadata?.props || [];
res.json({
success: true,
integrityInfo: integrityInfo,
verification: verificationResult,
metadata: {
propsCount: props.length,
props: props.map(p => ({
name: p.name,
ns: p.ns,
value: p.value?.substring(0, 32) + (p.value?.length > 32 ? '...' : ''),
class: p.class
}))
}
});
} catch (error) {
console.error('Debug integrity error:', error);
res.status(500).json({
success: false,
error: error.message,
stack: error.stack
});
}
});
// Get default credentials (for frontend display)
app.get('/api/auth/default-credentials', async (req, res) => {
try {
// Get actual users to determine their password timestamps
const users = await getAllUsers();
const defaultPasswords = {};
const defaultUsernames = ['admin', 'user', 'assessor'];
for (const username of defaultUsernames) {
const user = users.find(u => u.username === username);
if (user && user.updatedAt) {
// Generate password based on when user was last updated (use UTC to match server timezone)
const updateDate = new Date(user.updatedAt);
const day = String(updateDate.getUTCDate()).padStart(2, '0');
const month = String(updateDate.getUTCMonth() + 1).padStart(2, '0');
const year = String(updateDate.getUTCFullYear()).slice(-2);
const hour = String(updateDate.getUTCHours()).padStart(2, '0');
defaultPasswords[username] = `${username}#${day}${month}${year}${hour}`;
} else {
// Fallback to current time if user not found
defaultPasswords[username] = generateDefaultPasswordFromEnv(username);
}
}
res.json({
success: true,
passwords: defaultPasswords,
format: 'username#DDMMYYHH',
note: 'These are default credentials based on user update timestamp. Change them in production.'
});
} catch (error) {
console.error('Error generating default credentials:', error);
res.status(500).json({
error: 'Failed to generate default credentials',
details: error.message
});
}
});
/**
* Diagnostic endpoint - Check user status and config (for debugging)
*/
app.get('/api/auth/diagnostics', (req, res) => {
try {
const fs = require('fs');
const path = require('path');
const configDir = path.join(process.cwd(), 'config', 'app');
const usersFile = path.join(configDir, 'users.json');
const diagnostics = {
configDirectory: {
path: configDir,
exists: fs.existsSync(configDir),
writable: false,
readable: false
},
usersFile: {
path: usersFile,
exists: fs.existsSync(usersFile),
readable: false,
writable: false,
size: 0
},
users: {
count: 0,
usernames: []
},
buildTimestamp: process.env.BUILD_TIMESTAMP || 'not set',
environment: process.env.NODE_ENV || 'production'
};
// Check directory permissions
if (diagnostics.configDirectory.exists) {
try {
fs.accessSync(configDir, fs.constants.W_OK);
diagnostics.configDirectory.writable = true;
} catch (e) {
diagnostics.configDirectory.writable = false;
diagnostics.configDirectory.writableError = e.message;
}
try {
fs.accessSync(configDir, fs.constants.R_OK);
diagnostics.configDirectory.readable = true;
} catch (e) {
diagnostics.configDirectory.readable = false;
diagnostics.configDirectory.readableError = e.message;
}
}
// Check users file
if (diagnostics.usersFile.exists) {
try {
fs.accessSync(usersFile, fs.constants.R_OK);
diagnostics.usersFile.readable = true;
const stats = fs.statSync(usersFile);
diagnostics.usersFile.size = stats.size;
const users = JSON.parse(fs.readFileSync(usersFile, 'utf-8'));
diagnostics.users.count = users.length;
diagnostics.users.usernames = users.map(u => u.username);
} catch (e) {
diagnostics.usersFile.readable = false;
diagnostics.usersFile.readError = e.message;
}
}
// Try to get users via userManager
try {
const allUsers = getAllUsers();
diagnostics.users.actualCount = allUsers.length;
diagnostics.users.actualUsernames = allUsers.map(u => u.username);
} catch (e) {
diagnostics.users.error = e.message;
}
res.json({
success: true,
diagnostics: diagnostics,
recommendations: []
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
});
}
});
/**
* Diagnostic endpoint - Check user status (for debugging)
*/
app.get('/api/auth/diagnostic', (req, res) => {
try {
const { username } = req.query;
const users = getAllUsers();
if (username) {
const user = users.find(u => u.username === username);
if (user) {
return res.json({
found: true,
user: user,
canLogin: user.isActive === true,
message: user.isActive ? 'User can login' : 'User is inactive - cannot login'
});
} else {
return res.json({
found: false,
message: `User '${username}' not found`
});
}
}
// Return all users for diagnostic
const usersWithStatus = users.map(user => ({
...user,
canLogin: user.isActive === true
}));
res.json({
totalUsers: users.length,
users: usersWithStatus
});
} catch (error) {
console.error('Diagnostic error:', error);
res.status(500).json({
error: 'Diagnostic failed',
message: error.message
});
}
});
// ===== AUTHENTICATION & AUTHORIZATION ENDPOINTS =====
/**
* Login endpoint
*/
app.post('/api/auth/login', async (req, res) => {
try {
const { username, password } = req.body;
console.log(`\n🔐 Login request received`);
console.log(` Username: ${username}`);
console.log(` Password provided: ${password ? 'Yes' : 'No'}`);
if (!username || !password) {
console.log(`❌ Missing credentials`);
return res.status(400).json({
error: 'Missing credentials',
message: 'Username and password are required'
});
}
const user = await authenticateUser(username, password);
if (!user) {
console.log(`❌ Authentication failed for: ${username}`);
return res.status(401).json({
error: 'Invalid credentials',
message: 'Username or password is incorrect, or user account is inactive'
});
}
console.log(`✅ User logged in successfully: ${user.username} (${user.role})`);
res.json({
success: true,
user: {
id: user.id,
username: user.username,
email: user.email,
role: user.role,
fullName: user.fullName
},
sessionToken: user.sessionToken
});
} catch (error) {
console.error('❌ Login error:', error);
console.error(' Stack:', error.stack);
res.status(500).json({
error: 'Login failed',
message: error.message
});
}
});
// Okta OIDC state: signed state (preferred, works across restarts and load-balanced instances) + legacy in-memory/file store.
const OKTA_STATE_TTL_MS = 15 * 60 * 1000;
const oktaOidcStateStore = new Map();
const OKTA_STATE_FILE = path.join(__dirname, '..', 'config', 'app', 'okta_oidc_state.json');
function base64UrlEncode(buf) {
return Buffer.from(buf).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function base64UrlDecode(str) {
const padded = str.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice(0, (4 - (str.length % 4)) % 4);
return Buffer.from(padded, 'base64');
}
/** Generate PKCE code_verifier (43–128 chars per RFC 7636). */
function generateCodeVerifier() {
return base64UrlEncode(crypto.randomBytes(32));
}
/** Compute PKCE code_challenge = base64url(SHA256(ASCII(code_verifier))). */
function computeCodeChallenge(codeVerifier) {
const hash = crypto.createHash('sha256').update(codeVerifier, 'utf8').digest();
return base64UrlEncode(hash);
}
/** Create signed state payload so any instance can validate (no server-side store needed). Includes code_verifier for PKCE when Okta requires it. */
function createSignedOktaState(redirectUri, clientSecret, codeVerifier) {
const payload = {
redirectUri: redirectUri || '',
createdAt: Date.now(),
rnd: crypto.randomBytes(8).toString('hex'),
...(codeVerifier ? { codeVerifier } : {})
};
const payloadB64 = base64UrlEncode(Buffer.from(JSON.stringify(payload), 'utf8'));
const sig = crypto.createHmac('sha256', clientSecret || '').update(payloadB64).digest();
return `${payloadB64}.${base64UrlEncode(sig)}`;
}
/** Verify signed state; returns { redirectUri, codeVerifier? } or null. */
function verifySignedOktaState(state, clientSecret) {
if (!state || typeof state !== 'string' || !clientSecret) return null;
const dot = state.indexOf('.');
if (dot <= 0 || dot === state.length - 1) return null;
const payloadB64 = state.slice(0, dot);
const sigB64 = state.slice(dot + 1);
try {
const expectedSig = crypto.createHmac('sha256', clientSecret).update(payloadB64).digest();
const expectedB64 = base64UrlEncode(expectedSig);
if (sigB64 !== expectedB64) return null;
const payload = JSON.parse(base64UrlDecode(payloadB64).toString('utf8'));
if (!payload || typeof payload.createdAt !== 'number') return null;
if (Date.now() - payload.createdAt > OKTA_STATE_TTL_MS) return null;
return {
redirectUri: payload.redirectUri || '',
...(payload.codeVerifier ? { codeVerifier: payload.codeVerifier } : {})
};
} catch (_) {
return null;
}
}
function loadOktaStateFromFile() {
try {
if (!fs.existsSync(OKTA_STATE_FILE)) return;
const raw = fs.readFileSync(OKTA_STATE_FILE, 'utf8');
const data = JSON.parse(raw);
const now = Date.now();
if (data && typeof data === 'object') {
for (const [s, entry] of Object.entries(data)) {
if (entry?.createdAt && (now - entry.createdAt) < OKTA_STATE_TTL_MS) {
oktaOidcStateStore.set(s, {
createdAt: entry.createdAt,
redirectUri: entry.redirectUri || '',
...(entry.codeVerifier ? { codeVerifier: entry.codeVerifier } : {})
});
}
}
}
} catch (_) {
// ignore
}
}
function persistOktaState() {
try {
const dir = path.dirname(OKTA_STATE_FILE);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const now = Date.now();
const obj = {};
for (const [s, data] of oktaOidcStateStore.entries()) {
if (data?.createdAt && (now - data.createdAt) < OKTA_STATE_TTL_MS) {
obj[s] = {
createdAt: data.createdAt,
redirectUri: data.redirectUri || '',
...(data.codeVerifier ? { codeVerifier: data.codeVerifier } : {})
};
}
}
fs.writeFileSync(OKTA_STATE_FILE, JSON.stringify(obj), 'utf8');
} catch (_) {
// ignore
}
}
function cleanupOktaState() {
const now = Date.now();
for (const [s, data] of oktaOidcStateStore.entries()) {
if (now - data.createdAt > OKTA_STATE_TTL_MS) oktaOidcStateStore.delete(s);
}
persistOktaState();
}
loadOktaStateFromFile();
setInterval(cleanupOktaState, 60 * 1000);
/**
* Normalize Okta OIDC discovery JSON for callers (authorize, token exchange, SSO test).
*/
function normalizeOktaDiscoveryDoc(data, discoveryUrl) {
const scopes = Array.isArray(data.scopes_supported) ? data.scopes_supported : [];
const claims = Array.isArray(data.claims_supported) ? data.claims_supported : [];
return {
authorization_endpoint: data.authorization_endpoint,
token_endpoint: data.token_endpoint,
userinfo_endpoint: data.userinfo_endpoint,
issuer: typeof data.issuer === 'string' ? data.issuer : '',
scopes_supported: scopes,
claims_supported: claims,
discovery_url: discoveryUrl,
};
}
/**
* Fetch Okta OIDC discovery document. Returns endpoints plus issuer, scopes_supported, claims_supported, discovery_url.
* Tries: oauth2/{authServerId}/.well-known, then .well-known, then oauth2/default/.well-known.
*/
async function fetchOktaDiscovery(domain, authServerId) {
const base = `https://${domain}`;
const toTry = authServerId
? [`${base}/oauth2/${authServerId}/.well-known/openid-configuration`]
: [
`${base}/.well-known/openid-configuration`,
`${base}/oauth2/default/.well-known/openid-configuration`
];
for (const url of toTry) {
try {
const res = await axios.get(url, { timeout: 8000, validateStatus: () => true });
if (res.status === 200 && res.data?.authorization_endpoint) {
return normalizeOktaDiscoveryDoc(res.data, url);
}
} catch (_) {
// continue to next URL
}
}
if (authServerId) {
const fallback = `${base}/.well-known/openid-configuration`;
try {
const res = await axios.get(fallback, { timeout: 8000, validateStatus: () => true });
if (res.status === 200 && res.data?.authorization_endpoint) {
return normalizeOktaDiscoveryDoc(res.data, fallback);
}
} catch (_) {
// ignore
}
}
return null;
}
/**
* POST authorization_code grant to Okta token URL. Sends client_secret in the body first (common default).
* If Okta responds with invalid_client / invalid client secret (not invalid_grant), retries per RFC 6749 §2.3.1
* using HTTP Basic (client_id:client_secret), which some org policies require.
* @returns {Promise<{ response: object, retriedWithBasic: boolean }>}
*/
async function postOktaAuthorizationCodeToken(