mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-21 15:46:43 +00:00
aa3d99a594
* fix(mesh): re-evaluate data plane every 10s and add opt-in auto-recreate MeshService.dataPlaneStatus was written exactly once at boot in setupMeshNetwork() and never re-evaluated. After the operator removed sencho_mesh at runtime (or it was recreated externally, or Sencho was disconnected from it), /api/health and the dashboard banner kept returning the stale boot-time discriminator until the next process restart. Adds a 10s revalidator that inspects the current Docker truth in one network-inspect call and transitions dataPlaneStatus to reflect it. Short-circuits in not_started / not_in_docker / subnet_invalid (states that cannot change within this process) and in concurrent ticks. Transitions are idempotent on stable state, so the timer can tick indefinitely on a healthy mesh without log noise. New 'not_found' reason value for the network-was-removed-at-runtime case. Existing reasons (subnet_mismatch, subnet_overlap, attach_failed) also surface from the revalidator when their underlying conditions arise post-boot. transitionDataPlane keeps message and subnet fields fresh across consecutive observations even when reason is unchanged, so /api/health never reports stale numbers (e.g. two consecutive subnet_mismatch observations against different external subnets). Adds an opt-in mesh_auto_recreate global setting (default off). When on, the revalidator additionally calls attemptInPlaceRecreate() after surfacing not_found. The helper hard-prefers the boot-chosen subnet (this.meshSubnet) and never iterates candidates, because changing the subnet here would invalidate every existing extra_hosts override on disk. A real conflict on the original subnet is reported as subnet_overlap and preserved during the 60s recreate throttle window so the operator-actionable reason is not flapped back to not_found between attempts. Self-attachment is checked via Name match (operator --hostname X matches container Name /X) or full container-ID prefix for hex HOSTNAMEs >= 12 chars (Docker default short ID). Non-hex HOSTNAMEs cannot collide with container IDs at all so a Name miss is conclusive; short hex HOSTNAMEs preserve the prior status as 'unknown' rather than risking a false-positive prefix match. Frontend surfaces: - types/mesh.ts: 'not_found' added to MeshDataPlaneReason. - MeshDataPlaneBanner: 'not_found' headline copy. - Settings > System > Mesh data plane: TogglePill bound to mesh_auto_recreate, default off, helper text explains the tradeoff. Backend coverage in backend/src/__tests__/mesh-data-plane-revalidate.test.ts (25 cases): short-circuits, idempotent stable-state, recovery from subnet_mismatch / subnet_overlap, transition to not_found / subnet_mismatch / attach_failed, transient-Docker anti-flap, re-entrancy guard, name match path, ID-prefix path, short hex hostname ambiguity, non-hex hostname certainty, transition message refresh on observation drift, auto-recreate off (default), auto-recreate success with senchoIp preservation, auto-recreate overlap classification with no subnet drift, throttle window preserves classified reason, throttle release. Lifecycle test covers timer wiring in start()/stop(). Existing mesh-setup-error-classification suite (27 cases) still green. Resolves: F-4 in the v1.0 audit tracker. * fix(mesh): address Codex review of PR #1184 Three findings from the independent review: BLOCKER: attemptInPlaceRecreate() called recordSetupFailure() on create / attach failures, which clears this.senchoIp. The next revalidator tick's attachment check is guarded on senchoIp, so with it null the check is skipped and the snapshot path can silently flip the status back to ok against a network where Sencho is in fact not attached. Also: a later successful recreate would call ensureSelfAttached() with senchoIp null, which short-circuits, so the network gets recreated without binding Sencho. Replaced the recordSetupFailure() calls in attemptInPlaceRecreate with a new recordRecreateFailure() that uses transitionDataPlane and preserves senchoIp. Added two tests: create-fails-then-succeeds (verifies senchoIp survives the failure and the later retry binds Sencho correctly) and create-succeeds-attach-fails-then-next-tick (verifies the snapshot path surfaces attach_failed on the next tick instead of falsely reporting ok). SHOULD-FIX 1: single-key POST /api/settings wrote String(value) without re-validating against the per-key schema, so an allowlisted enum-shaped key like mesh_auto_recreate could persist arbitrary strings ('banana', 'true') that the bulk PATCH would later refuse. Routed the single-key path through SettingsPatchSchema.safeParse so both write paths validate identically. Added regression tests for an invalid mesh_auto_recreate value, a valid mesh_auto_recreate write, and an out-of-range numeric value. SHOULD-FIX 2: the new Mesh data plane subsection lived inside a section the registry exposes to non-admins, who would see the toggle and only learn it was admin-only after the save 403'd. Gated the subsection on `isAdmin` from useAuth so non-admins do not see the control. The other system controls keep their existing visibility pattern (read-only for non-admins). 71/71 backend tests green (revalidate + mesh-setup + settings-routes). 276/276 frontend tests green. tsc clean on backend + frontend.
196 lines
7.6 KiB
TypeScript
196 lines
7.6 KiB
TypeScript
/**
|
|
* Integration tests for /api/settings (GET/POST/PATCH). These endpoints had
|
|
* zero route-layer coverage prior to Phase 4B of the index.ts refactor; this
|
|
* file locks down the shape before extraction.
|
|
*/
|
|
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');
|
|
vi.spyOn(LicenseService.getInstance(), 'getVariant').mockReturnValue('admiral');
|
|
vi.spyOn(LicenseService.getInstance(), 'getSeatLimits').mockReturnValue({ maxAdmins: null, maxViewers: null });
|
|
|
|
({ app } = await import('../index'));
|
|
adminCookie = await loginAsTestAdmin(app);
|
|
|
|
const viewerHash = await bcrypt.hash('viewerpass', 1);
|
|
DatabaseService.getInstance().addUser({ username: 'settings-viewer', password_hash: viewerHash, role: 'viewer' });
|
|
const viewerRes = await request(app).post('/api/auth/login').send({ username: 'settings-viewer', password: 'viewerpass' });
|
|
const cookies = viewerRes.headers['set-cookie'] as string | string[];
|
|
viewerCookie = Array.isArray(cookies) ? cookies[0] : cookies;
|
|
});
|
|
|
|
afterAll(() => cleanupTestDb(tmpDir));
|
|
|
|
describe('GET /api/settings', () => {
|
|
it('rejects unauthenticated requests with 401', async () => {
|
|
const res = await request(app).get('/api/settings');
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('returns settings for authenticated users', async () => {
|
|
const res = await request(app).get('/api/settings').set('Cookie', adminCookie);
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toBeInstanceOf(Object);
|
|
});
|
|
|
|
it('strips auth credentials from the response', async () => {
|
|
const res = await request(app).get('/api/settings').set('Cookie', adminCookie);
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.auth_username).toBeUndefined();
|
|
expect(res.body.auth_password_hash).toBeUndefined();
|
|
expect(res.body.auth_jwt_secret).toBeUndefined();
|
|
});
|
|
|
|
it('allows non-admin users to read settings', async () => {
|
|
// Settings is read-only for non-admins; write is admin-gated separately.
|
|
const res = await request(app).get('/api/settings').set('Cookie', viewerCookie);
|
|
expect(res.status).toBe(200);
|
|
});
|
|
});
|
|
|
|
describe('POST /api/settings (single-key write)', () => {
|
|
it('rejects unauthenticated requests with 401', async () => {
|
|
const res = await request(app).post('/api/settings').send({ key: 'host_cpu_limit', value: '80' });
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('rejects non-admin users with 403', async () => {
|
|
const res = await request(app)
|
|
.post('/api/settings')
|
|
.set('Cookie', viewerCookie)
|
|
.send({ key: 'host_cpu_limit', value: '80' });
|
|
expect(res.status).toBe(403);
|
|
});
|
|
|
|
it('rejects disallowed setting keys with 400', async () => {
|
|
const res = await request(app)
|
|
.post('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({ key: 'auth_jwt_secret', value: 'pwned' });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/Invalid or disallowed setting key/);
|
|
});
|
|
|
|
it('rejects missing value with 400', async () => {
|
|
const res = await request(app)
|
|
.post('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({ key: 'host_cpu_limit' });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toMatch(/value is required/);
|
|
});
|
|
|
|
it('updates an allowlisted key', async () => {
|
|
const res = await request(app)
|
|
.post('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({ key: 'host_cpu_limit', value: '75' });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.success).toBe(true);
|
|
|
|
const settings = DatabaseService.getInstance().getGlobalSettings();
|
|
expect(settings.host_cpu_limit).toBe('75');
|
|
});
|
|
|
|
it('rejects an enum-shaped key whose value is not one of the allowed literals', async () => {
|
|
// Regression: the single-key POST previously wrote `String(value)`
|
|
// without re-validating, so an allowlisted enum-shaped key like
|
|
// `mesh_auto_recreate` could store arbitrary strings (`'banana'`)
|
|
// that the bulk PATCH would later refuse. The single-key path now
|
|
// routes through the same SettingsPatchSchema as PATCH.
|
|
const res = await request(app)
|
|
.post('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({ key: 'mesh_auto_recreate', value: 'banana' });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toBe('Validation failed');
|
|
expect(res.body.details).toBeInstanceOf(Object);
|
|
const settings = DatabaseService.getInstance().getGlobalSettings();
|
|
// Confirm the bad write did NOT leak through.
|
|
expect(settings.mesh_auto_recreate).not.toBe('banana');
|
|
});
|
|
|
|
it('accepts a well-formed mesh_auto_recreate write', async () => {
|
|
const res = await request(app)
|
|
.post('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({ key: 'mesh_auto_recreate', value: '1' });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.success).toBe(true);
|
|
expect(DatabaseService.getInstance().getGlobalSettings().mesh_auto_recreate).toBe('1');
|
|
// Reset for any later tests that read the value.
|
|
DatabaseService.getInstance().updateGlobalSetting('mesh_auto_recreate', '0');
|
|
});
|
|
|
|
it('rejects an out-of-range numeric value on the single-key path (now schema-validated)', async () => {
|
|
// Same regression class as mesh_auto_recreate=banana, but exercised
|
|
// on a numeric setting to lock down the schema routing.
|
|
const res = await request(app)
|
|
.post('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({ key: 'host_cpu_limit', value: '9999' });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toBe('Validation failed');
|
|
});
|
|
});
|
|
|
|
describe('PATCH /api/settings (bulk update)', () => {
|
|
it('rejects unauthenticated requests with 401', async () => {
|
|
const res = await request(app).patch('/api/settings').send({ host_cpu_limit: 50 });
|
|
expect(res.status).toBe(401);
|
|
});
|
|
|
|
it('rejects non-admin users with 403', async () => {
|
|
const res = await request(app)
|
|
.patch('/api/settings')
|
|
.set('Cookie', viewerCookie)
|
|
.send({ host_cpu_limit: 50 });
|
|
expect(res.status).toBe(403);
|
|
});
|
|
|
|
it('rejects invalid values with 400 and returns field-level errors', async () => {
|
|
const res = await request(app)
|
|
.patch('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({ host_cpu_limit: 9999, log_retention_days: 'not-a-number' });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error).toBe('Validation failed');
|
|
expect(res.body.details).toBeInstanceOf(Object);
|
|
});
|
|
|
|
it('applies a partial update atomically', async () => {
|
|
const res = await request(app)
|
|
.patch('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({ host_cpu_limit: 60, host_ram_limit: 70 });
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.success).toBe(true);
|
|
|
|
const settings = DatabaseService.getInstance().getGlobalSettings();
|
|
expect(settings.host_cpu_limit).toBe('60');
|
|
expect(settings.host_ram_limit).toBe('70');
|
|
});
|
|
|
|
it('accepts an empty body and no-ops successfully', async () => {
|
|
const res = await request(app)
|
|
.patch('/api/settings')
|
|
.set('Cookie', adminCookie)
|
|
.send({});
|
|
expect(res.status).toBe(200);
|
|
});
|
|
});
|