-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1617 lines (1425 loc) · 47.8 KB
/
server.js
File metadata and controls
1617 lines (1425 loc) · 47.8 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
const express = require("express");
const http = require("http");
const WebSocket = require("ws");
const path = require("path");
const fs = require("fs");
const axios = require("axios");
const session = require("express-session");
const crypto = require("crypto");
const bcrypt = require("bcryptjs");
const os = require("os");
const util = require("util");
const { exec } = require("child_process");
// Import our library modules
const ServiceManager = require("./lib/services");
const PRPCClient = require("./lib/api");
const LogManager = require("./lib/logs");
const NetworkManager = require("./lib/network");
const SystemMonitor = require("./lib/system");
const terminalManager = require("./lib/terminal");
const CentralConnector = require("./lib/central/central-connector");
const { getComponentVersions } = require("./lib/component-versions");
const { getPodPubkey, refreshPodPubkey } = require("./lib/pod-pubkey");
const { detectPodCluster } = require("./lib/pod-cluster");
const execPromise = util.promisify(exec);
const ALLOWED_POD_MAN_ROLES = new Set(["admin", "standard", "demo"]);
const LOCAL_AUDIT_LOG_PATH = path.resolve("./pod-man-audit.log");
// Load configuration
const config = JSON.parse(fs.readFileSync("./config.json", "utf8"));
function randomToken(bytes = 24) {
return crypto.randomBytes(bytes).toString("hex");
}
function normalizeConfig() {
let changed = false;
config.authentication = config.authentication || {};
config.authentication.users = Array.isArray(config.authentication.users) ? config.authentication.users : [];
if (typeof config.authentication.enabled !== "boolean") {
config.authentication.enabled = false;
changed = true;
}
if (!config.authentication.sessionSecret) {
config.authentication.sessionSecret = randomToken(32);
console.log("✓ Generated session secret");
changed = true;
}
if (typeof config.authentication.setupToken !== "string") {
config.authentication.setupToken = "";
changed = true;
}
if (config.authentication.users.length === 0 && !config.authentication.setupToken) {
config.authentication.setupToken = randomToken(16);
console.log("[Setup] Generated one-time setup token. Retrieve it from config.json or service logs before first setup.");
changed = true;
}
if (config.authentication.users.length > 0 && config.authentication.setupToken) {
config.authentication.setupToken = "";
changed = true;
}
if (config.authentication.users.length > 0 && !config.authentication.enabled) {
config.authentication.enabled = true;
changed = true;
}
config.centralManagement = config.centralManagement || {};
const centralDefaults = {
ownerCentralUserId: "",
ownerCentralEmail: "",
ownerBoundAt: "",
ownerBindingSource: "",
unattendedUpgradesEnabled: true,
remoteServiceControlEnabled: true
};
for (const [key, value] of Object.entries(centralDefaults)) {
if (config.centralManagement[key] === undefined) {
config.centralManagement[key] = value;
changed = true;
}
}
return changed;
}
function saveConfig() {
fs.writeFileSync("./config.json", JSON.stringify(config, null, 2), "utf8");
}
function normalizeLocalAuditOutcome(value) {
const normalized = String(value || "success").trim().toLowerCase();
return ["success", "failed", "denied"].includes(normalized) ? normalized : "success";
}
function buildLocalAuditActor(req) {
return {
username: req?.session?.username || null,
role: req?.session?.role || null,
centralUserId: req?.session?.centralUserId || null,
centralEmail: req?.session?.centralEmail || null,
ssoAuthenticated: Boolean(req?.session?.ssoAuthenticated)
};
}
function logLocalAuditEvent(eventType, {
req = null,
outcome = "success",
summary = "",
details = {}
} = {}) {
try {
const entry = {
timestamp: new Date().toISOString(),
eventType,
outcome: normalizeLocalAuditOutcome(outcome),
summary: summary || null,
actor: buildLocalAuditActor(req),
ipAddress: req?.ip || req?.socket?.remoteAddress || null,
userAgent: req?.get?.("user-agent") || req?.headers?.["user-agent"] || null,
details
};
fs.appendFileSync(LOCAL_AUDIT_LOG_PATH, `${JSON.stringify(entry)}\n`, "utf8");
} catch (error) {
console.error("[Audit] Failed to write local audit entry:", error.message);
}
}
function getAllowedDirectTerminalOrigins(req) {
const port = Number(config.server?.port || 7000);
const allowed = new Set();
for (const host of ["127.0.0.1", "localhost"]) {
allowed.add(`http://${host}:${port}`);
allowed.add(`https://${host}:${port}`);
}
const requestHost = String(req?.headers?.host || "").trim();
if (requestHost) {
allowed.add(`http://${requestHost}`);
allowed.add(`https://${requestHost}`);
}
return allowed;
}
function isAllowedDirectTerminalOrigin(req) {
const origin = String(req?.headers?.origin || "").trim();
return origin ? getAllowedDirectTerminalOrigins(req).has(origin) : false;
}
async function getClusterAwareCreditsSummary() {
const [clusterResult, pubkeyResult] = await Promise.all([
detectPodCluster(),
getPodPubkey()
]);
const cluster = clusterResult.cluster || null;
const creditsEndpoint = clusterResult.creditsEndpoint || null;
if (!creditsEndpoint) {
return {
success: false,
error: cluster
? `No credits endpoint is configured for cluster ${cluster}`
: "Unable to detect pod cluster from pod.service",
cluster,
clusterLabel: clusterResult.clusterLabel,
creditsEndpoint,
pubkey: pubkeyResult.pubkey || null,
pubkeyResult
};
}
const creditsResp = await axios.get(creditsEndpoint, { timeout: 5000 });
const list = Array.isArray(creditsResp.data?.pods_credits) ? creditsResp.data.pods_credits : [];
const creditsOnly = list
.map((entry) => entry.credits)
.filter((value) => typeof value === "number")
.sort((a, b) => a - b);
const count = creditsOnly.length;
const percentile95 = count > 0 ? creditsOnly[Math.floor(0.95 * (count - 1))] : null;
const threshold = percentile95 !== null ? Math.round(percentile95 * 0.8) : null;
const maxCredits = count > 0 ? creditsOnly[count - 1] : null;
const pubkey = pubkeyResult.pubkey || null;
const localEntry = pubkey ? list.find((entry) => entry.pod_id === pubkey) : null;
const localCredits = localEntry ? localEntry.credits : null;
return {
success: true,
cluster,
clusterLabel: clusterResult.clusterLabel,
creditsEndpoint,
leaderboardScope: clusterResult.clusterLabel,
pubkey,
pubkeyResult,
list,
localCredits,
percentile95,
threshold,
maxCredits,
eligible: threshold !== null && localCredits !== null ? localCredits >= threshold : null,
totalPods: count,
clusterDetails: clusterResult
};
}
if (normalizeConfig()) {
saveConfig();
}
if (config.authentication.users.length === 0 && config.authentication.setupToken) {
console.log(`[Setup] One-time setup token: ${config.authentication.setupToken}`);
}
// Initialize Central Connector (pass server config for dynamic pod-man port)
const centralConnector = new CentralConnector(config.centralManagement || {}, config.server || {}, {
getCentralConfig: () => config.centralManagement || {},
updateCentralConfig: (patch = {}) => {
config.centralManagement = {
...(config.centralManagement || {}),
...patch
};
saveConfig();
},
auditLogger: (eventType, details = {}) => {
const line = JSON.stringify({
timestamp: new Date().toISOString(),
eventType,
...details
});
fs.appendFileSync("./central-audit.log", `${line}\n`, "utf8");
}
});
// Initialize Express app
const app = express();
app.set("trust proxy", "loopback");
const server = http.createServer(app);
const wss = new WebSocket.Server({
server,
verifyClient: (info, callback) => {
try {
const requestPath = new URL(info.req.url || "/", "http://localhost").pathname;
if (requestPath !== "/terminal") {
logLocalAuditEvent("podman_terminal_denied", {
req: info.req,
outcome: "denied",
summary: "Terminal websocket denied before upgrade",
details: { reason: "invalid-terminal-path", path: requestPath }
});
callback(false, 404, "Not found");
return;
}
if (!isAllowedDirectTerminalOrigin(info.req)) {
logLocalAuditEvent("podman_terminal_denied", {
req: info.req,
outcome: "denied",
summary: "Terminal websocket denied before upgrade",
details: {
reason: "origin-denied",
origin: info.req.headers?.origin || null,
allowedOrigins: Array.from(getAllowedDirectTerminalOrigins(info.req))
}
});
callback(false, 403, "Terminal origin denied");
return;
}
callback(true);
} catch (error) {
callback(false, 400, "Invalid terminal upgrade request");
}
}
});
// Initialize Terminal Manager
// Middleware
app.use(express.json({ limit: '10mb' }));
// Session middleware for authentication
const sessionMiddleware = session({
name: "pod-man.sid",
secret: config.authentication.sessionSecret,
resave: false,
saveUninitialized: false,
proxy: true,
cookie: {
maxAge: config.authentication.sessionTimeout,
httpOnly: true,
sameSite: "strict",
secure: "auto"
}
});
app.use(sessionMiddleware);
app.use(express.static("public"));
// Rate limiting (simple in-memory implementation)
const requestCounts = new Map();
const RATE_LIMIT_WINDOW = 60000; // 1 minute
const MAX_REQUESTS = config.security.rateLimit.maxRequestsPerMinute || 60;
function checkRateLimit(req, res, next) {
if (!config.security.rateLimit.enabled) {
return next();
}
const ip = req.ip;
const now = Date.now();
if (!requestCounts.has(ip)) {
requestCounts.set(ip, { count: 1, resetTime: now + RATE_LIMIT_WINDOW });
return next();
}
const record = requestCounts.get(ip);
if (now > record.resetTime) {
record.count = 1;
record.resetTime = now + RATE_LIMIT_WINDOW;
return next();
}
if (record.count >= MAX_REQUESTS) {
return res.status(429).json({ error: "Rate limit exceeded" });
}
record.count++;
next();
}
app.use(checkRateLimit);
// ============================================================================
// AUTHENTICATION HELPERS
// ============================================================================
function getCentralHttpBaseUrl() {
const centralUrl = config.centralManagement?.centralUrl;
if (!centralUrl) {
throw new Error("Central URL is not configured");
}
const parsed = new URL(centralUrl);
parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
parsed.pathname = "";
parsed.search = "";
parsed.hash = "";
return parsed.toString().replace(/\/$/, "");
}
function setAuthenticatedSession(req, sessionUser) {
req.session.username = sessionUser.username;
req.session.role = sessionUser.role;
req.session.centralUserId = sessionUser.userId || null;
req.session.centralEmail = sessionUser.email || null;
req.session.ssoAuthenticated = Boolean(sessionUser.ssoAuthenticated);
}
function isAllowedPodManRole(role) {
return ALLOWED_POD_MAN_ROLES.has(String(role || "").trim().toLowerCase());
}
function normalizePodManRole(role) {
return String(role || "").trim().toLowerCase();
}
function assertAllowedPodManRole(role) {
const normalized = normalizePodManRole(role);
if (!isAllowedPodManRole(normalized)) {
throw new Error(`Unsupported role: ${role || "missing"}`);
}
return normalized;
}
function establishAuthenticatedSession(req, sessionUser, callback) {
req.session.regenerate((error) => {
if (error) {
callback(error);
return;
}
setAuthenticatedSession(req, sessionUser);
req.session.save(callback);
});
}
async function ensureRestrictedShellUser(scriptName) {
await execPromise(`bash ${path.resolve("./scripts", scriptName)}`);
}
async function ensureAuxiliaryShellAccounts() {
const roles = new Set((config.authentication.users || []).map((user) => user.role));
if (roles.has("demo")) {
try {
await ensureRestrictedShellUser("setup-demo-user.sh");
} catch (error) {
console.error("Failed to ensure demo shell user:", error.message);
}
}
if (roles.has("standard")) {
try {
await ensureRestrictedShellUser("setup-standard-user.sh");
} catch (error) {
console.error("Failed to ensure standard shell user:", error.message);
}
}
}
// Auth middleware
function requireAuth(req, res, next) {
if (!config.authentication.enabled) {
return next();
}
if (!req.session || !req.session.username) {
return res.status(401).json({ success: false, error: "Not authenticated" });
}
next();
}
// Admin-only middleware
function requireAdmin(req, res, next) {
if (!config.authentication.enabled) {
return next();
}
if (!req.session || !req.session.username || req.session.role !== "admin") {
return res.status(403).json({ success: false, error: "Admin access required" });
}
next();
}
// Admin or Standard user middleware (excludes demo)
function requireAdminOrStandard(req, res, next) {
if (!config.authentication.enabled) {
return next();
}
if (!req.session || !req.session.username) {
return res.status(401).json({ success: false, error: "Not authenticated" });
}
if (!["admin", "standard"].includes(req.session.role)) {
return res.status(403).json({ success: false, error: "This role cannot perform that action" });
}
// Allow admin and standard
next();
}
// ============================================================================
// API ENDPOINTS
// ============================================================================
// ============================================================================
// AUTHENTICATION ENDPOINTS
// ============================================================================
/**
* Check if setup is needed (no users exist)
*/
app.get("/api/setup/status", (req, res) => {
res.json({
success: true,
needsSetup: config.authentication.users.length === 0,
setupTokenRequired: config.authentication.users.length === 0
});
});
/**
* Initialize first-time setup (create admin + optional users)
*/
app.post("/api/setup/initialize", async (req, res) => {
try {
// Only allow if no users exist
if (config.authentication.users.length > 0) {
return res.status(403).json({ success: false, error: "Setup already completed" });
}
const { users, setupToken } = req.body;
if (!setupToken || setupToken !== config.authentication.setupToken) {
return res.status(403).json({ success: false, error: "Valid setup token required" });
}
if (!users || !Array.isArray(users) || users.length === 0) {
return res.status(400).json({ success: false, error: "No users provided" });
}
// Validate and hash passwords
const newUsers = [];
let hasDemoUser = false;
let hasStandardUser = false;
for (const user of users) {
if (!user.username || !user.password || !user.role) {
return res.status(400).json({ success: false, error: "Invalid user data" });
}
let normalizedRole;
try {
normalizedRole = assertAllowedPodManRole(user.role);
} catch (error) {
return res.status(400).json({ success: false, error: error.message });
}
const hashedPassword = await bcrypt.hash(user.password, 10);
newUsers.push({
username: user.username,
password: hashedPassword,
role: normalizedRole
});
if (normalizedRole === 'demo') {
hasDemoUser = true;
} else if (normalizedRole === 'standard') {
hasStandardUser = true;
}
}
// Save users to config
config.authentication.enabled = true;
config.authentication.users = newUsers;
config.authentication.setupToken = "";
saveConfig();
if (hasDemoUser) {
try {
await ensureRestrictedShellUser("setup-demo-user.sh");
} catch (error) {
console.error('Failed to setup demo user:', error);
}
}
if (hasStandardUser) {
try {
await ensureRestrictedShellUser("setup-standard-user.sh");
} catch (error) {
console.error('Failed to setup standard user:', error);
}
}
res.json({ success: true, message: "Setup completed" });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Login
*/
app.post("/api/login", async (req, res) => {
try {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ success: false, error: "Username and password required" });
}
const user = config.authentication.users.find(u => u.username === username);
if (!user) {
logLocalAuditEvent("podman_local_login_failure", {
req,
outcome: "denied",
summary: "Pod-Man login failed",
details: { username: username || null, reason: "unknown-user" }
});
return res.status(401).json({ success: false, error: "Invalid credentials" });
}
if (!isAllowedPodManRole(user.role)) {
logLocalAuditEvent("podman_local_login_failure", {
req,
outcome: "denied",
summary: "Pod-Man login rejected",
details: { username: user.username, reason: "unsupported-role", role: user.role || null }
});
return res.status(403).json({ success: false, error: "This account has an unsupported role. Contact a local admin." });
}
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
logLocalAuditEvent("podman_local_login_failure", {
req,
outcome: "denied",
summary: "Pod-Man login failed",
details: { username: user.username, reason: "invalid-password" }
});
return res.status(401).json({ success: false, error: "Invalid credentials" });
}
establishAuthenticatedSession(req, {
username: user.username,
role: user.role,
userId: null,
email: null,
ssoAuthenticated: false
}, (error) => {
if (error) {
logLocalAuditEvent("podman_local_login_failure", {
req,
outcome: "failed",
summary: "Pod-Man login session establishment failed",
details: { username: user.username, reason: error.message }
});
return res.status(500).json({ success: false, error: "Failed to establish session" });
}
logLocalAuditEvent("podman_local_login_success", {
req,
summary: "Pod-Man local login succeeded",
details: { username: user.username, role: user.role }
});
res.json({
success: true,
username: user.username,
role: user.role
});
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Logout
*/
app.post("/api/logout", (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).json({ success: false, error: err.message });
}
res.json({ success: true });
});
});
/**
* Check session
*/
app.get("/api/check-session", (req, res) => {
if (req.session && req.session.username) {
res.json({
success: true,
authenticated: true,
username: req.session.username,
role: req.session.role,
centralEmail: req.session.centralEmail || null,
centralUserId: req.session.centralUserId || null,
ssoAuthenticated: Boolean(req.session.ssoAuthenticated)
});
} else {
res.json({
success: true,
authenticated: false
});
}
});
/**
* Central SSO callback
*/
app.get("/sso/central", async (req, res) => {
const token = typeof req.query.token === "string" ? req.query.token.trim() : "";
if (!config.centralManagement?.enabled || !config.centralManagement?.apiKey) {
logLocalAuditEvent("podman_sso_failure", {
req,
outcome: "denied",
summary: "Central SSO rejected",
details: { reason: "central-sso-not-configured" }
});
return res.status(503).send("Central SSO is not configured on this pNode.");
}
if (!token) {
logLocalAuditEvent("podman_sso_failure", {
req,
outcome: "denied",
summary: "Central SSO rejected",
details: { reason: "missing-token" }
});
return res.status(400).send("Missing SSO token.");
}
if (!centralConnector.pnodeId) {
logLocalAuditEvent("podman_sso_failure", {
req,
outcome: "denied",
summary: "Central SSO rejected",
details: { reason: "pnode-not-registered" }
});
return res.status(503).send("This pNode is not registered with Central yet.");
}
try {
console.log(`[Central-SSO] Callback start: pnode=${centralConnector.pnodeId} token=${token.slice(0, 12)}...`);
const centralBaseUrl = getCentralHttpBaseUrl();
const response = await axios.post(
`${centralBaseUrl}/api/internal/sso/consume`,
{
token,
pnodeId: centralConnector.pnodeId,
service: "pod-man"
},
{
headers: {
Authorization: `Bearer ${config.centralManagement.apiKey}`,
"Content-Type": "application/json"
},
timeout: 10000
}
);
const sessionUser = response.data?.sessionUser;
const normalizedRole = normalizePodManRole(sessionUser?.role);
if (!response.data?.success || !sessionUser?.username || !normalizedRole || !isAllowedPodManRole(normalizedRole)) {
console.error("[Central-SSO] Rejecting session: invalid session user payload");
logLocalAuditEvent("podman_sso_failure", {
req,
outcome: "denied",
summary: "Central SSO rejected",
details: { reason: "invalid-session-user-payload" }
});
return res.status(401).send("Central SSO was rejected.");
}
const sanitizedSessionUser = {
...sessionUser,
role: normalizedRole
};
return establishAuthenticatedSession(req, sanitizedSessionUser, (error) => {
if (error) {
console.error("[Central-SSO] Failed to save session:", error.message);
logLocalAuditEvent("podman_sso_failure", {
req,
outcome: "failed",
summary: "Central SSO session establishment failed",
details: { reason: error.message, username: sanitizedSessionUser.username }
});
return res.status(500).send("Failed to establish pod-man session.");
}
console.log(`[Central-SSO] Session established for ${sanitizedSessionUser.username}`);
logLocalAuditEvent("podman_sso_success", {
req,
summary: "Central SSO succeeded",
details: {
username: sanitizedSessionUser.username,
role: sanitizedSessionUser.role,
centralUserId: sanitizedSessionUser.userId || null,
centralEmail: sanitizedSessionUser.email || null
}
});
res.redirect("/");
});
} catch (error) {
const status = error.response?.status || 500;
const message = error.response?.data?.error || error.message;
console.error("[Central-SSO] Consume failed:", message);
logLocalAuditEvent("podman_sso_failure", {
req,
outcome: status >= 500 ? "failed" : "denied",
summary: "Central SSO consume failed",
details: { reason: message, status }
});
return res.status(status).send(`Central SSO failed: ${message}`);
}
});
/**
* Add user (admin only)
*/
app.post("/api/users/add", requireAdmin, async (req, res) => {
try {
const { username, password, role } = req.body;
if (!username || !password || !role) {
logLocalAuditEvent("podman_user_add", {
req,
outcome: "denied",
summary: "Pod-Man user creation rejected",
details: { reason: "missing-fields", username: username || null, role: role || null }
});
return res.status(400).json({ success: false, error: "Username, password, and role required" });
}
// Check if user exists
if (config.authentication.users.find(u => u.username === username)) {
logLocalAuditEvent("podman_user_add", {
req,
outcome: "denied",
summary: "Pod-Man user creation rejected",
details: { reason: "username-exists", username }
});
return res.status(400).json({ success: false, error: "Username already exists" });
}
let normalizedRole;
try {
normalizedRole = assertAllowedPodManRole(role);
} catch (error) {
logLocalAuditEvent("podman_user_add", {
req,
outcome: "denied",
summary: "Pod-Man user creation rejected",
details: { reason: error.message, username, role }
});
return res.status(400).json({ success: false, error: error.message });
}
// Hash password and add user
const hashedPassword = await bcrypt.hash(password, 10);
config.authentication.users.push({
username,
password: hashedPassword,
role: normalizedRole
});
saveConfig();
if (normalizedRole === 'demo') {
try {
await ensureRestrictedShellUser("setup-demo-user.sh");
} catch (error) {
console.error('Failed to setup demo user:', error);
}
} else if (normalizedRole === 'standard') {
try {
await ensureRestrictedShellUser("setup-standard-user.sh");
} catch (error) {
console.error('Failed to setup standard user:', error);
}
}
logLocalAuditEvent("podman_user_added", {
req,
summary: "Pod-Man user added",
details: { username, role: normalizedRole }
});
res.json({ success: true, message: "User added" });
} catch (error) {
logLocalAuditEvent("podman_user_add", {
req,
outcome: "failed",
summary: "Pod-Man user creation failed",
details: { username: req.body?.username || null, reason: error.message }
});
res.status(500).json({ success: false, error: error.message });
}
});
/**
* Delete user (admin only)
*/
app.post("/api/users/delete", requireAdmin, (req, res) => {
try {
const { username } = req.body;
if (!username) {
logLocalAuditEvent("podman_user_delete", {
req,
outcome: "denied",
summary: "Pod-Man user deletion rejected",
details: { reason: "missing-username" }
});
return res.status(400).json({ success: false, error: "Username required" });
}
// Don't allow deleting yourself
if (username === req.session.username) {
logLocalAuditEvent("podman_user_delete", {
req,
outcome: "denied",
summary: "Pod-Man user deletion rejected",
details: { username, reason: "cannot-delete-self" }
});
return res.status(400).json({ success: false, error: "Cannot delete your own account" });
}
// Ensure at least one admin remains
const admins = config.authentication.users.filter(u => u.role === 'admin');
const userToDelete = config.authentication.users.find(u => u.username === username);
if (userToDelete && userToDelete.role === 'admin' && admins.length <= 1) {
logLocalAuditEvent("podman_user_delete", {
req,
outcome: "denied",
summary: "Pod-Man user deletion rejected",
details: { username, reason: "last-admin-protection" }
});
return res.status(400).json({ success: false, error: "Cannot delete last admin user" });
}
// Remove user
config.authentication.users = config.authentication.users.filter(u => u.username !== username);
saveConfig();
logLocalAuditEvent("podman_user_deleted", {
req,
summary: "Pod-Man user deleted",
details: { username }
});
res.json({ success: true, message: "User deleted" });
} catch (error) {
logLocalAuditEvent("podman_user_delete", {
req,
outcome: "failed",
summary: "Pod-Man user deletion failed",
details: { username: req.body?.username || null, reason: error.message }
});
res.status(500).json({ success: false, error: error.message });
}
});
/**
* List users (admin only)
*/
app.get("/api/users/list", requireAdmin, (req, res) => {
const users = config.authentication.users.map(u => ({
username: u.username,
role: u.role
}));
res.json({ success: true, users });
});
// ============================================================================
// CENTRAL MANAGEMENT ENDPOINTS
// ============================================================================
/**
* Get central connection status
*/
app.get("/api/central/status", requireAuth, (req, res) => {
res.json({
success: true,
status: centralConnector.getStatus()
});
});
app.post("/api/central/owner/reset", requireAdmin, (req, res) => {
if (typeof centralConnector.audit === "function") {
centralConnector.audit('central-owner-reset', {
localAdmin: req.session.username || null
});
}
config.centralManagement.ownerCentralUserId = "";
config.centralManagement.ownerCentralEmail = "";
config.centralManagement.ownerBoundAt = "";
config.centralManagement.ownerBindingSource = "";
saveConfig();
centralConnector.updateConfig(config.centralManagement);
logLocalAuditEvent("podman_central_owner_reset", {
req,
summary: "Central owner binding reset locally"
});
res.json({
success: true,
status: centralConnector.getStatus()
});
});
/**
* Update central connection config (admin only)
*/
app.post("/api/central/configure", requireAdmin, async (req, res) => {
try {
const { enabled, apiKey, centralUrl, autoConnect } = req.body;
const changed = {};
// Update config file
if (apiKey !== undefined) {
config.centralManagement.apiKey = apiKey;
changed.apiKeyUpdated = true;
}
if (centralUrl !== undefined) {