Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@

import org.apache.rocketmq.studio.common.domain.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
Expand All @@ -32,6 +35,19 @@
public class AuthController {

private final AuthService authService;
private final AuthProperties authProperties;

@GetMapping("/status")
public ResponseEntity<Result<AuthStatusVO>> status(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization) {
AuthStatusVO status = AuthStatusVO.builder()
.loginRequired(authProperties.isLoginRequired())
.authenticated(authService.isAuthenticated(authorization))
.build();
return ResponseEntity.ok()
.cacheControl(CacheControl.noStore())
.body(Result.ok(status));
}

@PostMapping("/login")
public Result<LoginVO> login(@RequestBody LoginDTO request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons

private boolean isPublicPath(String path) {
return path.equals("/api/auth/login")
|| path.equals("/api/auth/status")
|| path.startsWith("/api-docs")
|| path.startsWith("/swagger-ui")
|| path.startsWith("/actuator/health");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.rocketmq.studio.auth;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AuthStatusVO {
private boolean loginRequired;
private boolean authenticated;
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

Expand All @@ -46,9 +48,48 @@ class AuthControllerTest {
@MockBean
private AuthService authService;

@MockBean
private AuthProperties authProperties;

@Autowired
private ObjectMapper objectMapper;

@Test
void statusShouldReportDisabledLoginProtection() throws Exception {
when(authProperties.isLoginRequired()).thenReturn(false);
when(authService.isAuthenticated(null)).thenReturn(false);

mockMvc.perform(get("/api/auth/status"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-store"))
.andExpect(jsonPath("$.code").value(200))
.andExpect(jsonPath("$.data.loginRequired").value(false))
.andExpect(jsonPath("$.data.authenticated").value(false));
}

@Test
void statusShouldReportUnauthenticatedWhenTokenIsMissing() throws Exception {
when(authProperties.isLoginRequired()).thenReturn(true);
when(authService.isAuthenticated(null)).thenReturn(false);

mockMvc.perform(get("/api/auth/status"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.loginRequired").value(true))
.andExpect(jsonPath("$.data.authenticated").value(false));
}

@Test
void statusShouldReportAuthenticatedForActiveToken() throws Exception {
when(authProperties.isLoginRequired()).thenReturn(true);
when(authService.isAuthenticated("Bearer token-1")).thenReturn(true);

mockMvc.perform(get("/api/auth/status")
.header(HttpHeaders.AUTHORIZATION, "Bearer token-1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.loginRequired").value(true))
.andExpect(jsonPath("$.data.authenticated").value(true));
}

@Test
void loginShouldReturnTokenOnValidRequest() throws Exception {
LoginVO mockResponse = LoginVO.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,16 @@ void shouldAllowLoginEndpointWhenLoginIsEnabled() throws Exception {

assertThat(allowed).isTrue();
}

@Test
void shouldAllowAuthStatusEndpointWhenLoginIsEnabled() throws Exception {
AuthProperties properties = new AuthProperties();
properties.setLoginRequired(true);
AuthInterceptor interceptor = new AuthInterceptor(properties, new AuthService(properties));
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/auth/status");

boolean allowed = interceptor.preHandle(request, new MockHttpServletResponse(), new Object());

assertThat(allowed).isTrue();
}
}
102 changes: 102 additions & 0 deletions web/src/App.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getAuthStatus } from './api/auth';
import { AuthGate } from './App';
import { LangProvider } from './i18n/LangContext';

vi.mock('./api/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('./api/auth')>();
return { ...actual, getAuthStatus: vi.fn() };
});

vi.mock('./config', () => ({ API_BASE_URL: '/api', USE_MOCK: false }));

const mockedGetAuthStatus = vi.mocked(getAuthStatus);

function renderGate() {
return render(
<LangProvider>
<MemoryRouter initialEntries={['/protected']}>
<Routes>
<Route path="/login" element={<div>login page</div>} />
<Route element={<AuthGate />}>
<Route path="/protected" element={<div>protected content</div>} />
</Route>
</Routes>
</MemoryRouter>
</LangProvider>,
);
}

describe('AuthGate', () => {
beforeEach(() => {
mockedGetAuthStatus.mockReset();
localStorage.setItem('token', 'stale-token');
localStorage.setItem('rocketmq-studio-user', 'admin');
});

afterEach(() => {
cleanup();
localStorage.clear();
});

it('allows protected routes when login protection is disabled', async () => {
mockedGetAuthStatus.mockResolvedValue({ loginRequired: false, authenticated: false });

renderGate();

expect(await screen.findByText('protected content')).toBeInTheDocument();
});

it('allows protected routes for an authenticated session', async () => {
mockedGetAuthStatus.mockResolvedValue({ loginRequired: true, authenticated: true });

renderGate();

expect(await screen.findByText('protected content')).toBeInTheDocument();
});

it('clears an invalid session and redirects to login', async () => {
mockedGetAuthStatus.mockResolvedValue({ loginRequired: true, authenticated: false });

renderGate();

expect(await screen.findByText('login page')).toBeInTheDocument();
expect(localStorage.getItem('token')).toBeNull();
expect(localStorage.getItem('rocketmq-studio-user')).toBeNull();
});

it('fails closed and retries the status check', async () => {
mockedGetAuthStatus
.mockRejectedValueOnce(new Error('network unavailable'))
.mockResolvedValueOnce({ loginRequired: false, authenticated: false });

renderGate();

expect(await screen.findByText('无法验证登录状态')).toBeInTheDocument();
expect(screen.queryByText('protected content')).not.toBeInTheDocument();

fireEvent.click(screen.getByRole('button', { name: /\s*/ }));

await waitFor(() => expect(mockedGetAuthStatus).toHaveBeenCalledTimes(2));
expect(await screen.findByText('protected content')).toBeInTheDocument();
});
});
128 changes: 100 additions & 28 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@
* limitations under the License.
*/

import { Routes, Route, Navigate } from 'react-router-dom';
import { useCallback, useEffect, useState } from 'react';
import { Button, Result, Spin } from 'antd';
import { Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { getAuthStatus } from './api/auth';
import { USE_MOCK } from './config';
import { useLang } from './i18n/LangContext';
import useAuthStore from './stores/authStore';
import MainLayout from './layouts/MainLayout';
import HomePage from './pages/home';
import InstancePage from './pages/instance';
Expand Down Expand Up @@ -44,37 +50,103 @@ import ProducerPage from './pages/studio/Producer';
import OpsPage from './pages/studio/Ops';
import LoginPage from './pages/login';

type AuthGateState = 'checking' | 'allowed' | 'denied' | 'error';

export function AuthGate() {
const { t } = useLang();
const clearAuth = useAuthStore((state) => state.logout);
const [gateState, setGateState] = useState<AuthGateState>(USE_MOCK ? 'allowed' : 'checking');
const [attempt, setAttempt] = useState(0);

useEffect(() => {
if (USE_MOCK) return;

let cancelled = false;
void getAuthStatus()
.then((status) => {
if (cancelled) return;
if (!status.loginRequired || status.authenticated) {
setGateState('allowed');
return;
}
clearAuth();
setGateState('denied');
})
.catch(() => {
if (!cancelled) setGateState('error');
});

return () => {
cancelled = true;
};
}, [attempt, clearAuth]);

const retry = useCallback(() => {
setGateState('checking');
setAttempt((current) => current + 1);
}, []);

if (gateState === 'checking') {
return (
<div
role="status"
aria-label={t('common.loading')}
style={{ minHeight: '100vh', display: 'grid', placeItems: 'center' }}
>
<Spin size="large" />
</div>
);
}
if (gateState === 'denied') return <Navigate to="/login" replace />;
if (gateState === 'error') {
return (
<Result
status="error"
title={t('login.statusCheckFailed')}
extra={
<Button type="primary" onClick={retry}>
{t('common.retry')}
</Button>
}
/>
);
}
return <Outlet />;
}

function App() {
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/" element={<MainLayout />}>
<Route index element={<HomePage />} />
<Route path="instance" element={<InstancePage />} />
<Route path="instance/topic" element={<TopicPage />} />
<Route path="instance/consumer" element={<ConsumerPage />} />
<Route path="instance/message" element={<MessagePage />} />
<Route path="instance/acl" element={<AclPage />} />
<Route path="instance/dlq" element={<DlqPage />} />
<Route path="cluster" element={<ClusterPage />} />
<Route path="cluster/certs" element={<K8sCertsPage />} />
<Route path="cluster/clients" element={<ClientsPage />} />
<Route path="ops/dashboard" element={<DashboardOpsPage />} />
<Route path="ops/alerts" element={<AlertsPage />} />
<Route path="ops/system-alerts" element={<SystemAlertsPage />} />
<Route path="ops/audit" element={<AuditPage />} />
<Route path="ai" element={<AiPage />} />
<Route path="settings" element={<SettingsPage />} />
<Route path="studio/llm-settings" element={<LlmSettingsPage />} />
<Route path="studio/proxy" element={<ProxyPage />} />
<Route path="studio/lite-topic" element={<LiteTopicPage />} />
<Route path="studio/group-management" element={<GroupManagementPage />} />
<Route path="studio/broker-cluster" element={<BrokerClusterPage />} />
<Route path="studio/ssl-settings" element={<SslSettingsPage />} />
<Route path="studio/alert-management" element={<AlertManagementPage />} />
<Route path="studio/producer" element={<ProducerPage />} />
<Route path="studio/ops" element={<OpsPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
<Route element={<AuthGate />}>
<Route path="/" element={<MainLayout />}>
<Route index element={<HomePage />} />
<Route path="instance" element={<InstancePage />} />
<Route path="instance/topic" element={<TopicPage />} />
<Route path="instance/consumer" element={<ConsumerPage />} />
<Route path="instance/message" element={<MessagePage />} />
<Route path="instance/acl" element={<AclPage />} />
<Route path="instance/dlq" element={<DlqPage />} />
<Route path="cluster" element={<ClusterPage />} />
<Route path="cluster/certs" element={<K8sCertsPage />} />
<Route path="cluster/clients" element={<ClientsPage />} />
<Route path="ops/dashboard" element={<DashboardOpsPage />} />
<Route path="ops/alerts" element={<AlertsPage />} />
<Route path="ops/system-alerts" element={<SystemAlertsPage />} />
<Route path="ops/audit" element={<AuditPage />} />
<Route path="ai" element={<AiPage />} />
<Route path="settings" element={<SettingsPage />} />
<Route path="studio/llm-settings" element={<LlmSettingsPage />} />
<Route path="studio/proxy" element={<ProxyPage />} />
<Route path="studio/lite-topic" element={<LiteTopicPage />} />
<Route path="studio/group-management" element={<GroupManagementPage />} />
<Route path="studio/broker-cluster" element={<BrokerClusterPage />} />
<Route path="studio/ssl-settings" element={<SslSettingsPage />} />
<Route path="studio/alert-management" element={<AlertManagementPage />} />
<Route path="studio/producer" element={<ProducerPage />} />
<Route path="studio/ops" element={<OpsPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Route>
</Routes>
);
Expand Down
Loading
Loading