feat: pre-deploy scan visibility and pinned scanner version (#1378)

* feat: pre-deploy scan visibility and pinned scanner version

Pin managed Trivy installs and add an opt-in pre-deploy scan advisory so a
manual deploy can surface each image's latest scan before it runs.

- Managed Trivy now installs a pinned, known-good version by default for
  reproducible installs. Auto-update still tracks the latest release, and an
  explicit update always pulls the latest.
- Add an opt-in pre-deploy scan advisory: when enabled, deploying a stack from
  the editor first shows each image's latest cached scan severity for review.
  It is visibility only and never blocks; deploy enforcement is unchanged.
- Backend: pre_deploy_scan_advisory setting, PUT
  /security/pre-deploy-scan-advisory, a cache-only GET
  /security/stacks/:name/pre-deploy-summary, and a node-scoped
  getLatestVulnScanByDigestForNode lookup.
- Frontend: advisory toggle on the Security page scanner setup, and a
  PreDeployScanDialog wired into the editor deploy flow that fails open when the
  summary is unavailable.
- Docs: scanner configuration, version pinning, and the advisory.

* fix: harden pre-deploy advisory guard, toggle visibility, and installer busy state

Addresses review findings on the pre-deploy advisory.

- Block a second editor deploy during the async advisory window with a
  synchronous pending ref, cleared on cancel and in the deploy's finally, so a
  double-click can no longer start two deploys.
- Keep the pre-deploy advisory toggle visible to admins whenever the setting is
  on, so it can still be turned off after the scanner becomes unavailable.
- Resolve the managed Trivy version inside the install lock so the busy state and
  serialization cover the latest-version fetch and the managed-install check.
This commit is contained in:
Anso
2026-06-16 00:42:33 -04:00
committed by GitHub
parent 770bead889
commit 7ce045accb
21 changed files with 1093 additions and 23 deletions
@@ -0,0 +1,89 @@
/**
* getLatestVulnScanByDigestForNode: the node-scoped, vulnerability-bearing
* latest-scan lookup that powers the pre-deploy advisory. It must (a) only ever
* return a scan for the requested node, and (b) only consider scanner sets that
* actually ran the vulnerability scanner, so a secret-only or config scan is
* never mistaken for a clean vuln scan.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { setupTestDb, cleanupTestDb } from './helpers/setupTestDb';
import type { DatabaseService as DatabaseServiceType, VulnerabilityScan } from '../services/DatabaseService';
let tmpDir: string;
let DatabaseService: typeof import('../services/DatabaseService').DatabaseService;
function insertScan(
db: DatabaseServiceType,
over: Partial<Omit<VulnerabilityScan, 'id'>>,
): number {
return db.createVulnerabilityScan({
node_id: 1,
image_ref: 'img',
image_digest: 'sha256:default',
scanned_at: 1000,
total_vulnerabilities: 0,
critical_count: 0,
high_count: 0,
medium_count: 0,
low_count: 0,
unknown_count: 0,
fixable_count: 0,
secret_count: 0,
misconfig_count: 0,
scanners_used: 'vuln',
highest_severity: null,
os_info: null,
trivy_version: null,
scan_duration_ms: null,
triggered_by: 'manual',
status: 'completed',
error: null,
stack_context: null,
...over,
});
}
beforeAll(async () => {
tmpDir = await setupTestDb();
({ DatabaseService } = await import('../services/DatabaseService'));
});
afterAll(() => cleanupTestDb(tmpDir));
describe('getLatestVulnScanByDigestForNode', () => {
it('includes vuln and vuln,secret rows but excludes secret-only and config scans', () => {
const db = DatabaseService.getInstance();
const digest = 'sha256:setfilter';
// Newer rows that did NOT run the vuln scanner must be ignored even though
// they are more recent than the vuln-bearing rows.
insertScan(db, { image_digest: digest, scanners_used: 'secret', scanned_at: 5000, critical_count: 99 });
insertScan(db, { image_digest: digest, scanners_used: 'config', scanned_at: 4000, critical_count: 88 });
insertScan(db, { image_digest: digest, scanners_used: 'vuln', scanned_at: 1000, critical_count: 1 });
insertScan(db, { image_digest: digest, scanners_used: 'vuln,secret', scanned_at: 2000, critical_count: 2 });
const found = db.getLatestVulnScanByDigestForNode(digest, 1);
expect(found).not.toBeNull();
expect(found?.scanners_used).toBe('vuln,secret');
expect(found?.critical_count).toBe(2);
});
it('is node-scoped: a scan from another node is not returned', () => {
const db = DatabaseService.getInstance();
const digest = 'sha256:nodescope';
insertScan(db, { node_id: 2, image_digest: digest, scanners_used: 'vuln', scanned_at: 9000, critical_count: 7 });
expect(db.getLatestVulnScanByDigestForNode(digest, 1)).toBeNull();
expect(db.getLatestVulnScanByDigestForNode(digest, 2)?.critical_count).toBe(7);
});
it('ignores non-completed scans', () => {
const db = DatabaseService.getInstance();
const digest = 'sha256:status';
insertScan(db, { image_digest: digest, scanners_used: 'vuln', status: 'in_progress', scanned_at: 8000 });
expect(db.getLatestVulnScanByDigestForNode(digest, 1)).toBeNull();
});
it('returns null for an empty digest', () => {
expect(DatabaseService.getInstance().getLatestVulnScanByDigestForNode('', 1)).toBeNull();
});
});
@@ -0,0 +1,96 @@
/**
* PUT /api/security/pre-deploy-scan-advisory.
*
* Flips the per-instance `pre_deploy_scan_advisory` setting that drives the
* manual-deploy scan advisory. Visibility only, so it is admin-gated but carries
* no tier gate: reachable by any admin on Community as well as Admiral. The
* value is reflected back on GET /trivy-status.
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import request from 'supertest';
import bcrypt from 'bcrypt';
import { setupTestDb, cleanupTestDb, loginAsTestAdmin } from './helpers/setupTestDb';
let tmpDir: string;
let app: import('express').Express;
let DatabaseService: typeof import('../services/DatabaseService').DatabaseService;
let adminCookie: string;
let viewerCookie: string;
beforeAll(async () => {
tmpDir = await setupTestDb();
({ DatabaseService } = await import('../services/DatabaseService'));
const { LicenseService } = await import('../services/LicenseService');
vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('paid');
({ app } = await import('../index'));
adminCookie = await loginAsTestAdmin(app);
const viewerHash = await bcrypt.hash('viewerpass4', 1);
DatabaseService.getInstance().addUser({ username: 'advisory-viewer', password_hash: viewerHash, role: 'viewer' });
const viewerRes = await request(app).post('/api/auth/login').send({ username: 'advisory-viewer', password: 'viewerpass4' });
const cookies = viewerRes.headers['set-cookie'] as string | string[];
viewerCookie = Array.isArray(cookies) ? cookies[0] : cookies;
});
afterAll(() => cleanupTestDb(tmpDir));
describe('PUT /api/security/pre-deploy-scan-advisory', () => {
it('rejects unauthenticated requests with 401', async () => {
const res = await request(app).put('/api/security/pre-deploy-scan-advisory').send({ enabled: true });
expect(res.status).toBe(401);
});
it('rejects an authenticated viewer with 403', async () => {
const res = await request(app)
.put('/api/security/pre-deploy-scan-advisory')
.set('Cookie', viewerCookie)
.send({ enabled: true });
expect(res.status).toBe(403);
});
it('rejects a non-boolean enabled with 400', async () => {
const res = await request(app)
.put('/api/security/pre-deploy-scan-advisory')
.set('Cookie', adminCookie)
.send({ enabled: 'yes' });
expect(res.status).toBe(400);
});
it('accepts a Community admin (no tier gate) and persists the setting', async () => {
const { LicenseService } = await import('../services/LicenseService');
const spy = vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('community');
try {
const res = await request(app)
.put('/api/security/pre-deploy-scan-advisory')
.set('Cookie', adminCookie)
.send({ enabled: true });
expect(res.status).toBe(200);
expect(res.body.preDeployScanAdvisory).toBe(true);
expect(DatabaseService.getInstance().getGlobalSettings().pre_deploy_scan_advisory).toBe('1');
} finally {
spy.mockReturnValue('paid');
}
});
it('reflects the persisted value on GET /trivy-status', async () => {
await request(app)
.put('/api/security/pre-deploy-scan-advisory')
.set('Cookie', adminCookie)
.send({ enabled: true });
const res = await request(app).get('/api/security/trivy-status').set('Cookie', adminCookie);
expect(res.status).toBe(200);
expect(res.body.preDeployScanAdvisory).toBe(true);
});
it('disables the setting', async () => {
const res = await request(app)
.put('/api/security/pre-deploy-scan-advisory')
.set('Cookie', adminCookie)
.send({ enabled: false });
expect(res.status).toBe(200);
expect(res.body.preDeployScanAdvisory).toBe(false);
expect(DatabaseService.getInstance().getGlobalSettings().pre_deploy_scan_advisory).toBe('0');
});
});
@@ -0,0 +1,137 @@
/**
* GET /api/security/stacks/:stackName/pre-deploy-summary.
*
* Read-only advisory data for the pre-deploy dialog. It must:
* - short-circuit (no compose/digest/scan work) when the advisory is off,
* - resolve each image ref to a digest before the node-scoped scan lookup,
* - never trigger a scan (cache-only),
* - reject an invalid stack name, and require auth.
*/
import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest';
import request from 'supertest';
import bcrypt from 'bcrypt';
import { setupTestDb, cleanupTestDb, loginAsTestAdmin } from './helpers/setupTestDb';
import type { VulnerabilityScan } from '../services/DatabaseService';
let tmpDir: string;
let app: import('express').Express;
let DatabaseService: typeof import('../services/DatabaseService').DatabaseService;
let ComposeService: typeof import('../services/ComposeService').ComposeService;
let TrivyService: typeof import('../services/TrivyService').default;
let adminCookie: string;
let viewerCookie: string;
function makeScan(over: Partial<VulnerabilityScan>): VulnerabilityScan {
return {
id: 1, node_id: 1, image_ref: 'img', image_digest: 'sha256:a', scanned_at: 1000,
total_vulnerabilities: 5, critical_count: 3, high_count: 2, medium_count: 1, low_count: 4,
unknown_count: 0, fixable_count: 0, secret_count: 0, misconfig_count: 0,
scanners_used: 'vuln', highest_severity: 'CRITICAL', os_info: null, trivy_version: null,
scan_duration_ms: null, triggered_by: 'manual', status: 'completed', error: null,
stack_context: null, policy_evaluation: null, ...over,
};
}
function setAdvisory(enabled: boolean): void {
DatabaseService.getInstance().updateGlobalSetting('pre_deploy_scan_advisory', enabled ? '1' : '0');
}
beforeAll(async () => {
tmpDir = await setupTestDb();
({ DatabaseService } = await import('../services/DatabaseService'));
({ ComposeService } = await import('../services/ComposeService'));
TrivyService = (await import('../services/TrivyService')).default;
({ app } = await import('../index'));
adminCookie = await loginAsTestAdmin(app);
const viewerHash = await bcrypt.hash('viewerpass5', 1);
DatabaseService.getInstance().addUser({ username: 'summary-viewer', password_hash: viewerHash, role: 'viewer' });
const viewerRes = await request(app).post('/api/auth/login').send({ username: 'summary-viewer', password: 'viewerpass5' });
const cookies = viewerRes.headers['set-cookie'] as string | string[];
viewerCookie = Array.isArray(cookies) ? cookies[0] : cookies;
});
afterAll(() => {
setAdvisory(false);
cleanupTestDb(tmpDir);
});
afterEach(() => {
vi.restoreAllMocks();
setAdvisory(false);
});
describe('GET /api/security/stacks/:stackName/pre-deploy-summary', () => {
it('rejects unauthenticated requests with 401', async () => {
const res = await request(app).get('/api/security/stacks/web/pre-deploy-summary');
expect(res.status).toBe(401);
});
it('short-circuits to { enabled: false } without any compose/digest work when off', async () => {
setAdvisory(false);
const listImages = vi.spyOn(ComposeService.prototype, 'listStackImages');
const getDigest = vi.spyOn(TrivyService.getInstance(), 'getImageDigest');
const res = await request(app).get('/api/security/stacks/web/pre-deploy-summary').set('Cookie', adminCookie);
expect(res.status).toBe(200);
expect(res.body).toEqual({ enabled: false });
expect(listImages).not.toHaveBeenCalled();
expect(getDigest).not.toHaveBeenCalled();
});
it('returns per-image cached scan counts, resolving refs to digests (cache-only)', async () => {
setAdvisory(true);
vi.spyOn(ComposeService.prototype, 'listStackImages').mockResolvedValue(['nginx:1.14', 'redis:7']);
vi.spyOn(TrivyService.getInstance(), 'getImageDigest').mockImplementation(
async (ref: string) => (ref === 'nginx:1.14' ? 'sha256:nginx' : null),
);
const lookup = vi
.spyOn(DatabaseService.getInstance(), 'getLatestVulnScanByDigestForNode')
.mockImplementation((digest: string) => (digest === 'sha256:nginx' ? makeScan({ critical_count: 31, high_count: 82, highest_severity: 'CRITICAL', scanned_at: 4242 }) : null));
// Cache-only: the advisory must never kick off a scan.
const runScan = vi.spyOn(TrivyService.getInstance(), 'scanImagePreflight');
const res = await request(app).get('/api/security/stacks/web/pre-deploy-summary').set('Cookie', adminCookie);
expect(res.status).toBe(200);
expect(res.body.enabled).toBe(true);
expect(res.body.images).toEqual([
{
imageRef: 'nginx:1.14',
scan: { criticalCount: 31, highCount: 82, mediumCount: 1, lowCount: 4, highestSeverity: 'CRITICAL', scannedAt: 4242 },
},
{ imageRef: 'redis:7', scan: null },
]);
expect(lookup).toHaveBeenCalled();
expect(runScan).not.toHaveBeenCalled();
});
it('rejects an invalid stack name with 400 when enabled', async () => {
setAdvisory(true);
const res = await request(app).get('/api/security/stacks/bad%20name/pre-deploy-summary').set('Cookie', adminCookie);
expect(res.status).toBe(400);
});
it('is readable by a non-admin (advisory visibility is not admin-gated)', async () => {
setAdvisory(true);
vi.spyOn(ComposeService.prototype, 'listStackImages').mockResolvedValue(['nginx:1.14']);
vi.spyOn(TrivyService.getInstance(), 'getImageDigest').mockResolvedValue(null);
const res = await request(app).get('/api/security/stacks/web/pre-deploy-summary').set('Cookie', viewerCookie);
expect(res.status).toBe(200);
expect(res.body.enabled).toBe(true);
});
it('returns a generic 500 (no internal detail) when image enumeration fails', async () => {
setAdvisory(true);
vi.spyOn(ComposeService.prototype, 'listStackImages').mockRejectedValue(new Error('/secret/path: compose parse boom'));
const res = await request(app).get('/api/security/stacks/web/pre-deploy-summary').set('Cookie', adminCookie);
expect(res.status).toBe(500);
expect(res.body.error).toBe('Failed to build pre-deploy summary');
expect(JSON.stringify(res.body)).not.toContain('/secret/path');
});
});
@@ -69,6 +69,7 @@ describe('GET /api/settings', () => {
db.updateGlobalSetting(k, '');
}
db.updateGlobalSetting('trivy_auto_update', '0');
db.updateGlobalSetting('pre_deploy_scan_advisory', '0');
db.updateGlobalSetting('mesh_auto_recreate', '0');
});
@@ -83,6 +84,9 @@ describe('GET /api/settings', () => {
db.updateGlobalSetting('cloud_backup_endpoint', 'https://s3.example.com');
db.updateGlobalSetting('cloud_backup_bucket', 'private-bucket');
db.updateGlobalSetting('trivy_auto_update', '1');
// Scanner toggles live under /api/security/*, never the generic settings
// allowlist, so the advisory key must not surface here either.
db.updateGlobalSetting('pre_deploy_scan_advisory', '1');
// A key that is neither allowlisted nor obviously sensitive: the allowlist
// must still exclude it. This locks the fail-closed contract that is the
// reason the GET uses an allowlist rather than a denylist.
@@ -97,6 +101,7 @@ describe('GET /api/settings', () => {
expect(res.body.cloud_backup_endpoint).toBeUndefined();
expect(res.body.cloud_backup_bucket).toBeUndefined();
expect(res.body.trivy_auto_update).toBeUndefined();
expect(res.body.pre_deploy_scan_advisory).toBeUndefined();
expect(res.body.some_future_setting).toBeUndefined();
// Allowlisted keys still come through. Two structurally different keys (a
// numeric and an enum-shaped one) prove the projection passes the whole
@@ -0,0 +1,89 @@
/**
* Managed Trivy install/update version selection.
*
* A normal managed install pins to a known-good bundled version for
* reproducibility; opting into auto-update tracks the latest release; and an
* explicit Update always pulls the latest regardless of the auto-update setting.
* The download itself (doInstall) is mocked so these stay offline and fast.
*/
import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest';
import { setupTestDb, cleanupTestDb } from './helpers/setupTestDb';
let tmpDir: string;
let DatabaseService: typeof import('../services/DatabaseService').DatabaseService;
let TrivyInstaller: typeof import('../services/TrivyInstaller').default;
// The pinned default the installer must use when auto-update is off. Kept in
// sync with PINNED_TRIVY_VERSION in TrivyInstaller.ts.
const PINNED = '0.70.0';
type InstallerInternals = { doInstall: (version: string) => Promise<{ version: string }> };
beforeAll(async () => {
tmpDir = await setupTestDb();
({ DatabaseService } = await import('../services/DatabaseService'));
TrivyInstaller = (await import('../services/TrivyInstaller')).default;
});
afterAll(() => cleanupTestDb(tmpDir));
afterEach(() => {
vi.restoreAllMocks();
DatabaseService.getInstance().updateGlobalSetting('trivy_auto_update', '0');
});
describe('TrivyInstaller managed version selection', () => {
it('install() pins to the bundled version by default (auto-update off)', async () => {
const installer = TrivyInstaller.getInstance();
DatabaseService.getInstance().updateGlobalSetting('trivy_auto_update', '0');
const fetchLatest = vi.spyOn(installer, 'fetchLatestVersion').mockResolvedValue('0.99.0');
const doInstall = vi
.spyOn(installer as unknown as InstallerInternals, 'doInstall')
.mockResolvedValue({ version: PINNED });
await installer.install();
expect(fetchLatest).not.toHaveBeenCalled();
expect(doInstall).toHaveBeenCalledWith(PINNED);
});
it('install() tracks the latest release when auto-update is on', async () => {
const installer = TrivyInstaller.getInstance();
DatabaseService.getInstance().updateGlobalSetting('trivy_auto_update', '1');
const fetchLatest = vi.spyOn(installer, 'fetchLatestVersion').mockResolvedValue('0.99.0');
const doInstall = vi
.spyOn(installer as unknown as InstallerInternals, 'doInstall')
.mockResolvedValue({ version: '0.99.0' });
await installer.install();
expect(fetchLatest).toHaveBeenCalled();
expect(doInstall).toHaveBeenCalledWith('0.99.0');
});
it('update() always installs the latest release, even with auto-update off', async () => {
const installer = TrivyInstaller.getInstance();
DatabaseService.getInstance().updateGlobalSetting('trivy_auto_update', '0');
vi.spyOn(installer, 'isManagedInstalled').mockReturnValue(true);
const fetchLatest = vi.spyOn(installer, 'fetchLatestVersion').mockResolvedValue('0.99.0');
const doInstall = vi
.spyOn(installer as unknown as InstallerInternals, 'doInstall')
.mockResolvedValue({ version: '0.99.0' });
await installer.update();
expect(fetchLatest).toHaveBeenCalled();
expect(doInstall).toHaveBeenCalledWith('0.99.0');
});
it('rejects a resolved version below the supported minimum (real doInstall guard)', async () => {
const installer = TrivyInstaller.getInstance();
// Auto-update on so install() takes the fetched-latest path; the fetch returns
// a sub-minimum version, which the doInstall guard must reject before any
// download happens. doInstall is NOT mocked here so the real guard runs.
DatabaseService.getInstance().updateGlobalSetting('trivy_auto_update', '1');
vi.spyOn(installer, 'fetchLatestVersion').mockResolvedValue('0.49.0');
await expect(installer.install()).rejects.toThrow(/below minimum/);
});
});
+87 -1
View File
@@ -4,7 +4,9 @@ import { requireAdmin, requirePaid } from '../middleware/tierGates';
import { trivyInstallLimiter } from '../middleware/rateLimiters';
import TrivyService, { SbomFormat } from '../services/TrivyService';
import TrivyInstaller from '../services/TrivyInstaller';
import { DatabaseService, parsePolicyEvaluation, type VulnerabilityScan } from '../services/DatabaseService';
import { DatabaseService, parsePolicyEvaluation, type VulnerabilityScan, type VulnSeverity } from '../services/DatabaseService';
import { ComposeService } from '../services/ComposeService';
import { isValidStackName } from '../utils/validation';
import { FleetSyncService } from '../services/FleetSyncService';
import { LicenseService } from '../services/LicenseService';
import { validateImageRef } from '../utils/image-ref';
@@ -149,6 +151,7 @@ securityRouter.get('/trivy-status', authMiddleware, (_req: Request, res: Respons
source: svc.getSource(),
autoUpdate: settings.trivy_auto_update === '1',
honorSuppressionsOnDeploy: settings.deploy_block_honor_suppressions === '1',
preDeployScanAdvisory: settings.pre_deploy_scan_advisory === '1',
busy: installer.isBusy(),
});
});
@@ -264,6 +267,89 @@ securityRouter.put('/deploy-block-honor-suppressions', authMiddleware, (req: Req
}
});
// Pre-deploy scan advisory toggle. When on, a manual stack deploy first shows
// the latest cached scan severity for each image so the operator can review it
// before deploying. Visibility only: it never blocks (that is the paid
// deploy-block policy). Per-instance, admin-only, all tiers. Default off.
securityRouter.put('/pre-deploy-scan-advisory', authMiddleware, (req: Request, res: Response): void => {
if (!requireAdmin(req, res)) return;
if (typeof req.body?.enabled !== 'boolean') {
res.status(400).json({ error: 'enabled must be a boolean' });
return;
}
const enabled = req.body.enabled;
try {
DatabaseService.getInstance().updateGlobalSetting('pre_deploy_scan_advisory', enabled ? '1' : '0');
res.json({ preDeployScanAdvisory: enabled });
} catch (err) {
const msg = getErrorMessage(err, 'Failed to update setting');
console.error('[Security] Pre-deploy scan advisory toggle failed:', msg);
res.status(500).json({ error: msg });
}
});
interface PreDeployImageSummary {
imageRef: string;
scan: {
criticalCount: number;
highCount: number;
mediumCount: number;
lowCount: number;
highestSeverity: VulnSeverity | null;
scannedAt: number;
} | null;
}
// Read-only advisory data for the pre-deploy dialog: the latest cached,
// node-scoped, vulnerability-bearing scan for each image declared in the stack's
// compose file. Cache-only by design (never triggers a scan) so it stays fast
// and side-effect-free on the deploy path, and short-circuits when the advisory
// is off so the common path does no compose/digest work. No tier gate
// (visibility is free); matches the auth model of the other /scans read routes.
securityRouter.get('/stacks/:stackName/pre-deploy-summary', authMiddleware, async (req: Request, res: Response): Promise<void> => {
const settings = DatabaseService.getInstance().getGlobalSettings();
if (settings.pre_deploy_scan_advisory !== '1') {
res.json({ enabled: false });
return;
}
const stackName = String(req.params.stackName);
if (!isValidStackName(stackName)) {
res.status(400).json({ error: 'Invalid stack name' });
return;
}
const nodeId = req.nodeId;
try {
const db = DatabaseService.getInstance();
const trivy = TrivyService.getInstance();
const imageRefs = await ComposeService.getInstance(nodeId).listStackImages(stackName);
const images: PreDeployImageSummary[] = [];
for (const imageRef of imageRefs) {
const digest = await trivy.getImageDigest(imageRef, nodeId);
const scan = digest ? db.getLatestVulnScanByDigestForNode(digest, nodeId) : null;
images.push({
imageRef,
scan: scan
? {
criticalCount: scan.critical_count,
highCount: scan.high_count,
mediumCount: scan.medium_count,
lowCount: scan.low_count,
highestSeverity: scan.highest_severity,
scannedAt: scan.scanned_at,
}
: null,
});
}
res.json({ enabled: true, images });
} catch (err) {
const msg = getErrorMessage(err, 'Failed to build pre-deploy summary');
console.error('[Security] Pre-deploy summary failed for %s:', sanitizeForLog(stackName), sanitizeForLog(msg));
// Keep the detail in the server log only: this path runs docker compose and
// image inspect, whose error text can carry filesystem or daemon detail.
res.status(500).json({ error: 'Failed to build pre-deploy summary' });
}
});
securityRouter.post('/scan', authMiddleware, (req: Request, res: Response): void => {
if (!requireAdmin(req, res)) return;
const svc = TrivyService.getInstance();
+28
View File
@@ -588,6 +588,13 @@ export interface VulnerabilityScan {
policy_evaluation: string | null;
}
// Fail-closed allowlist of the scanners_used values that ran the vulnerability
// scanner. Image scans store vuln/secret joins from normalizeScanners (TrivyService),
// while compose scans store 'config' directly; listing only the vuln-bearing sets
// means any other value (secret-only, config, or a future literal) is excluded, so
// a clean vuln read can never be a secret-only or config scan in disguise.
export const VULN_BEARING_SCANNER_SETS = ['vuln', 'vuln,secret'] as const;
export function parsePolicyEvaluation(raw: string | null | undefined): PolicyEvaluation | null {
if (!raw) return null;
try {
@@ -1458,6 +1465,7 @@ export class DatabaseService {
stmt.run('trivy_auto_update', '0');
stmt.run('trivy_last_notified_version', '');
stmt.run('deploy_block_honor_suppressions', '0');
stmt.run('pre_deploy_scan_advisory', '0');
stmt.run('mesh_auto_recreate', '0');
stmt.run('prune_on_update', '1');
stmt.run('reclaim_hero', '1');
@@ -4226,6 +4234,26 @@ export class DatabaseService {
);
}
/**
* Latest completed vulnerability-bearing scan for a digest ON A SPECIFIC NODE.
*
* Unlike getLatestScanByDigest, this filters by node_id so a read-only
* response never surfaces a scan (or scan id) produced on another node, and
* it restricts to scanner sets that actually ran the vulnerability scanner so
* a secret-only or config scan is not mistaken for a clean vuln scan.
*/
public getLatestVulnScanByDigestForNode(digest: string, nodeId: number): VulnerabilityScan | null {
if (!digest) return null;
const placeholders = VULN_BEARING_SCANNER_SETS.map(() => '?').join(', ');
return (
(this.db
.prepare(
`SELECT * FROM vulnerability_scans WHERE image_digest = ? AND node_id = ? AND status = 'completed' AND scanners_used IN (${placeholders}) ORDER BY scanned_at DESC LIMIT 1`,
)
.get(digest, nodeId, ...VULN_BEARING_SCANNER_SETS) as VulnerabilityScan | undefined) ?? null
);
}
public deleteOldScans(olderThanMs: number): number {
const cutoff = Date.now() - olderThanMs;
const result = this.db
+27 -8
View File
@@ -4,6 +4,7 @@ import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import semver from 'semver';
import { DatabaseService } from './DatabaseService';
const execFileAsync = promisify(execFile);
@@ -15,6 +16,11 @@ const GITHUB_API_TIMEOUT_MS = 15 * 1000;
const VERIFY_TIMEOUT_MS = 10 * 1000;
const LATEST_VERSION_TTL_MS = 60 * 60 * 1000;
const MIN_TRIVY_VERSION = '0.50.0';
// Managed installs pin to a known-good release by default so the scanner binary
// is reproducible and supply-chain stable rather than whatever "latest" resolves
// to at install time. Opting into auto-update (trivy_auto_update) tracks the
// newest release instead. Keep this at or above MIN_TRIVY_VERSION.
const PINNED_TRIVY_VERSION = '0.70.0';
export type TrivySource = 'managed' | 'host' | 'none';
@@ -142,14 +148,28 @@ class TrivyInstaller {
}
public async install(): Promise<{ version: string }> {
return this.acquire(async () => this.doInstall());
// Resolve the version inside acquire() so busy stays true through the
// latest-version network fetch and a concurrent op is serialized.
return this.acquire(async () => this.doInstall(await this.resolveInstallVersion()));
}
public async update(): Promise<{ version: string }> {
if (!this.isManagedInstalled()) {
throw new Error('No managed Trivy install to update');
}
return this.acquire(async () => this.doInstall());
return this.acquire(async () => {
if (!this.isManagedInstalled()) {
throw new Error('No managed Trivy install to update');
}
// An explicit update always pulls the newest release, regardless of
// the auto-update setting; that is the whole point of the action.
return this.doInstall(await this.fetchLatestVersion(true));
});
}
// Fresh installs pin by default for reproducibility; when the operator has
// opted into auto-update, a fresh install tracks the latest release so it
// matches the cadence the scheduler will keep it on.
private async resolveInstallVersion(): Promise<string> {
const autoUpdate = DatabaseService.getInstance().getGlobalSettings().trivy_auto_update === '1';
return autoUpdate ? this.fetchLatestVersion(true) : PINNED_TRIVY_VERSION;
}
public async uninstall(): Promise<void> {
@@ -176,10 +196,9 @@ class TrivyInstaller {
}
}
private async doInstall(): Promise<{ version: string }> {
const version = await this.fetchLatestVersion(true);
private async doInstall(version: string): Promise<{ version: string }> {
if (semver.lt(version, MIN_TRIVY_VERSION)) {
throw new Error(`Fetched Trivy version ${version} is below minimum ${MIN_TRIVY_VERSION}`);
throw new Error(`Trivy version ${version} is below minimum ${MIN_TRIVY_VERSION}`);
}
const archTag = archAssetTag();
const assetName = `trivy_${version}_Linux-${archTag}.tar.gz`;