diff --git a/src/web-server/routes/index.ts b/src/web-server/routes/index.ts index 85534e0c..7e84b386 100644 --- a/src/web-server/routes/index.ts +++ b/src/web-server/routes/index.ts @@ -6,6 +6,7 @@ */ import { Router } from 'express'; +import { requireLocalAccessWhenAuthDisabled } from '../middleware/auth-middleware'; // Import domain routers import profileRoutes from './profile-routes'; @@ -36,6 +37,30 @@ import claudeExtensionRoutes from './claude-extension-routes'; // Create the main API router export const apiRoutes = Router(); +const REMOTE_WRITE_ACCESS_ERROR = + 'Remote dashboard writes require localhost access when dashboard auth is disabled.'; + +function isMutationMethod(method: string): boolean { + const normalized = method.toUpperCase(); + return ( + normalized === 'POST' || + normalized === 'PUT' || + normalized === 'PATCH' || + normalized === 'DELETE' + ); +} + +apiRoutes.use((req, res, next) => { + if (!isMutationMethod(req.method)) { + next(); + return; + } + + if (requireLocalAccessWhenAuthDisabled(req, res, REMOTE_WRITE_ACCESS_ERROR)) { + next(); + } +}); + // ==================== Profile & Settings ==================== // Profile CRUD, settings management, presets, accounts apiRoutes.use('/profiles', profileRoutes); diff --git a/tests/unit/web-server/api-routes-remote-write-guard.test.ts b/tests/unit/web-server/api-routes-remote-write-guard.test.ts new file mode 100644 index 00000000..de2a2c77 --- /dev/null +++ b/tests/unit/web-server/api-routes-remote-write-guard.test.ts @@ -0,0 +1,125 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test'; +import express from 'express'; +import type { Server } from 'http'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { apiRoutes } from '../../../src/web-server/routes'; + +describe('api-routes remote write guard', () => { + let server: Server; + let baseUrl = ''; + let forcedRemoteAddress = '127.0.0.1'; + let tempHome = ''; + let originalDashboardAuthEnabled: string | undefined; + let originalCcsHome: string | undefined; + + beforeAll(async () => { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + Object.defineProperty(req.socket, 'remoteAddress', { + value: forcedRemoteAddress, + configurable: true, + }); + next(); + }); + app.use('/api', apiRoutes); + + await new Promise((resolve, reject) => { + server = app.listen(0, '127.0.0.1'); + server.once('error', reject); + server.once('listening', () => resolve()); + }); + + const address = server.address(); + if (!address || typeof address === 'string') { + throw new Error('Unable to resolve test server port'); + } + baseUrl = `http://127.0.0.1:${address.port}`; + }); + + afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); + }); + + beforeEach(() => { + originalDashboardAuthEnabled = process.env.CCS_DASHBOARD_AUTH_ENABLED; + originalCcsHome = process.env.CCS_HOME; + tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'ccs-api-routes-remote-write-guard-')); + process.env.CCS_HOME = tempHome; + process.env.CCS_DASHBOARD_AUTH_ENABLED = 'false'; + forcedRemoteAddress = '10.10.0.24'; + }); + + afterEach(() => { + if (originalDashboardAuthEnabled !== undefined) { + process.env.CCS_DASHBOARD_AUTH_ENABLED = originalDashboardAuthEnabled; + } else { + delete process.env.CCS_DASHBOARD_AUTH_ENABLED; + } + + if (originalCcsHome !== undefined) { + process.env.CCS_HOME = originalCcsHome; + } else { + delete process.env.CCS_HOME; + } + + if (tempHome && fs.existsSync(tempHome)) { + fs.rmSync(tempHome, { recursive: true, force: true }); + tempHome = ''; + } + }); + + it('allows remote read-only GET requests when dashboard auth is disabled', async () => { + const response = await fetch(`${baseUrl}/api/profiles`); + + expect(response.status).toBe(200); + }); + + it('blocks remote profile creation when dashboard auth is disabled', async () => { + const response = await fetch(`${baseUrl}/api/profiles`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'demo', + baseUrl: 'https://api.example.com', + apiKey: 'token', + }), + }); + + expect(response.status).toBe(403); + expect(await response.json()).toEqual({ + error: 'Remote dashboard writes require localhost access when dashboard auth is disabled.', + }); + }); + + it('blocks remote backup restore when dashboard auth is disabled', async () => { + const response = await fetch(`${baseUrl}/api/persist/restore`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }); + + expect(response.status).toBe(403); + expect(await response.json()).toEqual({ + error: 'Remote dashboard writes require localhost access when dashboard auth is disabled.', + }); + }); + + it('allows remote writes again when dashboard auth is enabled', async () => { + process.env.CCS_DASHBOARD_AUTH_ENABLED = 'true'; + + const response = await fetch(`${baseUrl}/api/profiles`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'demo', + baseUrl: 'https://api.example.com', + apiKey: 'token', + }), + }); + + expect(response.status).not.toBe(403); + }); +});