Skip to content

Commit

Permalink
[ISSUE#10153] Add auth state into /state api and add announcement api. (
Browse files Browse the repository at this point in the history
#10203)

* Add ModuleState and use ModuleState replace ServerStateController.

* Add AuthModuleStateBuilder

* state接口使用ModuleState.

* Add announcement api.

* skip rat scan for announcement.conf

* default plugin open login page when auth.enabled=true.
  • Loading branch information
KomachiSion authored Mar 27, 2023
1 parent d291f24 commit 5fffde5
Show file tree
Hide file tree
Showing 22 changed files with 647 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.plugin.auth.constant.Constants;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.module.ModuleState;
import com.alibaba.nacos.sys.module.ModuleStateHolder;
import com.alibaba.nacos.sys.utils.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -179,6 +181,11 @@ public void onEvent(ServerConfigChangeEvent event) {
.getProperty(Constants.Auth.NACOS_CORE_AUTH_ENABLE_USER_AGENT_AUTH_WHITE, Boolean.class, false);
nacosAuthSystemType = EnvUtil.getProperty(Constants.Auth.NACOS_CORE_AUTH_SYSTEM_TYPE, "");
refreshPluginProperties();
ModuleStateHolder.getInstance().getModuleState(AuthModuleStateBuilder.AUTH_MODULE)
.ifPresent(moduleState -> {
ModuleState temp = new AuthModuleStateBuilder().build();
moduleState.getStates().putAll(temp.getStates());
});
} catch (Exception e) {
LOGGER.warn("Upgrade auth config from env failed, use old value", e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed 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 com.alibaba.nacos.auth.config;

import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginManager;
import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService;
import com.alibaba.nacos.sys.module.ModuleState;
import com.alibaba.nacos.sys.module.ModuleStateBuilder;
import com.alibaba.nacos.sys.utils.ApplicationUtils;

import java.util.Optional;

/**
* Module state builder for auth module.
*
* @author xiweng.yy
*/
public class AuthModuleStateBuilder implements ModuleStateBuilder {

public static final String AUTH_MODULE = "auth";

public static final String AUTH_ENABLED = "auth_enabled";

public static final String LOGIN_PAGE_ENABLED = "login_page_enabled";

public static final String AUTH_SYSTEM_TYPE = "auth_system_type";

@Override
public ModuleState build() {
ModuleState result = new ModuleState(AUTH_MODULE);
AuthConfigs authConfigs = ApplicationUtils.getBean(AuthConfigs.class);
result.newState(AUTH_ENABLED, authConfigs.isAuthEnabled());
result.newState(LOGIN_PAGE_ENABLED, isLoginPageEnabled(authConfigs));
result.newState(AUTH_SYSTEM_TYPE, authConfigs.getNacosAuthSystemType());
return result;
}

private Boolean isLoginPageEnabled(AuthConfigs authConfigs) {
Optional<AuthPluginService> authPluginService = AuthPluginManager.getInstance()
.findAuthServiceSpiImpl(authConfigs.getNacosAuthSystemType());
return authPluginService.map(AuthPluginService::isLoginEnabled).orElse(false);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#
# Copyright 1999-2023 Alibaba Group Holding Ltd.
#
# Licensed 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.
#

com.alibaba.nacos.auth.config.AuthModuleStateBuilder
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed 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 com.alibaba.nacos.auth.config;

import com.alibaba.nacos.sys.module.ModuleState;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ConfigurableApplicationContext;

import static com.alibaba.nacos.auth.config.AuthModuleStateBuilder.AUTH_ENABLED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class AuthModuleStateBuilderTest {

@Mock
private ConfigurableApplicationContext context;

@Mock
private AuthConfigs authConfigs;

@Before
public void setUp() throws Exception {
when(context.getBean(AuthConfigs.class)).thenReturn(authConfigs);
ApplicationUtils.injectContext(context);
when(authConfigs.getNacosAuthSystemType()).thenReturn("nacos");
}

@After
public void tearDown() throws Exception {
}

@Test
public void testBuild() {
ModuleState actual = new AuthModuleStateBuilder().build();
assertFalse((Boolean) actual.getStates().get(AUTH_ENABLED));
assertFalse((Boolean) actual.getStates().get("login_page_enabled"));
assertEquals("nacos", actual.getStates().get("auth_system_type"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public void setUp() throws Exception {
ramContext.setAccessKey(PropertyKeyConst.ACCESS_KEY);
ramContext.setSecretKey(PropertyKeyConst.SECRET_KEY);
stsCredential = new StsCredential();
StsConfig.getInstance().setRamRoleName(null);
}

@After
Expand Down Expand Up @@ -141,6 +142,7 @@ private void prepareForSts() throws NoSuchFieldException, IllegalAccessException

private void clearForSts() throws NoSuchFieldException, IllegalAccessException {
StsConfig.getInstance().setSecurityCredentialsUrl(null);
StsConfig.getInstance().setSecurityCredentials(null);
Field field = StsCredentialHolder.class.getDeclaredField("stsCredential");
field.setAccessible(true);
field.set(StsCredentialHolder.getInstance(), null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,18 @@

package com.alibaba.nacos.console.controller;

import com.alibaba.nacos.common.utils.VersionUtils;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.model.RestResultUtils;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.module.ModuleState;
import com.alibaba.nacos.sys.module.ModuleStateHolder;
import com.alibaba.nacos.sys.utils.DiskUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -35,6 +40,8 @@
@RequestMapping("/v1/console/server")
public class ServerStateController {

private static final String ANNOUNCEMENT_FILE = "announcement.conf";

/**
* Get server state of current server.
*
Expand All @@ -43,13 +50,19 @@ public class ServerStateController {
@GetMapping("/state")
public ResponseEntity<Map<String, String>> serverState() {
Map<String, String> serverState = new HashMap<>(4);
serverState.put("standalone_mode",
EnvUtil.getStandaloneMode() ? EnvUtil.STANDALONE_MODE_ALONE : EnvUtil.STANDALONE_MODE_CLUSTER);

serverState.put("function_mode", EnvUtil.getFunctionMode());
serverState.put("version", VersionUtils.version);

for (ModuleState each : ModuleStateHolder.getInstance().getAllModuleStates()) {
each.getStates().forEach((s, o) -> serverState.put(s, null == o ? null : o.toString()));
}
return ResponseEntity.ok().body(serverState);
}

@GetMapping("/announcement")
public RestResult<String> getAnnouncement() {
File announcementFile = new File(EnvUtil.getConfPath(), ANNOUNCEMENT_FILE);
String announcement = null;
if (announcementFile.exists() && announcementFile.isFile()) {
announcement = DiskUtils.readFile(announcementFile);
}
return RestResultUtils.success(announcement);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,26 @@

package com.alibaba.nacos.console.controller;

import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.VersionUtils;
import com.alibaba.nacos.sys.env.Constants;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

/**
* ServerStateController unit test.
*
* @ClassName: ServerStateControllerTest
* @Author: ChenHao26
* @Date: 2022/8/13 10:54
Expand All @@ -52,6 +59,12 @@ public void setUp() {
@Test
public void serverState() throws Exception {
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(CONSOLE_URL);
Assert.assertEquals(200, mockmvc.perform(builder).andReturn().getResponse().getStatus());
MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse();
Assert.assertEquals(200, response.getStatus());
ObjectNode responseContent = JacksonUtils.toObj(response.getContentAsByteArray(), ObjectNode.class);
Assert.assertEquals(EnvUtil.STANDALONE_MODE_CLUSTER,
responseContent.get(Constants.STANDALONE_MODE_STATE).asText());
Assert.assertEquals("null", responseContent.get(Constants.FUNCTION_MODE_STATE).asText());
Assert.assertEquals(VersionUtils.version, responseContent.get(Constants.NACOS_VERSION).asText());
}
}
1 change: 1 addition & 0 deletions distribution/conf/announcement.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
当前集群没有开启鉴权,请参考[文档](https://nacos.io/zh-cn/docs/v2/guide/user/auth.html)开启鉴权~
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.alibaba.nacos.plugin.auth.impl;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.auth.config.AuthConfigs;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.plugin.auth.api.IdentityContext;
import com.alibaba.nacos.plugin.auth.api.Permission;
Expand Down Expand Up @@ -107,6 +108,11 @@ public String getAuthServiceName() {
return AuthConstants.AUTH_PLUGIN_TYPE;
}

@Override
public boolean isLoginEnabled() {
return ApplicationUtils.getBean(AuthConfigs.class).isAuthEnabled();
}

protected void checkNacosAuthManager() {
if (null == authenticationManager) {
authenticationManager = ApplicationUtils.getBean(DefaultAuthenticationManager.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,13 @@ public interface AuthPluginService {
*/
String getAuthServiceName();

/**
* Is the plugin enable login.
*
* @return {@code true} if plugin need login, otherwise {@code false}
* @since 2.2.2
*/
default boolean isLoginEnabled() {
return false;
}
}
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@
<exclude>**/any.proto</exclude>
<exclude>src/main/java/com/alibaba/nacos/common/packagescan/classreading/**</exclude>
<exclude>.flattened-pom.xml</exclude>
<exclude>**/announcement.conf</exclude>
</excludes>
</configuration>
<executions>
Expand Down
8 changes: 8 additions & 0 deletions sys/src/main/java/com/alibaba/nacos/sys/env/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
*/
public interface Constants {

String SYS_MODULE = "sys";

/**
* Spring Profile : "standalone".
*/
Expand All @@ -34,11 +36,15 @@ public interface Constants {
*/
String STANDALONE_MODE_PROPERTY_NAME = "nacos.standalone";

String STANDALONE_MODE_STATE = "standalone_mode";

/**
* The System property name of Function mode.
*/
String FUNCTION_MODE_PROPERTY_NAME = "nacos.functionMode";

String FUNCTION_MODE_STATE = "function_mode";

/**
* The System property name of prefer hostname over ip.
*/
Expand All @@ -49,6 +55,8 @@ public interface Constants {
*/
String ROOT_WEB_CONTEXT_PATH = "/";

String NACOS_VERSION = "version";

String NACOS_SERVER_IP = "nacos.server.ip";

String USE_ONLY_SITE_INTERFACES = "nacos.inetutils.use-only-site-local-interfaces";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 1999-2023 Alibaba Group Holding Ltd.
*
* Licensed 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 com.alibaba.nacos.sys.env;

import com.alibaba.nacos.common.utils.VersionUtils;
import com.alibaba.nacos.sys.module.ModuleState;
import com.alibaba.nacos.sys.module.ModuleStateBuilder;

/**
* Module state builder for env module.
*
* @author xiweng.yy
*/
public class EnvModuleStateBuilder implements ModuleStateBuilder {

@Override
public ModuleState build() {
ModuleState result = new ModuleState(Constants.SYS_MODULE);
result.newState(Constants.STANDALONE_MODE_STATE,
EnvUtil.getStandaloneMode() ? EnvUtil.STANDALONE_MODE_ALONE : EnvUtil.STANDALONE_MODE_CLUSTER);
result.newState(Constants.FUNCTION_MODE_STATE, EnvUtil.getFunctionMode());
result.newState(Constants.NACOS_VERSION, VersionUtils.version);
return result;
}
}
Loading

0 comments on commit 5fffde5

Please sign in to comment.