fix(fleet-snapshots): gate reads on admin role and encrypt content at rest (#1273)

* fix(fleet-snapshots): gate reads on admin role and encrypt content at rest

Fleet snapshots capture every node's compose.yaml and .env, so the data is
as sensitive as the live stacks. This hardens access and reliability across
the snapshot pipeline.

- Restrict snapshot reads to administrators. GET /api/fleet/snapshots and
  /:id now require the admin role, matching create, restore, and delete; the
  Fleet "Snapshots" tab and its panel render only for admins. Previously any
  authenticated user could enumerate snapshots and read every node's .env.

- Encrypt snapshot file contents at rest with the instance key. Restore and
  cloud-archive paths decrypt on read, so cloud archives stay portable and a
  database copy no longer exposes stack secrets in plaintext. Rows written
  before this change still read back as plaintext.

- Surface partial captures. A stack whose compose file cannot be read or
  fetched, or a file over the 1 MB capture cap, is recorded as a warning and
  shown on the snapshot instead of being silently dropped, so a snapshot is
  never mistaken for complete. Remote .env read errors are now distinguished
  from a genuinely absent .env.

Adds route-authz, capture-warning, and encryption round-trip tests; updates
the Fleet-Wide Backups feature docs.

* fix(fleet-snapshots): gate cloud snapshot reads on admin role

The cloud snapshot read routes were guarded by provider/license only, not by
role, while their write counterparts (upload, delete) already required admin
and the Cloud Backup settings surface is admin-only. Because a downloaded
archive contains plaintext compose and .env files, a non-admin could list and
download cloud snapshots and read every node's secrets, the same exposure the
local snapshot reads were just closed against.

- Require admin on GET /api/cloud-backup/snapshots, /status/:id, and
  /object/:keyB64/download, matching the local snapshot reads and the
  admin-only Cloud Backup settings section.
- When capturing a remote node, treat a 200 response carrying X-Env-Exists:
  false as a stack with no .env (matching the local ENOENT path) instead of
  storing an empty .env that restore would later write back.

Adds non-admin authorization tests for the cloud read routes and a remote
absent-.env capture test.
This commit is contained in:
Anso
2026-06-01 17:27:59 -04:00
committed by GitHub
parent 0953025036
commit c11a550b6a
15 changed files with 630 additions and 81 deletions
+3
View File
@@ -186,6 +186,7 @@ cloudBackupRouter.get('/usage', async (req: Request, res: Response): Promise<voi
cloudBackupRouter.get('/snapshots', async (req: Request, res: Response): Promise<void> => {
if (rejectApiTokenScope(req, res, SCOPE_MESSAGE)) return;
if (!requireAdmin(req, res)) return;
if (!gateForCurrentProvider(req, res)) return;
try {
const entries = await CloudBackupService.getInstance().listCloudSnapshots();
@@ -218,6 +219,7 @@ cloudBackupRouter.post('/upload/:id', async (req: Request, res: Response): Promi
cloudBackupRouter.get('/status/:id', (req: Request, res: Response): void => {
if (rejectApiTokenScope(req, res, SCOPE_MESSAGE)) return;
if (!requireAdmin(req, res)) return;
if (!gateForCurrentProvider(req, res)) return;
const id = parseSnapshotIdParam(req, res);
if (id == null) return;
@@ -226,6 +228,7 @@ cloudBackupRouter.get('/status/:id', (req: Request, res: Response): void => {
cloudBackupRouter.get('/object/:keyB64/download', async (req: Request, res: Response): Promise<void> => {
if (rejectApiTokenScope(req, res, SCOPE_MESSAGE)) return;
if (!requireAdmin(req, res)) return;
if (!gateForCurrentProvider(req, res)) return;
const objectKey = decodeObjectKey(req, res);
if (!objectKey) return;
+31 -8
View File
@@ -1597,6 +1597,7 @@ fleetRouter.post('/snapshots', authMiddleware, async (req: Request, res: Respons
let totalStacks = 0;
const allFiles: Array<{ nodeId: number; nodeName: string; stackName: string; filename: string; content: string }> = [];
const skippedStacks: Array<{ nodeId: number; nodeName: string; stackName: string; reason: string }> = [];
for (const nodeData of capturedNodes) {
totalStacks += nodeData.stacks.length;
@@ -1611,6 +1612,14 @@ fleetRouter.post('/snapshots', authMiddleware, async (req: Request, res: Respons
});
}
}
for (const warning of nodeData.warnings) {
skippedStacks.push({
nodeId: nodeData.nodeId,
nodeName: nodeData.nodeName,
stackName: warning.stackName,
reason: warning.reason,
});
}
}
const snapshotId = db.createSnapshot(
@@ -1619,6 +1628,7 @@ fleetRouter.post('/snapshots', authMiddleware, async (req: Request, res: Respons
capturedNodes.length,
totalStacks,
JSON.stringify(skippedNodes),
JSON.stringify(skippedStacks),
);
if (allFiles.length > 0) {
@@ -1627,21 +1637,30 @@ fleetRouter.post('/snapshots', authMiddleware, async (req: Request, res: Respons
const cloudSvc = CloudBackupService.getInstance();
if (cloudSvc.isEnabled() && cloudSvc.isAutoUploadOn()) {
void cloudSvc.uploadSnapshot(snapshotId).catch(uploadErr => {
const message = uploadErr instanceof Error ? uploadErr.message : String(uploadErr);
console.error('[Fleet Snapshot] Cloud upload failed:', message);
void NotificationService.getInstance()
.dispatchAlert('error', 'system', `Cloud backup upload failed for snapshot ${snapshotId}: ${message}`)
.catch(() => { /* notification dispatch is best-effort */ });
});
void cloudSvc.uploadSnapshot(snapshotId)
.then(() => console.log(`[Fleet Snapshot] Cloud auto-upload OK for snapshot ${snapshotId}`))
.catch(uploadErr => {
const message = uploadErr instanceof Error ? uploadErr.message : String(uploadErr);
console.error('[Fleet Snapshot] Cloud upload failed:', message);
void NotificationService.getInstance()
.dispatchAlert('error', 'system', `Cloud backup upload failed for snapshot ${snapshotId}: ${message}`)
.catch(() => { /* notification dispatch is best-effort */ });
});
}
console.log('[Fleet] Snapshot created:', capturedNodes.length, 'nodes,', totalStacks, 'stacks');
if (skippedNodes.length > 0 || skippedStacks.length > 0) {
console.warn(`[Fleet] Snapshot ${snapshotId} partial: ${capturedNodes.length} node(s), ${totalStacks} stack(s); skipped ${skippedNodes.length} node(s), ${skippedStacks.length} stack(s)`);
} else {
console.log('[Fleet] Snapshot created:', capturedNodes.length, 'nodes,', totalStacks, 'stacks');
}
if (isDebugEnabled()) {
console.debug(`[Fleet:debug] Snapshot ${snapshotId} capture completed in ${Date.now() - captureStart}ms, ${allFiles.length} file(s) stored`);
for (const skip of skippedNodes) {
console.debug(`[Fleet:debug] Skipped node "${skip.nodeName}" (id=${skip.nodeId}): ${skip.reason}`);
}
for (const skip of skippedStacks) {
console.debug(`[Fleet:debug] Skipped stack "${skip.stackName}" on "${skip.nodeName}" (id=${skip.nodeId}): ${skip.reason}`);
}
}
const snapshot = db.getSnapshot(snapshotId);
res.status(201).json(snapshot);
@@ -1652,6 +1671,8 @@ fleetRouter.post('/snapshots', authMiddleware, async (req: Request, res: Respons
});
fleetRouter.get('/snapshots', authMiddleware, async (req: Request, res: Response): Promise<void> => {
if (!requireAdmin(req, res)) return;
try {
const limit = Math.min(parseInt(req.query.limit as string, 10) || 50, 100);
const offset = parseInt(req.query.offset as string, 10) || 0;
@@ -1667,6 +1688,8 @@ fleetRouter.get('/snapshots', authMiddleware, async (req: Request, res: Response
});
fleetRouter.get('/snapshots/:id', authMiddleware, async (req: Request, res: Response): Promise<void> => {
if (!requireAdmin(req, res)) return;
try {
const id = parseIntParam(req, res, 'id', 'snapshot ID');
if (id === null) return;