mirror of
https://github.com/tiennm99/ccs.git
synced 2026-08-11 00:24:08 +00:00
Merge pull request #920 from kaitranntt/kai/fix/dashboard-remote-readonly-auth-gate
fix(dashboard): gate remote read-only auth
This commit is contained in:
@@ -40,7 +40,7 @@ export async function handleUp(args: string[]): Promise<void> {
|
||||
if (parsed.host) {
|
||||
console.log(
|
||||
info(
|
||||
'Remote access requires dashboard auth. Run inside the container:\n docker exec -it ccs-cliproxy ccs config auth setup'
|
||||
'Full remote management requires dashboard auth. Without it, remote access stays read-only.\nRun inside the container:\n docker exec -it ccs-cliproxy ccs config auth setup'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -42,7 +42,17 @@ export function resolveDashboardAccessState(
|
||||
const isLocalAccess = isLoopbackRemoteAddress(remoteAddress);
|
||||
const authConfigured = Boolean(authConfig.username && authConfig.password_hash);
|
||||
|
||||
if (authConfig.enabled && authConfigured) {
|
||||
if (!authConfig.enabled) {
|
||||
return {
|
||||
authRequired: false,
|
||||
authEnabled: false,
|
||||
authConfigured,
|
||||
isLocalAccess,
|
||||
accessMode: 'open',
|
||||
};
|
||||
}
|
||||
|
||||
if (authConfigured) {
|
||||
return {
|
||||
authRequired: true,
|
||||
authEnabled: true,
|
||||
@@ -52,19 +62,9 @@ export function resolveDashboardAccessState(
|
||||
};
|
||||
}
|
||||
|
||||
if (!authConfig.enabled && isLocalAccess) {
|
||||
return {
|
||||
authRequired: false,
|
||||
authEnabled: false,
|
||||
authConfigured,
|
||||
isLocalAccess: true,
|
||||
accessMode: 'open',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
authRequired: true,
|
||||
authEnabled: authConfig.enabled,
|
||||
authEnabled: true,
|
||||
authConfigured,
|
||||
isLocalAccess,
|
||||
accessMode: 'setup',
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
|
||||
import { Router } from 'express';
|
||||
import { requireLocalAccessWhenAuthDisabled } from '../middleware/auth-middleware';
|
||||
import {
|
||||
handleSummary,
|
||||
handleDaily,
|
||||
@@ -24,6 +25,20 @@ export { prewarmUsageCache, clearUsageCache, getLastFetchTimestamp } from './agg
|
||||
|
||||
export const usageRoutes = Router();
|
||||
|
||||
const USAGE_WRITE_ACCESS_ERROR =
|
||||
'Usage refresh requires localhost access when dashboard auth is disabled.';
|
||||
|
||||
usageRoutes.use((req, res, next) => {
|
||||
if (req.method.toUpperCase() !== 'POST') {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (requireLocalAccessWhenAuthDisabled(req, res, USAGE_WRITE_ACCESS_ERROR)) {
|
||||
next();
|
||||
}
|
||||
});
|
||||
|
||||
// Summary endpoint
|
||||
usageRoutes.get('/summary', handleSummary);
|
||||
|
||||
|
||||
@@ -38,7 +38,8 @@ describe('docker up subcommand', () => {
|
||||
expect(rendered).toContain('Docker stack is running on docker-box.');
|
||||
expect(rendered).toContain('Dashboard port: 4000');
|
||||
expect(rendered).toContain('CLIProxy port: 9317');
|
||||
expect(rendered).toContain('Remote access requires dashboard auth');
|
||||
expect(rendered).toContain('Full remote management requires dashboard auth');
|
||||
expect(rendered).toContain('Without it, remote access stays read-only.');
|
||||
expect(capture.errorLines).toEqual([]);
|
||||
expect(process.exitCode).toBe(0);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
|
||||
import bcrypt from 'bcrypt';
|
||||
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';
|
||||
import {
|
||||
authMiddleware,
|
||||
createSessionMiddleware,
|
||||
} from '../../../src/web-server/middleware/auth-middleware';
|
||||
|
||||
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<void>((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<void>((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('blocks remote PUT requests when dashboard auth is disabled', async () => {
|
||||
const response = await fetch(`${baseUrl}/api/cliproxy-server`, {
|
||||
method: 'PUT',
|
||||
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('blocks remote PATCH requests when dashboard auth is disabled', async () => {
|
||||
const response = await fetch(`${baseUrl}/api/codex/config/patch`, {
|
||||
method: 'PATCH',
|
||||
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('blocks remote DELETE requests when dashboard auth is disabled', async () => {
|
||||
const response = await fetch(`${baseUrl}/api/profiles/demo`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
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 () => {
|
||||
const password = 'testpassword123';
|
||||
process.env.CCS_DASHBOARD_AUTH_ENABLED = 'true';
|
||||
process.env.CCS_DASHBOARD_USERNAME = 'admin';
|
||||
process.env.CCS_DASHBOARD_PASSWORD_HASH = await bcrypt.hash(password, 10);
|
||||
|
||||
const authApp = express();
|
||||
authApp.use(express.json());
|
||||
authApp.use((req, _res, next) => {
|
||||
Object.defineProperty(req.socket, 'remoteAddress', {
|
||||
value: forcedRemoteAddress,
|
||||
configurable: true,
|
||||
});
|
||||
next();
|
||||
});
|
||||
authApp.use(createSessionMiddleware());
|
||||
authApp.use(authMiddleware);
|
||||
authApp.use('/api', apiRoutes);
|
||||
|
||||
const authServer = await new Promise<Server>((resolve, reject) => {
|
||||
const instance = authApp.listen(0, '127.0.0.1');
|
||||
instance.once('error', reject);
|
||||
instance.once('listening', () => resolve(instance));
|
||||
});
|
||||
|
||||
const address = authServer.address();
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('Unable to resolve auth-enabled test server port');
|
||||
}
|
||||
const authBaseUrl = `http://127.0.0.1:${address.port}`;
|
||||
|
||||
const loginResponse = await fetch(`${authBaseUrl}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: 'admin',
|
||||
password,
|
||||
}),
|
||||
});
|
||||
const cookie = loginResponse.headers.get('set-cookie');
|
||||
|
||||
expect(loginResponse.status).toBe(200);
|
||||
expect(cookie).toBeTruthy();
|
||||
|
||||
const response = await fetch(`${authBaseUrl}/api/profiles`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: cookie as string,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: 'demo',
|
||||
baseUrl: 'https://api.example.com',
|
||||
apiKey: 'token',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
|
||||
await new Promise<void>((resolve) => authServer.close(() => resolve()));
|
||||
|
||||
delete process.env.CCS_DASHBOARD_USERNAME;
|
||||
delete process.env.CCS_DASHBOARD_PASSWORD_HASH;
|
||||
});
|
||||
});
|
||||
@@ -54,18 +54,18 @@ describe('resolveDashboardAccessState', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('shows setup state for remote access when auth is disabled', () => {
|
||||
it('keeps remote access open when auth is disabled', () => {
|
||||
expect(
|
||||
resolveDashboardAccessState(
|
||||
{ enabled: false, username: '', password_hash: '', session_timeout_hours: 24 },
|
||||
'192.168.2.100'
|
||||
)
|
||||
).toEqual({
|
||||
authRequired: true,
|
||||
authRequired: false,
|
||||
authEnabled: false,
|
||||
authConfigured: false,
|
||||
isLocalAccess: false,
|
||||
accessMode: 'setup',
|
||||
accessMode: 'open',
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
|
||||
import express from 'express';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import type { Server } from 'http';
|
||||
import { usageRoutes } from '../../../src/web-server/usage/routes';
|
||||
|
||||
describe('usage-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/usage', usageRoutes);
|
||||
|
||||
await new Promise<void>((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<void>((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-usage-routes-auth-'));
|
||||
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 usage status requests when dashboard auth is disabled', async () => {
|
||||
const response = await fetch(`${baseUrl}/api/usage/status`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('blocks remote usage refresh when dashboard auth is disabled', async () => {
|
||||
const response = await fetch(`${baseUrl}/api/usage/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(await response.json()).toEqual({
|
||||
error: 'Usage refresh requires localhost access when dashboard auth is disabled.',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,28 +1,69 @@
|
||||
import { Shield, X } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useAuth } from '@/contexts/auth-context';
|
||||
|
||||
export function LocalhostDisclaimer() {
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
const { authEnabled, authConfigured, isLocalAccess, loading } = useAuth();
|
||||
|
||||
if (dismissed) return null;
|
||||
const isRemoteReadonly = !isLocalAccess && !authEnabled;
|
||||
|
||||
if ((dismissed && !isRemoteReadonly) || loading) return null;
|
||||
|
||||
const wrapperClasses = isRemoteReadonly
|
||||
? 'w-full border-t border-amber-200 bg-amber-50 px-4 py-2 text-amber-900 transition-colors duration-200 dark:border-amber-800 dark:bg-amber-900/20 dark:text-amber-200'
|
||||
: 'w-full border-t border-yellow-200 bg-yellow-50 px-4 py-2 text-yellow-800 transition-colors duration-200 dark:border-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-200';
|
||||
const dismissClasses = isRemoteReadonly
|
||||
? 'text-amber-600 hover:bg-amber-100 hover:text-amber-800 dark:text-amber-400 dark:hover:bg-amber-800/30'
|
||||
: 'text-yellow-600 hover:bg-yellow-100 hover:text-yellow-800 dark:text-yellow-400 dark:hover:bg-yellow-800/30';
|
||||
const message = isRemoteReadonly ? (
|
||||
<>
|
||||
{authConfigured ? (
|
||||
<>
|
||||
<span className="hidden sm:inline">
|
||||
Remote dashboard access is read-only because dashboard auth is currently disabled on the
|
||||
host. Re-enable dashboard auth on the host to unlock remote changes.
|
||||
</span>
|
||||
<span className="sm:hidden">
|
||||
Remote dashboard is read-only until dashboard auth is re-enabled on the host.
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="hidden sm:inline">
|
||||
Remote dashboard access is read-only until you run ccs config auth setup on the host.
|
||||
</span>
|
||||
<span className="sm:hidden">
|
||||
Remote dashboard is read-only until host auth is configured.
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="hidden sm:inline">
|
||||
This dashboard runs locally. All data stays on your machine.
|
||||
</span>
|
||||
<span className="sm:hidden">Local dashboard - data stays on your device.</span>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-full bg-yellow-50 dark:bg-yellow-900/20 border-t border-yellow-200 dark:border-yellow-800 px-4 py-2 transition-colors duration-200">
|
||||
<div className={wrapperClasses}>
|
||||
<div className="flex items-center justify-center gap-4">
|
||||
<div className="flex items-center gap-2 text-sm text-yellow-800 dark:text-yellow-200">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Shield className="w-4 h-4 flex-shrink-0" />
|
||||
<span className="hidden sm:inline">
|
||||
This dashboard runs locally. All data stays on your machine.
|
||||
</span>
|
||||
<span className="sm:hidden">Local dashboard - data stays on your device.</span>
|
||||
{message}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setDismissed(true)}
|
||||
className="text-yellow-600 hover:text-yellow-800 dark:text-yellow-400 flex-shrink-0 p-1 rounded hover:bg-yellow-100 dark:hover:bg-yellow-800/30 transition-colors"
|
||||
aria-label="Dismiss disclaimer"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
{!isRemoteReadonly ? (
|
||||
<button
|
||||
onClick={() => setDismissed(true)}
|
||||
className={`flex-shrink-0 rounded p-1 transition-colors ${dismissClasses}`}
|
||||
aria-label="Dismiss disclaimer"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { RequireAuth } from '@/components/auth/require-auth';
|
||||
|
||||
const { useAuthMock } = vi.hoisted(() => ({
|
||||
useAuthMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/contexts/auth-context', () => ({
|
||||
useAuth: useAuthMock,
|
||||
}));
|
||||
|
||||
function renderGuard(initialPath = '/') {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialPath]}>
|
||||
<Routes>
|
||||
<Route path="/login" element={<div>login page</div>} />
|
||||
<Route element={<RequireAuth />}>
|
||||
<Route path="/" element={<div>dashboard page</div>} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
describe('RequireAuth', () => {
|
||||
beforeEach(() => {
|
||||
useAuthMock.mockReset();
|
||||
});
|
||||
|
||||
it('allows remote readonly sessions through without redirecting to login', () => {
|
||||
useAuthMock.mockReturnValue({
|
||||
authRequired: false,
|
||||
isAuthenticated: false,
|
||||
username: null,
|
||||
loading: false,
|
||||
authEnabled: false,
|
||||
authConfigured: false,
|
||||
isLocalAccess: false,
|
||||
accessMode: 'open',
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
});
|
||||
|
||||
renderGuard();
|
||||
|
||||
expect(screen.getByText('dashboard page')).toBeVisible();
|
||||
expect(screen.queryByText('login page')).toBeNull();
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users when dashboard auth is enabled', () => {
|
||||
useAuthMock.mockReturnValue({
|
||||
authRequired: true,
|
||||
isAuthenticated: false,
|
||||
username: null,
|
||||
loading: false,
|
||||
authEnabled: true,
|
||||
authConfigured: true,
|
||||
isLocalAccess: false,
|
||||
accessMode: 'login',
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
});
|
||||
|
||||
renderGuard();
|
||||
|
||||
expect(screen.getByText('login page')).toBeVisible();
|
||||
expect(screen.queryByText('dashboard page')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { LocalhostDisclaimer } from '@/components/shared/localhost-disclaimer';
|
||||
|
||||
const { useAuthMock } = vi.hoisted(() => ({
|
||||
useAuthMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/contexts/auth-context', () => ({
|
||||
useAuth: useAuthMock,
|
||||
}));
|
||||
|
||||
describe('LocalhostDisclaimer', () => {
|
||||
beforeEach(() => {
|
||||
useAuthMock.mockReset();
|
||||
});
|
||||
|
||||
it('shows the local safety copy for loopback sessions', () => {
|
||||
useAuthMock.mockReturnValue({
|
||||
authEnabled: false,
|
||||
authConfigured: false,
|
||||
isLocalAccess: true,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
render(<LocalhostDisclaimer />);
|
||||
|
||||
expect(
|
||||
screen.getByText('This dashboard runs locally. All data stays on your machine.')
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
it('shows the remote read-only copy when auth is disabled for remote access', () => {
|
||||
useAuthMock.mockReturnValue({
|
||||
authEnabled: false,
|
||||
authConfigured: false,
|
||||
isLocalAccess: false,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
render(<LocalhostDisclaimer />);
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Remote dashboard access is read-only until you run ccs config auth setup on the host.'
|
||||
)
|
||||
).toBeVisible();
|
||||
expect(screen.queryByLabelText('Dismiss disclaimer')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows the re-enable message when host credentials already exist', () => {
|
||||
useAuthMock.mockReturnValue({
|
||||
authEnabled: false,
|
||||
authConfigured: true,
|
||||
isLocalAccess: false,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
render(<LocalhostDisclaimer />);
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Remote dashboard access is read-only because dashboard auth is currently disabled on the host. Re-enable dashboard auth on the host to unlock remote changes.'
|
||||
)
|
||||
).toBeVisible();
|
||||
expect(screen.queryByLabelText('Dismiss disclaimer')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import i18n from '@/lib/i18n';
|
||||
import { LoginPage } from '@/pages/login';
|
||||
import { render, screen, userEvent } from '@tests/setup/test-utils';
|
||||
import { render, screen, userEvent, waitFor } from '@tests/setup/test-utils';
|
||||
|
||||
const { navigateMock, useAuthMock } = vi.hoisted(() => ({
|
||||
navigateMock: vi.fn(),
|
||||
@@ -40,13 +40,13 @@ describe('LoginPage', () => {
|
||||
await i18n.changeLanguage('en');
|
||||
});
|
||||
|
||||
it('renders a setup state for remote access when dashboard auth is unavailable', () => {
|
||||
it('redirects away when dashboard auth is disabled for remote access', async () => {
|
||||
useAuthMock.mockReturnValue({
|
||||
authRequired: true,
|
||||
authRequired: false,
|
||||
isAuthenticated: false,
|
||||
username: null,
|
||||
loading: false,
|
||||
accessMode: 'setup',
|
||||
accessMode: 'open',
|
||||
authEnabled: false,
|
||||
authConfigured: false,
|
||||
isLocalAccess: false,
|
||||
@@ -56,11 +56,10 @@ describe('LoginPage', () => {
|
||||
|
||||
render(<LoginPage />);
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Remote access needs host setup' })).toBeVisible();
|
||||
expect(screen.getByText('ccs config auth setup')).toBeVisible();
|
||||
expect(screen.getByText('No default credentials ship with CCS.')).toBeVisible();
|
||||
expect(screen.queryByLabelText('Username')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Sign In' })).not.toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(navigateMock).toHaveBeenCalledWith('/settings', { replace: true });
|
||||
});
|
||||
expect(screen.queryByRole('heading', { name: 'Remote access needs host setup' })).toBeNull();
|
||||
});
|
||||
|
||||
it('renders the incomplete setup copy when auth is enabled without credentials', () => {
|
||||
|
||||
Reference in New Issue
Block a user