mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-18 06:23:18 +00:00
fix(nodes): never send stored node tokens to clients (#1281)
Node read endpoints now return a client-safe projection that omits the stored api_token and exposes a has_token boolean instead, so a node's long-lived proxy credential is never serialized to a browser or API token client. The token stays encrypted at rest and is read server-side only by the components that need it (the remote proxy, the connection test, and the mesh dialer). The edit form opens the API Token field blank, and a blank value keeps the existing credential, so saving an edit without retyping the token no longer clears it; a non-empty value rotates it. The backend enforces the same rule defensively. Node management actions (add, edit, delete, test connection, generate node token) are gated in the UI to match their server-side permission checks, so operators no longer see an action the API would reject. The test-connection route also gains the missing server-side permission and token-scope guards. Also validate the x-node-id header and fall back to the default node for malformed values instead of an obscure 404, and return 400 (not 500) when deleting the default node.
This commit is contained in:
@@ -8,6 +8,34 @@ import { setupTestDb, cleanupTestDb, TEST_USERNAME, TEST_JWT_SECRET } from './he
|
||||
import { disableCapability, enableCapability } from '../services/CapabilityRegistry';
|
||||
import { NodeRegistry } from '../services/NodeRegistry';
|
||||
import { CacheService } from '../services/CacheService';
|
||||
import { DatabaseService } from '../services/DatabaseService';
|
||||
import { nodeContextMiddleware } from '../middleware/nodeContext';
|
||||
|
||||
/** Mint a Bearer for a non-admin user, creating the row if needed so
|
||||
* authMiddleware (which resolves the role from the DB) sees the real role. */
|
||||
function tokenForRole(username: string, role: 'viewer' | 'deployer'): string {
|
||||
const db = DatabaseService.getInstance();
|
||||
if (!db.getUserByUsername(username)) {
|
||||
db.addUser({ username, password_hash: 'x', role });
|
||||
}
|
||||
return `Bearer ${jwt.sign({ username }, TEST_JWT_SECRET, { expiresIn: '1m' })}`;
|
||||
}
|
||||
|
||||
async function createRemoteNode(token: string): Promise<number> {
|
||||
const res = await request(app)
|
||||
.post('/api/nodes')
|
||||
.set('Authorization', token)
|
||||
.send({
|
||||
name: `remote-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
||||
type: 'remote',
|
||||
mode: 'proxy',
|
||||
api_url: 'http://192.168.1.77:1852',
|
||||
api_token: 'tok-original',
|
||||
compose_dir: '/app/compose',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
return res.body.id as number;
|
||||
}
|
||||
|
||||
let tmpDir: string;
|
||||
let app: import('express').Express;
|
||||
@@ -135,3 +163,125 @@ describe('Stack name validation on GET routes (H3 fix)', () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Node read endpoints never leak the api_token (C-1)', () => {
|
||||
it('GET /api/nodes omits api_token and exposes has_token instead', async () => {
|
||||
const id = await createRemoteNode(authHeader);
|
||||
const res = await request(app).get('/api/nodes').set('Authorization', authHeader);
|
||||
expect(res.status).toBe(200);
|
||||
const nodes = res.body as Array<Record<string, unknown>>;
|
||||
for (const n of nodes) {
|
||||
expect(Object.prototype.hasOwnProperty.call(n, 'api_token')).toBe(false);
|
||||
expect(typeof n.has_token).toBe('boolean');
|
||||
}
|
||||
const created = nodes.find((n) => n.id === id)!;
|
||||
expect(created.has_token).toBe(true);
|
||||
const local = nodes.find((n) => n.type === 'local')!;
|
||||
expect(local.has_token).toBe(false);
|
||||
});
|
||||
|
||||
it('GET /api/nodes/:id omits api_token and exposes has_token', async () => {
|
||||
const id = await createRemoteNode(authHeader);
|
||||
const res = await request(app).get(`/api/nodes/${id}`).set('Authorization', authHeader);
|
||||
expect(res.status).toBe(200);
|
||||
expect(Object.prototype.hasOwnProperty.call(res.body, 'api_token')).toBe(false);
|
||||
expect(res.body.has_token).toBe(true);
|
||||
// The decrypted secret still lives server-side for the proxy / test paths.
|
||||
expect(DatabaseService.getInstance().getNode(id)?.api_token).toBe('tok-original');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /api/nodes/:id preserves the token unless a new one is supplied (H-1)', () => {
|
||||
it('keeps the stored token when api_token is omitted', async () => {
|
||||
const id = await createRemoteNode(authHeader);
|
||||
const res = await request(app)
|
||||
.put(`/api/nodes/${id}`)
|
||||
.set('Authorization', authHeader)
|
||||
.send({ name: 'renamed-keep', api_url: 'http://192.168.1.77:1852', compose_dir: '/app/compose' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(DatabaseService.getInstance().getNode(id)?.api_token).toBe('tok-original');
|
||||
});
|
||||
|
||||
it('keeps the stored token when api_token is an empty string', async () => {
|
||||
const id = await createRemoteNode(authHeader);
|
||||
const res = await request(app)
|
||||
.put(`/api/nodes/${id}`)
|
||||
.set('Authorization', authHeader)
|
||||
.send({ name: 'renamed-blank', api_token: '', api_url: 'http://192.168.1.77:1852', compose_dir: '/app/compose' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(DatabaseService.getInstance().getNode(id)?.api_token).toBe('tok-original');
|
||||
});
|
||||
|
||||
it('rotates the token when a non-empty api_token is supplied', async () => {
|
||||
const id = await createRemoteNode(authHeader);
|
||||
const res = await request(app)
|
||||
.put(`/api/nodes/${id}`)
|
||||
.set('Authorization', authHeader)
|
||||
.send({ name: 'renamed-rotate', api_token: 'tok-new', api_url: 'http://192.168.1.77:1852', compose_dir: '/app/compose' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(DatabaseService.getInstance().getNode(id)?.api_token).toBe('tok-new');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/nodes/:id/test authorization (H-3)', () => {
|
||||
it('403s a non-admin (viewer) with PERMISSION_DENIED', async () => {
|
||||
const id = await createRemoteNode(authHeader);
|
||||
const res = await request(app)
|
||||
.post(`/api/nodes/${id}/test`)
|
||||
.set('Authorization', tokenForRole('node-test-viewer', 'viewer'));
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.code).toBe('PERMISSION_DENIED');
|
||||
});
|
||||
|
||||
it('403s a full-admin API token with SCOPE_DENIED', async () => {
|
||||
const id = await createRemoteNode(authHeader);
|
||||
const mint = await request(app)
|
||||
.post('/api/api-tokens')
|
||||
.set('Authorization', authHeader)
|
||||
.send({ name: `node-test-reject-${Date.now()}`, scope: 'full-admin' });
|
||||
const apiToken = mint.body.token as string;
|
||||
expect(apiToken).toBeTruthy();
|
||||
const res = await request(app)
|
||||
.post(`/api/nodes/${id}/test`)
|
||||
.set('Authorization', `Bearer ${apiToken}`);
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.code).toBe('SCOPE_DENIED');
|
||||
});
|
||||
});
|
||||
|
||||
describe('nodeContextMiddleware nodeId validation (M-2)', () => {
|
||||
type MiddlewareReq = { headers: Record<string, string>; query: Record<string, string>; path: string; nodeId?: number };
|
||||
|
||||
function run(req: MiddlewareReq): { status: number; nextCalled: boolean } {
|
||||
let status = 0;
|
||||
let nextCalled = false;
|
||||
const res = { status: (c: number) => { status = c; return { json: () => undefined }; } };
|
||||
nodeContextMiddleware(req as never, res as never, (() => { nextCalled = true; }) as never);
|
||||
return { status, nextCalled };
|
||||
}
|
||||
|
||||
it('falls back to the default node for a malformed x-node-id instead of 404', () => {
|
||||
const req: MiddlewareReq = { headers: { 'x-node-id': 'abc' }, query: {}, path: '/api/stats' };
|
||||
const { status, nextCalled } = run(req);
|
||||
expect(nextCalled).toBe(true);
|
||||
expect(status).toBe(0);
|
||||
expect(req.nodeId).toBe(NodeRegistry.getInstance().getDefaultNodeId());
|
||||
});
|
||||
|
||||
it('still 404s a well-formed but non-existent node id', () => {
|
||||
const req: MiddlewareReq = { headers: { 'x-node-id': '999999' }, query: {}, path: '/api/stats' };
|
||||
const { status, nextCalled } = run(req);
|
||||
expect(status).toBe(404);
|
||||
expect(nextCalled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/nodes/:id default-node guard (M-4)', () => {
|
||||
it('400s when deleting the default node', async () => {
|
||||
const list = await request(app).get('/api/nodes').set('Authorization', authHeader);
|
||||
const def = (list.body as Array<{ id: number; is_default: boolean }>).find((n) => n.is_default)!;
|
||||
const res = await request(app).delete(`/api/nodes/${def.id}`).set('Authorization', authHeader);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toMatch(/default node/i);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { Node } from '../services/DatabaseService';
|
||||
|
||||
/**
|
||||
* Node shape safe to send to a browser or API-token client. The stored
|
||||
* `api_token` (a long-lived node_proxy Bearer credential) is never serialized;
|
||||
* callers that need to know whether a token is configured read `has_token`
|
||||
* instead. The plaintext credential stays server-side, read via
|
||||
* `DatabaseService.getNode` by the components that genuinely need it (for
|
||||
* example the remote proxy, the connection test, and the mesh dialer).
|
||||
*/
|
||||
export type PublicNode = Omit<Node, 'api_token'> & { has_token: boolean };
|
||||
|
||||
/** Project a stored Node into its client-safe form, dropping the api_token. */
|
||||
export function toPublicNode(node: Node): PublicNode {
|
||||
const { api_token, ...rest } = node;
|
||||
return { ...rest, has_token: typeof api_token === 'string' && api_token.length > 0 };
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { Request, Response, NextFunction, RequestHandler } from 'express';
|
||||
import { NodeRegistry } from '../services/NodeRegistry';
|
||||
import { DatabaseService } from '../services/DatabaseService';
|
||||
import { isProxyExemptPath } from '../helpers/proxyExemptPaths';
|
||||
import { sanitizeForLog } from '../utils/safeLog';
|
||||
|
||||
/**
|
||||
* Resolve `req.nodeId` from the `x-node-id` header, `?nodeId=` query param,
|
||||
@@ -15,13 +16,24 @@ import { isProxyExemptPath } from '../helpers/proxyExemptPaths';
|
||||
export const nodeContextMiddleware: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
|
||||
const nodeIdHeader = req.headers['x-node-id'] as string;
|
||||
const nodeIdQuery = req.query.nodeId as string;
|
||||
if (nodeIdHeader) {
|
||||
req.nodeId = parseInt(nodeIdHeader, 10);
|
||||
} else if (nodeIdQuery) {
|
||||
req.nodeId = parseInt(nodeIdQuery, 10);
|
||||
} else {
|
||||
req.nodeId = NodeRegistry.getInstance().getDefaultNodeId();
|
||||
}
|
||||
// A malformed id (parseInt → NaN, or a non-positive value) must fall back to
|
||||
// the default node rather than resolve to NaN and trip the obscure 404 below.
|
||||
// A well-formed id for a node that does not exist still 404s further down;
|
||||
// only malformed input falls through to the default.
|
||||
const parseNodeId = (raw: string | undefined): number | null => {
|
||||
if (!raw) return null;
|
||||
const n = parseInt(raw, 10);
|
||||
if (Number.isInteger(n) && n > 0) return n;
|
||||
// Present but malformed is a client bug: warn so the fall-back to the
|
||||
// default node is observable instead of a request silently landing on the
|
||||
// wrong node during debugging.
|
||||
console.warn(`[NodeContext] Ignoring malformed node id "${sanitizeForLog(raw)}"; using the default node.`);
|
||||
return null;
|
||||
};
|
||||
req.nodeId =
|
||||
parseNodeId(nodeIdHeader) ??
|
||||
parseNodeId(nodeIdQuery) ??
|
||||
NodeRegistry.getInstance().getDefaultNodeId();
|
||||
|
||||
if (req.path.startsWith('/api/') && !isProxyExemptPath(req.path)) {
|
||||
const node = DatabaseService.getInstance().getNode(req.nodeId);
|
||||
|
||||
@@ -18,6 +18,7 @@ import { FleetUpdateTrackerService } from '../services/FleetUpdateTrackerService
|
||||
import { FleetSyncService } from '../services/FleetSyncService';
|
||||
import { isValidRemoteUrl } from '../utils/validation';
|
||||
import { getErrorMessage } from '../utils/errors';
|
||||
import { toPublicNode } from '../helpers/publicNode';
|
||||
import { isDebugEnabled } from '../utils/debug';
|
||||
import { sanitizeForLog } from '../utils/safeLog';
|
||||
|
||||
@@ -95,7 +96,7 @@ export const nodesRouter = Router();
|
||||
nodesRouter.get('/', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const nodes = DatabaseService.getInstance().getNodes();
|
||||
res.json(nodes);
|
||||
res.json(nodes.map(toPublicNode));
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to fetch nodes' });
|
||||
}
|
||||
@@ -149,7 +150,7 @@ nodesRouter.get('/:id', async (req: Request, res: Response) => {
|
||||
if (!node) {
|
||||
return res.status(404).json({ error: 'Node not found' });
|
||||
}
|
||||
res.json(node);
|
||||
res.json(toPublicNode(node));
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to fetch node' });
|
||||
}
|
||||
@@ -191,6 +192,7 @@ nodesRouter.post('/', enrollmentLimiter, async (req: Request, res: Response) =>
|
||||
});
|
||||
|
||||
NodeRegistry.getInstance().notifyNodeAdded(id);
|
||||
console.log(`[Nodes] Created ${type} node "${sanitizeForLog(name)}" (id=${id}, mode=${resolvedMode})`);
|
||||
|
||||
// Backfill replicated security state on the new remote so an operator who
|
||||
// adds a node mid-life does not have to wait for the next policy edit
|
||||
@@ -257,6 +259,16 @@ nodesRouter.put('/:id', async (req: Request, res: Response) => {
|
||||
const id = parseInt(nodeId);
|
||||
const updates = req.body;
|
||||
|
||||
// Keep the existing credential unless a real new token is supplied: the
|
||||
// stored token is never returned to the client, so an untouched edit form
|
||||
// must not clear it. Anything that is not a non-empty string (blank, null,
|
||||
// missing, wrong type) drops the field here (defense-in-depth alongside the
|
||||
// frontend) so it can never overwrite a configured token; only a non-empty
|
||||
// string rotates it.
|
||||
if (typeof updates.api_token !== 'string' || updates.api_token.trim() === '') {
|
||||
delete updates.api_token;
|
||||
}
|
||||
|
||||
const existingNode = DatabaseService.getInstance().getNode(id);
|
||||
if (!existingNode) {
|
||||
return res.status(404).json({ error: 'Node not found' });
|
||||
@@ -273,6 +285,7 @@ nodesRouter.put('/:id', async (req: Request, res: Response) => {
|
||||
|
||||
NodeRegistry.getInstance().evictConnection(id);
|
||||
NodeRegistry.getInstance().notifyNodeUpdated(id);
|
||||
console.log(`[Nodes] Updated node ${id} ("${sanitizeForLog(existingNode.name)}")`);
|
||||
|
||||
// Trigger 2: if the api_token was rotated on a mesh-enabled proxy-mode
|
||||
// remote, close the existing callback bridge and re-dial. The next
|
||||
@@ -313,6 +326,13 @@ nodesRouter.delete('/:id', async (req: Request, res: Response) => {
|
||||
if (!requirePermission(req, res, 'node:manage', 'node', nodeIdParam)) return;
|
||||
try {
|
||||
const id = parseInt(nodeIdParam);
|
||||
const existing = DatabaseService.getInstance().getNode(id);
|
||||
if (!existing) {
|
||||
return res.status(404).json({ error: 'Node not found' });
|
||||
}
|
||||
if (existing.is_default) {
|
||||
return res.status(400).json({ error: 'Cannot delete the default node' });
|
||||
}
|
||||
// Release any live tunnel or mesh bridge before deleting the record so it is
|
||||
// freed immediately rather than lingering until the peer disconnects. Close a
|
||||
// proxy-mode mesh bridge through its dialer FIRST: closeBridge removes the
|
||||
@@ -327,6 +347,7 @@ nodesRouter.delete('/:id', async (req: Request, res: Response) => {
|
||||
NodeRegistry.getInstance().notifyNodeRemoved(id);
|
||||
CacheService.getInstance().invalidate(`${REMOTE_META_NAMESPACE}:${id}`);
|
||||
FleetUpdateTrackerService.getInstance().delete(id);
|
||||
console.log(`[Nodes] Deleted node ${id} ("${sanitizeForLog(existing.name)}")`);
|
||||
res.json({ success: true });
|
||||
} catch (error: unknown) {
|
||||
console.error('Failed to delete node:', error);
|
||||
@@ -485,13 +506,23 @@ nodesRouter.post('/:id/fleet-sync/reset-anchor', async (req: Request, res: Respo
|
||||
});
|
||||
|
||||
nodesRouter.post('/:id/test', async (req: Request, res: Response) => {
|
||||
if (rejectApiTokenScope(req, res, NODE_SCOPE_MESSAGE)) return;
|
||||
const nodeIdParam = req.params.id as string;
|
||||
if (!requirePermission(req, res, 'node:manage', 'node', nodeIdParam)) return;
|
||||
try {
|
||||
const id = parseInt(req.params.id as string);
|
||||
const id = parseInt(nodeIdParam);
|
||||
const startedAt = Date.now();
|
||||
const result = await NodeRegistry.getInstance().testConnection(id);
|
||||
// An explicit test is the operator asking for fresh truth: drop the cached
|
||||
// /api/meta so the next read rebuilds version and capabilities live rather
|
||||
// than serving a value up to the remote-meta TTL old.
|
||||
invalidateRemoteMetaCache(id);
|
||||
if (!result.success) {
|
||||
console.warn(`[Nodes] Connection test failed for node ${id}: ${sanitizeForLog(result.error ?? 'unknown')}`);
|
||||
}
|
||||
if (isDebugEnabled()) {
|
||||
console.log(`[Nodes:diag] test node=${id} success=${result.success} ms=${Date.now() - startedAt}`);
|
||||
}
|
||||
res.json(result);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Connection test failed';
|
||||
@@ -507,6 +538,7 @@ nodesRouter.get('/:id/meta', authMiddleware, async (req: Request, res: Response)
|
||||
res.status(404).json({ error: 'Node not found' });
|
||||
return;
|
||||
}
|
||||
if (isDebugEnabled()) console.log(`[Nodes:diag] meta node=${id} type=${node.type}`);
|
||||
|
||||
if (node.type === 'local') {
|
||||
res.json({ version: getSenchoVersion(), capabilities: getActiveCapabilities() });
|
||||
|
||||
Reference in New Issue
Block a user