mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-22 08:06:42 +00:00
feat(fleet-sync): gate sync-status polling on admin role (#1271)
* feat(fleet-sync): gate sync-status polling on admin role The fleet sync status poll requires a paid admin on the server, but the useFleetSyncStatus hook only checked the paid tier. A paid non-admin who opened the Fleet Status tab or Settings, Nodes would poll the endpoint every 30 seconds and get a 403 each time, with the policy sync rows silently never loading. Gate the hook on both paid tier and admin role so the client mirrors the server and the request only fires when it can succeed. Also add a one-time log when an instance transitions from control to replica, and a real-database integration test covering the full receive path: role flip, identity and watermark persistence, wholesale row replacement with local rows preserved, replica read-only enforcement, and the stale-watermark and control-anchor rejection branches. Includes a hook test asserting the gate across the paid and admin matrix. * fix(fleet-sync): drop sync-status rows that resolve after the gate flips A sync-status fetch started while the user was an eligible paid admin could resolve after the user lost eligibility mid-flight (role or tier change), re-populating the status rows that the gate-false path had already cleared. That briefly re-enabled the policy-sync rows and the anchor-mismatch banner for a now-ineligible client. Track the latest gate state in a ref and skip the state writes when the fetch resolves after eligibility was lost, so the rows stay empty under role and tier transitions. Adds a regression test for the late-resolve path. * fix(security): sanitize control identity before logging replica transition The control to replica transition log interpolated the control fingerprint straight from the inbound sync payload, so a sibling pushing a forged controlIdentity with embedded CR/LF could split or spoof log lines. Wrap the value in the shared sanitizeForLog helper, matching every other tainted log sink, so control characters are stripped before the entry is written.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
|
||||
const fetchStatusesMock = vi.fn();
|
||||
let mockIsPaid = false;
|
||||
let mockIsAdmin = false;
|
||||
|
||||
vi.mock('@/lib/fleetSyncApi', () => ({
|
||||
fetchFleetSyncStatuses: (...args: unknown[]) => fetchStatusesMock(...args),
|
||||
}));
|
||||
vi.mock('@/context/LicenseContext', () => ({
|
||||
useLicense: () => ({ isPaid: mockIsPaid }),
|
||||
}));
|
||||
vi.mock('@/context/AuthContext', () => ({
|
||||
useAuth: () => ({ isAdmin: mockIsAdmin }),
|
||||
}));
|
||||
// Run the interval callback synchronously so we can assert it is (not) armed
|
||||
// without faking timers.
|
||||
vi.mock('@/lib/utils', () => ({
|
||||
visibilityInterval: (fn: () => void) => { fn(); return () => undefined; },
|
||||
}));
|
||||
|
||||
import { useFleetSyncStatus } from '../useFleetSyncStatus';
|
||||
|
||||
beforeEach(() => {
|
||||
fetchStatusesMock.mockReset().mockResolvedValue([{ node_id: 1, resource: 'scan_policies' }]);
|
||||
mockIsPaid = false;
|
||||
mockIsAdmin = false;
|
||||
});
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('useFleetSyncStatus gate parity', () => {
|
||||
it('fetches for a paid admin (mirrors requireAdmin + requirePaid)', async () => {
|
||||
mockIsPaid = true;
|
||||
mockIsAdmin = true;
|
||||
const { result } = renderHook(() => useFleetSyncStatus());
|
||||
|
||||
await waitFor(() => expect(result.current.statuses).toHaveLength(1));
|
||||
expect(fetchStatusesMock).toHaveBeenCalled();
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
it('does not fetch for a paid non-admin (the 403-loop this fix prevents)', async () => {
|
||||
mockIsPaid = true;
|
||||
mockIsAdmin = false;
|
||||
const { result } = renderHook(() => useFleetSyncStatus());
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(fetchStatusesMock).not.toHaveBeenCalled();
|
||||
expect(result.current.statuses).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not fetch for an admin on a community license', async () => {
|
||||
mockIsPaid = false;
|
||||
mockIsAdmin = true;
|
||||
const { result } = renderHook(() => useFleetSyncStatus());
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(fetchStatusesMock).not.toHaveBeenCalled();
|
||||
expect(result.current.statuses).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not fetch when neither paid nor admin', async () => {
|
||||
const { result } = renderHook(() => useFleetSyncStatus());
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(fetchStatusesMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores rows from a fetch that resolves after the gate flips ineligible', async () => {
|
||||
let resolveFetch!: (rows: Array<{ node_id: number; resource: string }>) => void;
|
||||
const pending = new Promise<Array<{ node_id: number; resource: string }>>((res) => { resolveFetch = res; });
|
||||
fetchStatusesMock.mockReturnValue(pending);
|
||||
mockIsPaid = true;
|
||||
mockIsAdmin = true;
|
||||
const { result, rerender } = renderHook(() => useFleetSyncStatus());
|
||||
expect(fetchStatusesMock).toHaveBeenCalled();
|
||||
expect(result.current.statuses).toEqual([]); // in-flight, not resolved yet
|
||||
|
||||
// Lose admin before the in-flight fetch resolves.
|
||||
mockIsAdmin = false;
|
||||
act(() => { rerender(); });
|
||||
expect(result.current.statuses).toEqual([]);
|
||||
|
||||
// The late resolve must not republish rows to the now-ineligible client.
|
||||
await act(async () => {
|
||||
resolveFetch([{ node_id: 9, resource: 'scan_policies' }]);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(result.current.statuses).toEqual([]);
|
||||
});
|
||||
|
||||
it('starts fetching once the user becomes a paid admin', async () => {
|
||||
const { result, rerender } = renderHook(() => useFleetSyncStatus());
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(fetchStatusesMock).not.toHaveBeenCalled();
|
||||
|
||||
mockIsPaid = true;
|
||||
mockIsAdmin = true;
|
||||
act(() => { rerender(); });
|
||||
|
||||
await waitFor(() => expect(fetchStatusesMock).toHaveBeenCalled());
|
||||
await waitFor(() => expect(result.current.statuses).toHaveLength(1));
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useLicense } from '@/context/LicenseContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import { visibilityInterval } from '@/lib/utils';
|
||||
import { fetchFleetSyncStatuses, type FleetSyncStatus } from '@/lib/fleetSyncApi';
|
||||
|
||||
@@ -7,9 +8,10 @@ const REFRESH_INTERVAL_MS = 30_000;
|
||||
|
||||
/**
|
||||
* Polls `/api/fleet/sync-status` and exposes the rows plus a manual
|
||||
* `refresh()`. Skips fetching for community-tier users since the endpoint is
|
||||
* paid-tier-gated; the hook returns an empty array in that case so consumers
|
||||
* can render the `!isPaid` branch without conditionals.
|
||||
* `refresh()`. The endpoint requires a paid admin, so the hook only fetches
|
||||
* for paid admins and returns an empty array otherwise. This mirrors the
|
||||
* route guard exactly: gating on tier alone would leave a paid non-admin
|
||||
* polling an endpoint that always 403s.
|
||||
*/
|
||||
export function useFleetSyncStatus(): {
|
||||
statuses: FleetSyncStatus[];
|
||||
@@ -17,29 +19,37 @@ export function useFleetSyncStatus(): {
|
||||
refresh: () => void;
|
||||
} {
|
||||
const { isPaid } = useLicense();
|
||||
const { isAdmin } = useAuth();
|
||||
const canQuery = isPaid && isAdmin;
|
||||
// Reflects the latest gate state so a fetch begun while eligible cannot
|
||||
// publish its rows after the user loses eligibility mid-flight (role or
|
||||
// tier change). Without this, a late resolve would re-populate statuses
|
||||
// that the gate-false path already cleared.
|
||||
const canQueryRef = useRef(canQuery);
|
||||
canQueryRef.current = canQuery;
|
||||
const [statuses, setStatuses] = useState<FleetSyncStatus[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
if (!isPaid) {
|
||||
if (!canQuery) {
|
||||
setStatuses([]);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
fetchFleetSyncStatuses()
|
||||
.then((rows) => setStatuses(rows))
|
||||
.then((rows) => { if (canQueryRef.current) setStatuses(rows); })
|
||||
.catch((err) => {
|
||||
// Stale data stays visible to avoid flicker; log so the failure isn't completely silent.
|
||||
console.warn('[FleetSync] sync-status fetch failed:', err);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [isPaid]);
|
||||
.finally(() => { if (canQueryRef.current) setLoading(false); });
|
||||
}, [canQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
if (!isPaid) return undefined;
|
||||
if (!canQuery) return undefined;
|
||||
return visibilityInterval(refresh, REFRESH_INTERVAL_MS);
|
||||
}, [isPaid, refresh]);
|
||||
}, [canQuery, refresh]);
|
||||
|
||||
return { statuses, loading, refresh };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user