mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-18 22:36:19 +00:00
feat(nodes): hide hub-only views when active node is remote (#1007)
* feat(nodes): hide hub-only views when active node is remote Fleet, Schedules, Audit, Logs, and Auto-Update operate on hub-owned state (node registry, fleet schedules, centralized audit, fleet-wide log aggregation, fleet-wide update preview). When the active node is remote, proxying those surfaces would show that remote's own disconnected state instead of the hub's. Hide them from the nav strip and force-redirect to Home if one was open during the node switch. Backend hubOnlyGuard middleware sits between nodeContextMiddleware and the remote proxy and rejects /api/scheduled-tasks, /api/audit-log, and /api/notification-routes with 403 + HUB_ONLY_ENDPOINT when nodeId resolves to a remote, closing the script-bypass path the UI gating cannot reach. Settings sub-sections were already gated via the hiddenOnRemote registry; this extends the same model to top-level views. * docs(nodes): note hub-only visibility on Fleet, Schedules, Audit, Logs, Auto-Update Each of the five hub-only feature pages now points readers to the canonical "What top-level views show when a remote node is active" section in multi-node.mdx, so users landing directly on a feature page understand why the nav item disappears when they switch to a remote node.
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Regression guard for `hubOnlyGuard` middleware.
|
||||
*
|
||||
* Hub-only paths (e.g. /api/scheduled-tasks, /api/audit-log,
|
||||
* /api/notification-routes) manage state owned by the local hub. When a
|
||||
* request carries `x-node-id` for a remote node, the guard must reject
|
||||
* with 409 before the remote proxy forwards it. Without this guard, a
|
||||
* scripted client could trick the proxy into running hub-level operations
|
||||
* on a remote instance, crossing a node-authority boundary that the UI
|
||||
* promises will not happen.
|
||||
*
|
||||
* The guard sits between `enforceApiTokenScope` (step 12) and
|
||||
* `createRemoteProxyMiddleware` (step 14).
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { setupTestDb, cleanupTestDb, TEST_USERNAME, TEST_JWT_SECRET } from './helpers/setupTestDb';
|
||||
|
||||
describe('hubOnlyGuard', () => {
|
||||
let tmpDir: string;
|
||||
let app: import('express').Express;
|
||||
let authHeader: string;
|
||||
let remoteNodeId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
tmpDir = await setupTestDb();
|
||||
({ app } = await import('../index'));
|
||||
|
||||
const { DatabaseService } = await import('../services/DatabaseService');
|
||||
remoteNodeId = DatabaseService.getInstance().addNode({
|
||||
name: 'hub-only-remote',
|
||||
type: 'remote',
|
||||
compose_dir: '/tmp',
|
||||
is_default: false,
|
||||
api_url: 'http://127.0.0.1:1',
|
||||
api_token: 'hub-only-token',
|
||||
});
|
||||
|
||||
const token = jwt.sign({ username: TEST_USERNAME }, TEST_JWT_SECRET, { expiresIn: '1m' });
|
||||
authHeader = `Bearer ${token}`;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
cleanupTestDb(tmpDir);
|
||||
});
|
||||
|
||||
it('rejects /api/scheduled-tasks with 403 when nodeId targets a remote node', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/scheduled-tasks/')
|
||||
.set('Authorization', authHeader)
|
||||
.set('x-node-id', String(remoteNodeId));
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body?.code).toBe('HUB_ONLY_ENDPOINT');
|
||||
expect(res.body?.error).toMatch(/hub-only/i);
|
||||
});
|
||||
|
||||
it('rejects /api/audit-log with 403 when nodeId targets a remote node', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/audit-log/')
|
||||
.set('Authorization', authHeader)
|
||||
.set('x-node-id', String(remoteNodeId));
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body?.code).toBe('HUB_ONLY_ENDPOINT');
|
||||
});
|
||||
|
||||
it('rejects /api/notification-routes with 403 when nodeId targets a remote node', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/notification-routes/')
|
||||
.set('Authorization', authHeader)
|
||||
.set('x-node-id', String(remoteNodeId));
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body?.code).toBe('HUB_ONLY_ENDPOINT');
|
||||
});
|
||||
|
||||
it('lets /api/scheduled-tasks through to the local handler when no nodeId is set', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/scheduled-tasks/')
|
||||
.set('Authorization', authHeader);
|
||||
|
||||
// Anything other than 403 with HUB_ONLY_ENDPOINT proves the guard fell
|
||||
// through. Local handler may return 200 or a tier-gate 403; both are
|
||||
// acceptable here, so assert on the body code rather than the status.
|
||||
expect(res.body?.code).not.toBe('HUB_ONLY_ENDPOINT');
|
||||
});
|
||||
|
||||
it('does not interfere with non-hub paths even when nodeId targets a remote node', async () => {
|
||||
// /api/stacks is not hub-only and should be forwarded by the proxy.
|
||||
// The exact upstream-error status is not the contract here; what
|
||||
// matters is that the guard did not reject with HUB_ONLY_ENDPOINT.
|
||||
const res = await request(app)
|
||||
.get('/api/stacks')
|
||||
.set('Authorization', authHeader)
|
||||
.set('x-node-id', String(remoteNodeId));
|
||||
|
||||
expect(res.body?.code).not.toBe('HUB_ONLY_ENDPOINT');
|
||||
});
|
||||
});
|
||||
+7
-6
@@ -11,7 +11,7 @@ import './types/express';
|
||||
/**
|
||||
* Build an Express app with the full middleware pipeline installed.
|
||||
*
|
||||
* Canonical middleware order (16 steps). Do not reorder without re-running the
|
||||
* Canonical middleware order (17 steps). Do not reorder without re-running the
|
||||
* regression checklist in `docs/internal/architecture/middleware-order.md`.
|
||||
*
|
||||
* 1. trust proxy
|
||||
@@ -26,12 +26,13 @@ import './types/express';
|
||||
* 10. authGate (at /api) -- registered in index.ts
|
||||
* 11. auditLog (at /api) -- registered in index.ts
|
||||
* 12. enforceApiTokenScope (at /api) -- registered in index.ts
|
||||
* 13. createRemoteProxyMiddleware -- proxy/remoteNodeProxy.ts, registered in index.ts
|
||||
* 14. routes -- registered in index.ts from routes/*
|
||||
* 15. static serving + SPA fallback -- registered in index.ts
|
||||
* 16. errorHandler -- registered in index.ts
|
||||
* 13. hubOnlyGuard (at /api) -- middleware/hubOnlyGuard.ts, registered in index.ts
|
||||
* 14. createRemoteProxyMiddleware -- proxy/remoteNodeProxy.ts, registered in index.ts
|
||||
* 15. routes -- registered in index.ts from routes/*
|
||||
* 16. static serving + SPA fallback -- registered in index.ts
|
||||
* 17. errorHandler -- registered in index.ts
|
||||
*
|
||||
* Steps 10 to 12 and 14 must run after the public auth routers (meta, auth,
|
||||
* Steps 10 to 13 and 15 must run after the public auth routers (meta, auth,
|
||||
* mfa, sso) are registered so those routes stay reachable without a session
|
||||
* cookie. index.ts mounts those public routers before step 10 to preserve
|
||||
* that invariant.
|
||||
|
||||
@@ -22,3 +22,28 @@ export function isProxyExemptPath(path: string): boolean {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Path prefixes that are hub-only: they manage state owned by the local hub
|
||||
// (centralized audit, fleet schedules, notification routing rules). Routed
|
||||
// to the local hub when nodeId resolves to local, but rejected with 409 when
|
||||
// nodeId resolves to a remote node so a script/curl call cannot trick the
|
||||
// proxy into forwarding hub-only authority across a node boundary.
|
||||
//
|
||||
// Frontend nav surfaces are gated separately via `HUB_ONLY_VIEWS` in
|
||||
// useViewNavigationState.ts; this list is the backend defense-in-depth.
|
||||
//
|
||||
// Consumed by:
|
||||
// - middleware/hubOnlyGuard.ts → 409 when nodeId is remote
|
||||
export const HUB_ONLY_PREFIXES: readonly string[] = [
|
||||
'/api/scheduled-tasks/',
|
||||
'/api/audit-log/',
|
||||
'/api/notification-routes/',
|
||||
];
|
||||
|
||||
/** Returns true when the path is hub-only and must not be proxied to a remote node. */
|
||||
export function isHubOnlyPath(path: string): boolean {
|
||||
for (const prefix of HUB_ONLY_PREFIXES) {
|
||||
if (path.startsWith(prefix)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import express, { Request, Response } from 'express';
|
||||
import './types/express';
|
||||
import { authGate, auditLog } from './middleware/authGate';
|
||||
import { enforceApiTokenScope } from './middleware/apiTokenScope';
|
||||
import { hubOnlyGuard } from './middleware/hubOnlyGuard';
|
||||
import { errorHandler } from './middleware/errorHandler';
|
||||
import { createApp } from './app';
|
||||
import { createRemoteProxyMiddleware } from './proxy/remoteNodeProxy';
|
||||
@@ -82,6 +83,14 @@ app.use('/api', auditLog);
|
||||
|
||||
app.use('/api', enforceApiTokenScope);
|
||||
|
||||
// Hub-only guard: reject requests whose nodeId resolves to a remote node
|
||||
// when the path is hub-only (e.g. /api/scheduled-tasks, /api/audit-log,
|
||||
// /api/notification-routes). Without this, the proxy would forward the
|
||||
// request and process it on the remote as a local call, crossing a
|
||||
// node-authority boundary that the UI hides. See helpers/proxyExemptPaths.ts
|
||||
// for the prefix list and middleware/hubOnlyGuard.ts for the rationale.
|
||||
app.use('/api', hubOnlyGuard);
|
||||
|
||||
// Remote Node HTTP Proxy (see proxy/remoteNodeProxy.ts). Mounted BEFORE the
|
||||
// per-group routers so a request targeting a remote node short-circuits into
|
||||
// the proxy instead of hitting a local handler that would read local state.
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { Request, Response, NextFunction, RequestHandler } from 'express';
|
||||
import { NodeRegistry } from '../services/NodeRegistry';
|
||||
import { isHubOnlyPath } from '../helpers/proxyExemptPaths';
|
||||
|
||||
/**
|
||||
* Reject hub-only API requests whose `req.nodeId` resolves to a remote node.
|
||||
*
|
||||
* The hub-level views in the frontend (Schedules, Audit, Notification
|
||||
* Routing config, etc.) are hidden from the nav strip when the active node
|
||||
* is remote, so a normal user never reaches these endpoints with a remote
|
||||
* nodeId. A scripted client could still craft `x-node-id: <remote>` against
|
||||
* one of these paths; without this guard, the request would be forwarded
|
||||
* by `remoteNodeProxy` and processed on the remote as if it were local,
|
||||
* silently crossing a node-authority boundary that the UI promised would
|
||||
* not happen.
|
||||
*
|
||||
* Mounted at `/api` between `nodeContextMiddleware` (which sets req.nodeId)
|
||||
* and `createRemoteProxyMiddleware` (which would otherwise forward the
|
||||
* request). Rejects with 403 — the endpoint exists but the request cannot
|
||||
* be served as routed.
|
||||
*
|
||||
* Returns 403 only for hub-only paths; non-hub paths fall through.
|
||||
*/
|
||||
export const hubOnlyGuard: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
|
||||
if (!isHubOnlyPath(`/api${req.path}`)) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const node = NodeRegistry.getInstance().getNode(req.nodeId);
|
||||
if (node?.type === 'remote') {
|
||||
res.status(403).json({
|
||||
error: 'This endpoint is hub-only and cannot be proxied to a remote node. Switch the active node back to your local hub.',
|
||||
code: 'HUB_ONLY_ENDPOINT',
|
||||
});
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
Reference in New Issue
Block a user