[ISSUE #11343] Simplified validation logic (#11345)

* 优化节点显示,添加mode

* Simplified validation logic

* add license

* fix unit test

* add config,console,naming unit test and rename annotation

* add config,console,naming unit test and rename annotation

* fix EnvUtils test

* fix EnvUtils test

* fix ParamExtractorFilterTest

* fix ParamExtractorFilterTest

* fix ParamExtractorFilterTest

* fix ParamExtractorFilterTest

* fix ParamExtractorFilterTest
This commit is contained in:
zhanghong 2023-11-15 15:25:00 +08:00 committed by GitHub
parent e77a0bbe0d
commit a935fa1092
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
90 changed files with 842 additions and 1459 deletions

View File

@ -17,7 +17,6 @@
package com.alibaba.nacos.config.server.configuration;
import com.alibaba.nacos.config.server.filter.CircuitFilter;
import com.alibaba.nacos.config.server.filter.ConfigParamCheckFilter;
import com.alibaba.nacos.config.server.filter.NacosWebFilter;
import com.alibaba.nacos.persistence.configuration.condition.ConditionDistributedEmbedStorage;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
@ -66,19 +65,4 @@ public class NacosConfigConfiguration {
return new CircuitFilter();
}
@Bean
public FilterRegistrationBean<ConfigParamCheckFilter> configParamCheckFilterRegistration() {
FilterRegistrationBean<ConfigParamCheckFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(configParamCheckFilter());
registration.addUrlPatterns("/v1/cs/*");
registration.addUrlPatterns("/v2/cs/*");
registration.setName("configparamcheckfilter");
registration.setOrder(8);
return registration;
}
@Bean
public ConfigParamCheckFilter configParamCheckFilter() {
return new ConfigParamCheckFilter();
}
}

View File

@ -19,8 +19,10 @@ package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.capacity.Capacity;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.config.server.service.capacity.CapacityService;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
@ -38,6 +40,7 @@ import javax.servlet.http.HttpServletResponse;
*/
@RestController
@RequestMapping(Constants.CAPACITY_CONTROLLER_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class CapacityController {
private static final Logger LOGGER = LoggerFactory.getLogger(CapacityController.class);

View File

@ -28,9 +28,11 @@ import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.remote.Connection;
import com.alibaba.nacos.core.remote.ConnectionManager;
import com.alibaba.nacos.core.utils.GenericType;
@ -61,6 +63,7 @@ import static com.alibaba.nacos.api.config.remote.request.ClientConfigMetricRequ
*/
@RestController
@RequestMapping(Constants.METRICS_CONTROLLER_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class ClientMetricsController {
private final ServerMemberManager serverMemberManager;

View File

@ -20,9 +20,11 @@ import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.SampleResult;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.config.server.remote.ConfigChangeListenContext;
import com.alibaba.nacos.config.server.service.LongPollingService;
import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.remote.Connection;
import com.alibaba.nacos.core.remote.ConnectionManager;
import org.springframework.ui.ModelMap;
@ -46,6 +48,7 @@ import java.util.Set;
*/
@RestController
@RequestMapping(Constants.COMMUNICATION_CONTROLLER_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class CommunicationController {
private final LongPollingService longPollingService;

View File

@ -33,6 +33,10 @@ import com.alibaba.nacos.config.server.model.ConfigInfo;
import com.alibaba.nacos.config.server.model.ConfigInfo4Beta;
import com.alibaba.nacos.config.server.model.ConfigMetadata;
import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus;
import com.alibaba.nacos.config.server.paramcheck.ConfigBlurSearchHttpParamExtractor;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.config.server.paramcheck.ConfigListenerHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.config.server.model.SameConfigPolicy;
import com.alibaba.nacos.config.server.model.SampleResult;
@ -100,6 +104,7 @@ import static com.alibaba.nacos.config.server.utils.RequestUtil.getRemoteIp;
*/
@RestController
@RequestMapping(Constants.CONFIG_CONTROLLER_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class ConfigController {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigController.class);
@ -332,6 +337,7 @@ public class ConfigController {
*/
@PostMapping("/listener")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
@ExtractorManager.Extractor(httpExtractor = ConfigListenerHttpParamExtractor.class)
public void listener(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
@ -378,6 +384,7 @@ public class ConfigController {
*/
@GetMapping(params = "search=accurate")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
@ExtractorManager.Extractor(httpExtractor = ConfigBlurSearchHttpParamExtractor.class)
public Page<ConfigInfo> searchConfig(@RequestParam("dataId") String dataId, @RequestParam("group") String group,
@RequestParam(value = "appName", required = false) String appName,
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant,
@ -406,6 +413,7 @@ public class ConfigController {
*/
@GetMapping(params = "search=blur")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
@ExtractorManager.Extractor(httpExtractor = ConfigBlurSearchHttpParamExtractor.class)
public Page<ConfigInfo> fuzzySearchConfig(@RequestParam("dataId") String dataId,
@RequestParam("group") String group, @RequestParam(value = "appName", required = false) String appName,
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant,

View File

@ -17,6 +17,8 @@
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.common.model.RestResult;
@ -57,6 +59,7 @@ import java.util.Objects;
*/
@RestController
@RequestMapping(Constants.OPS_CONTROLLER_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class ConfigOpsController {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigOpsController.class);

View File

@ -17,6 +17,8 @@
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.persistence.datasource.DataSourceService;
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
@ -35,6 +37,7 @@ import java.util.Map;
*/
@RestController
@RequestMapping(Constants.HEALTH_CONTROLLER_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class HealthController {
private DataSourceService dataSourceService;

View File

@ -22,6 +22,8 @@ import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.ConfigHistoryInfo;
import com.alibaba.nacos.config.server.model.ConfigInfoWrapper;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.config.server.service.HistoryService;
import com.alibaba.nacos.config.server.utils.ParamUtils;
@ -43,6 +45,7 @@ import java.util.List;
*/
@RestController
@RequestMapping(Constants.HISTORY_CONTROLLER_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class HistoryController {
private final HistoryService historyService;

View File

@ -21,8 +21,10 @@ import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus;
import com.alibaba.nacos.config.server.model.SampleResult;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.config.server.service.ConfigSubService;
import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.plugin.auth.constant.SignType;
import org.springframework.ui.ModelMap;
@ -41,6 +43,7 @@ import java.util.Map;
*/
@RestController
@RequestMapping(Constants.LISTENER_CONTROLLER_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class ListenerController {
private final ConfigSubService configSubService;

View File

@ -29,6 +29,9 @@ import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.controller.ConfigServletInner;
import com.alibaba.nacos.config.server.model.ConfigInfo;
import com.alibaba.nacos.config.server.model.ConfigRequestInfo;
import com.alibaba.nacos.config.server.paramcheck.ConfigBlurSearchHttpParamExtractor;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.config.server.model.form.ConfigForm;
import com.alibaba.nacos.config.server.service.ConfigDetailService;
@ -64,6 +67,7 @@ import java.util.Map;
@NacosApi
@RestController
@RequestMapping(Constants.CONFIG_CONTROLLER_V2_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class ConfigControllerV2 {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigControllerV2.class);
@ -171,6 +175,7 @@ public class ConfigControllerV2 {
*/
@GetMapping("/searchDetail")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
@ExtractorManager.Extractor(httpExtractor = ConfigBlurSearchHttpParamExtractor.class)
public Page<ConfigInfo> searchConfigByDetails(@RequestParam("dataId") String dataId, @RequestParam("group") String group,
@RequestParam(value = "appName", required = false) String appName,
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant,

View File

@ -26,6 +26,8 @@ import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.ConfigHistoryInfo;
import com.alibaba.nacos.config.server.model.ConfigInfoWrapper;
import com.alibaba.nacos.config.server.paramcheck.ConfigDefaultHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.config.server.service.HistoryService;
import com.alibaba.nacos.config.server.utils.ParamUtils;
@ -51,6 +53,7 @@ import java.util.List;
@NacosApi
@RestController
@RequestMapping(Constants.HISTORY_CONTROLLER_V2_PATH)
@ExtractorManager.Extractor(httpExtractor = ConfigDefaultHttpParamExtractor.class)
public class HistoryControllerV2 {
private final HistoryService historyService;

View File

@ -17,9 +17,7 @@
package com.alibaba.nacos.config.server.paramcheck;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import javax.servlet.http.HttpServletRequest;
@ -36,13 +34,7 @@ public class ConfigBlurSearchHttpParamExtractor extends AbstractHttpParamExtract
private static final String BLUR_SEARCH_MODE = "blur";
@Override
public void init() {
addTargetRequest(Constants.CONFIG_CONTROLLER_PATH, HttpMethod.GET);
addTargetRequest(Constants.CONFIG_CONTROLLER_PATH + "/", HttpMethod.GET);
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) throws Exception {
public List<ParamInfo> extractParam(HttpServletRequest request) {
String searchMode = request.getParameter("search");
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
if (StringUtils.equals(searchMode, BLUR_SEARCH_MODE)) {

View File

@ -31,11 +31,6 @@ import java.util.List;
*/
public class ConfigDefaultHttpParamExtractor extends AbstractHttpParamExtractor {
@Override
public void init() {
addDefaultTargetRequest("config");
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) {
ParamInfo paramInfo = new ParamInfo();

View File

@ -16,13 +16,15 @@
package com.alibaba.nacos.config.server.paramcheck;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.core.exception.ErrorCode;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
@ -39,18 +41,17 @@ public class ConfigListenerHttpParamExtractor extends AbstractHttpParamExtractor
static final char LINE_SEPARATOR_CHAR = (char) 1;
@Override
public void init() {
addTargetRequest(Constants.CONFIG_CONTROLLER_PATH + "/listener", HttpMethod.POST);
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) throws Exception {
public List<ParamInfo> extractParam(HttpServletRequest request) throws NacosRuntimeException {
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
String listenConfigs = request.getParameter("Listening-Configs");
if (StringUtils.isBlank(listenConfigs)) {
return paramInfos;
}
listenConfigs = URLDecoder.decode(listenConfigs, Constants.ENCODE);
try {
listenConfigs = URLDecoder.decode(listenConfigs, Constants.ENCODE);
} catch (UnsupportedEncodingException e) {
throw new NacosRuntimeException(ErrorCode.UnKnowError.getCode(), e);
}
if (StringUtils.isBlank(listenConfigs)) {
return paramInfos;
}

View File

@ -24,6 +24,8 @@ import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.config.server.service.ConfigCacheService;
import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.ConfigBatchListenRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.utils.StringPool;
@ -48,6 +50,7 @@ public class ConfigChangeBatchListenRequestHandler
@Override
@TpsControl(pointName = "ConfigListen")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
@ExtractorManager.Extractor(rpcExtractor = ConfigBatchListenRequestParamExtractor.class)
public ConfigChangeBatchListenResponse handle(ConfigBatchListenRequest configChangeListenRequest, RequestMeta meta)
throws NacosException {
String connectionId = StringPool.get(meta.getConnectionId());

View File

@ -22,6 +22,8 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.service.dump.DumpService;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.ConfigRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.core.control.TpsControl;
import org.springframework.stereotype.Component;
@ -44,6 +46,7 @@ public class ConfigChangeClusterSyncRequestHandler
@TpsControl(pointName = "ClusterConfigChangeNotify")
@Override
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public ConfigChangeClusterSyncResponse handle(ConfigChangeClusterSyncRequest configChangeSyncRequest,
RequestMeta meta) throws NacosException {

View File

@ -36,6 +36,8 @@ import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
import com.alibaba.nacos.config.server.utils.ParamUtils;
import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.ConfigRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.core.utils.Loggers;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
@ -72,6 +74,7 @@ public class ConfigPublishRequestHandler extends RequestHandler<ConfigPublishReq
@Override
@TpsControl(pointName = "ConfigPublish")
@Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG)
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public ConfigPublishResponse handle(ConfigPublishRequest request, RequestMeta meta) throws NacosException {
try {

View File

@ -38,6 +38,8 @@ import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.ConfigRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.plugin.auth.constant.SignType;
@ -78,6 +80,7 @@ public class ConfigQueryRequestHandler extends RequestHandler<ConfigQueryRequest
@Override
@TpsControl(pointName = "ConfigQuery")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public ConfigQueryResponse handle(ConfigQueryRequest request, RequestMeta meta) throws NacosException {
try {

View File

@ -29,6 +29,8 @@ import com.alibaba.nacos.config.server.service.repository.ConfigInfoTagPersistSe
import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
import com.alibaba.nacos.config.server.utils.ParamUtils;
import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.ConfigRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.utils.Loggers;
@ -60,6 +62,7 @@ public class ConfigRemoveRequestHandler extends RequestHandler<ConfigRemoveReque
@Override
@TpsControl(pointName = "ConfigRemove")
@Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG)
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public ConfigRemoveResponse handle(ConfigRemoveRequest configRemoveRequest, RequestMeta meta)
throws NacosException {
// check tenant

View File

@ -1,46 +0,0 @@
/*
* 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.config.server.paramcheck;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.Assert.assertEquals;
/**
* The type Config default http param extractor test.
*
* @author zhuoguang
*/
public class ConfigDefaultHttpParamExtractorTest {
/**
* Extract param and check.
*/
@Test
public void extractParamAndCheck() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/nacos/v1/cs/testst");
request.setMethod(HttpMethod.PUT);
HttpParamExtractorManager manager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor extractor = manager.getExtractor(request.getRequestURI(), request.getMethod(), "config");
assertEquals(ConfigDefaultHttpParamExtractor.class.getSimpleName(), extractor.getClass().getSimpleName());
}
}

View File

@ -1,44 +0,0 @@
/*
* 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.config.server.paramcheck;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.Assert.assertEquals;
/**
* The type Config listener http param extractor test.
*
* @author zhuoguang
*/
public class ConfigListenerHttpParamExtractorTest {
@Test
public void extractParamAndCheck() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/nacos" + Constants.CONFIG_CONTROLLER_PATH + "/listener");
request.setMethod(HttpMethod.POST);
HttpParamExtractorManager manager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor extractor = manager.getExtractor(request.getRequestURI(), request.getMethod(), "config");
assertEquals(ConfigListenerHttpParamExtractor.class.getSimpleName(), extractor.getClass().getSimpleName());
}
}

View File

@ -0,0 +1,143 @@
/*
* 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.config.server.paramcheck;
import com.alibaba.nacos.config.server.controller.ConfigController;
import com.alibaba.nacos.core.code.ControllerMethodsCache;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.ParamCheckerFilter;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.internal.verification.Times;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
/**
* Param Config ExtractorTest.
*
* @author 985492783@qq.com
* @date 2023/11/9 16:04
*/
@RunWith(MockitoJUnitRunner.class)
public class ParamExtractorTest {
@Mock
private ControllerMethodsCache methodsCache;
private ParamCheckerFilter filter;
@Test
public void testBlurFilter() throws Exception {
MockedStatic<EnvUtil> mockedStatic = Mockito.mockStatic(EnvUtil.class);
final Method check = ConfigController.class.getMethod("fuzzySearchConfig", String.class, String.class, String.class,
String.class, String.class, int.class, int.class);
ExtractorManager.Extractor annotation = check.getAnnotation(ExtractorManager.Extractor.class);
AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation));
MockedStatic<ExtractorManager> managerMockedStatic = Mockito.mockStatic(ExtractorManager.class);
mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any()))
.thenAnswer((k) -> k.getArgument(2));
filter = new ParamCheckerFilter(methodsCache);
managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(annotation)).thenReturn(httpExtractor);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.addParameter("dataId", "testDataId*");
Mockito.when(methodsCache.getMethod(request)).thenReturn(check);
filter.doFilter(request, response, (servletRequest, servletResponse) -> {
});
assertEquals(response.getStatus(), 400);
response = new MockHttpServletResponse();
request.addParameter("search", "blur");
filter.doFilter(request, response, (servletRequest, servletResponse) -> {
});
assertEquals(response.getStatus(), 200);
assertEquals(httpExtractor.getClass(), ConfigBlurSearchHttpParamExtractor.class);
Mockito.verify(httpExtractor, new Times(2)).extractParam(Mockito.any());
managerMockedStatic.close();
mockedStatic.close();
}
@Test
public void testListenerFilter() throws Exception {
MockedStatic<EnvUtil> mockedStatic = Mockito.mockStatic(EnvUtil.class);
final Method check = ConfigController.class.getMethod("listener", HttpServletRequest.class,
HttpServletResponse.class);
ExtractorManager.Extractor annotation = check.getAnnotation(ExtractorManager.Extractor.class);
AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation));
MockedStatic<ExtractorManager> managerMockedStatic = Mockito.mockStatic(ExtractorManager.class);
mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any()))
.thenAnswer((k) -> k.getArgument(2));
filter = new ParamCheckerFilter(methodsCache);
managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(annotation)).thenReturn(httpExtractor);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Mockito.when(methodsCache.getMethod(request)).thenReturn(check);
filter.doFilter(request, response, (servletRequest, servletResponse) -> {
});
assertEquals(httpExtractor.getClass(), ConfigListenerHttpParamExtractor.class);
Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any());
managerMockedStatic.close();
mockedStatic.close();
}
@Test
public void testDefaultFilter() throws Exception {
MockedStatic<EnvUtil> mockedStatic = Mockito.mockStatic(EnvUtil.class);
final Method check = ConfigController.class.getMethod("getConfigAdvanceInfo", String.class, String.class,
String.class);
ExtractorManager.Extractor annotation = ConfigController.class.getAnnotation(ExtractorManager.Extractor.class);
AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation));
MockedStatic<ExtractorManager> managerMockedStatic = Mockito.mockStatic(ExtractorManager.class);
mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any()))
.thenAnswer((k) -> k.getArgument(2));
filter = new ParamCheckerFilter(methodsCache);
managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(annotation)).thenReturn(httpExtractor);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Mockito.when(methodsCache.getMethod(request)).thenReturn(check);
filter.doFilter(request, response, (servletRequest, servletResponse) -> {
});
assertEquals(httpExtractor.getClass(), ConfigDefaultHttpParamExtractor.class);
Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any());
managerMockedStatic.close();
mockedStatic.close();
}
}

View File

@ -16,8 +16,10 @@
package com.alibaba.nacos.console.controller;
import com.alibaba.nacos.console.paramcheck.ConsoleDefaultHttpParamExtractor;
import com.alibaba.nacos.core.cluster.health.ModuleHealthCheckerHolder;
import com.alibaba.nacos.core.cluster.health.ReadinessResult;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@ -33,6 +35,7 @@ import javax.servlet.http.HttpServletRequest;
*/
@RestController("consoleHealth")
@RequestMapping("/v1/console/health")
@ExtractorManager.Extractor(httpExtractor = ConsoleDefaultHttpParamExtractor.class)
public class HealthController {
/**

View File

@ -21,8 +21,10 @@ import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.model.RestResultUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.console.paramcheck.ConsoleDefaultHttpParamExtractor;
import com.alibaba.nacos.core.namespace.repository.NamespacePersistService;
import com.alibaba.nacos.core.namespace.model.Namespace;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.service.NamespaceOperationService;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants;
@ -46,6 +48,7 @@ import java.util.regex.Pattern;
*/
@RestController
@RequestMapping("/v1/console/namespaces")
@ExtractorManager.Extractor(httpExtractor = ConsoleDefaultHttpParamExtractor.class)
public class NamespaceController {
@Autowired

View File

@ -18,6 +18,8 @@ package com.alibaba.nacos.console.controller;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.model.RestResultUtils;
import com.alibaba.nacos.console.paramcheck.ConsoleDefaultHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.module.ModuleState;
import com.alibaba.nacos.sys.module.ModuleStateHolder;
@ -38,6 +40,7 @@ import java.util.Map;
*/
@RestController
@RequestMapping("/v1/console/server")
@ExtractorManager.Extractor(httpExtractor = ConsoleDefaultHttpParamExtractor.class)
public class ServerStateController {
private static final String ANNOUNCEMENT_FILE = "announcement.conf";

View File

@ -17,8 +17,10 @@
package com.alibaba.nacos.console.controller.v2;
import com.alibaba.nacos.api.model.v2.Result;
import com.alibaba.nacos.console.paramcheck.ConsoleDefaultHttpParamExtractor;
import com.alibaba.nacos.core.cluster.health.ModuleHealthCheckerHolder;
import com.alibaba.nacos.core.cluster.health.ReadinessResult;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@ -32,6 +34,7 @@ import javax.servlet.http.HttpServletRequest;
*/
@RestController("consoleHealthV2")
@RequestMapping("/v2/console/health")
@ExtractorManager.Extractor(httpExtractor = ConsoleDefaultHttpParamExtractor.class)
public class HealthControllerV2 {
/**

View File

@ -23,9 +23,11 @@ import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.model.v2.Result;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.console.paramcheck.ConsoleDefaultHttpParamExtractor;
import com.alibaba.nacos.core.namespace.model.Namespace;
import com.alibaba.nacos.core.namespace.model.form.NamespaceForm;
import com.alibaba.nacos.core.namespace.repository.NamespacePersistService;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.service.NamespaceOperationService;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.plugin.auth.constant.SignType;
@ -52,6 +54,7 @@ import java.util.regex.Pattern;
@NacosApi
@RestController
@RequestMapping("/v2/console/namespace")
@ExtractorManager.Extractor(httpExtractor = ConsoleDefaultHttpParamExtractor.class)
public class NamespaceControllerV2 {
private final NamespaceOperationService namespaceOperationService;

View File

@ -1,94 +0,0 @@
/*
* 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.console.filter;
import com.alibaba.nacos.common.paramcheck.AbstractParamChecker;
import com.alibaba.nacos.common.paramcheck.ParamCheckResponse;
import com.alibaba.nacos.common.paramcheck.ParamCheckerManager;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import com.alibaba.nacos.core.paramcheck.ServerParamCheckConfig;
import com.alibaba.nacos.plugin.control.Loggers;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* console param check filter.
*
* @author zhuoguang
*/
public class ConsoleParamCheckFilter implements Filter {
private static final String MODULE = "console";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean paramCheckEnabled = ServerParamCheckConfig.getInstance().isParamCheckEnabled();
if (!paramCheckEnabled) {
chain.doFilter(request, response);
return;
}
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
try {
String uri = req.getRequestURI();
String method = req.getMethod();
HttpParamExtractorManager extractorManager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor paramExtractor = extractorManager.getExtractor(uri, method, MODULE);
List<ParamInfo> paramInfoList = paramExtractor.extractParam(req);
ParamCheckerManager paramCheckerManager = ParamCheckerManager.getInstance();
AbstractParamChecker paramChecker = paramCheckerManager.getParamChecker(ServerParamCheckConfig.getInstance().getActiveParamChecker());
ParamCheckResponse paramCheckResponse = paramChecker.checkParamInfoList(paramInfoList);
if (paramCheckResponse.isSuccess()) {
chain.doFilter(request, resp);
} else {
Loggers.CONTROL.info("Param check invalid,{},url:{}", paramCheckResponse.getMessage(), uri);
generate400Response(resp, paramCheckResponse.getMessage());
}
} catch (Exception e) {
generate400Response(resp, e.getMessage());
}
}
/**
* Generate 400 response.
*
* @param response the response
* @param message the message
*/
public void generate400Response(HttpServletResponse response, String message) {
try {
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache,no-store");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getOutputStream().println(message);
} catch (Exception ex) {
Loggers.CONTROL.error("Error to generate tps 400 response", ex);
}
}
}

View File

@ -32,12 +32,7 @@ import java.util.List;
public class ConsoleDefaultHttpParamExtractor extends AbstractHttpParamExtractor {
@Override
public void init() {
addDefaultTargetRequest("console");
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) throws Exception {
public List<ParamInfo> extractParam(HttpServletRequest request) {
ParamInfo paramInfo = new ParamInfo();
paramInfo.setNamespaceId(getAliasNamespaceId(request));
paramInfo.setNamespaceShowName(getAliasNamespaceShowName(request));

View File

@ -1,43 +0,0 @@
/*
* 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.console.paramcheck;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.Assert.assertEquals;
/**
* The type Console default http param extractor test.
*
* @author zhuoguang
*/
public class ConsoleDefaultHttpParamExtractorTest {
@Test
public void extractParamAndCheck() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod(HttpMethod.POST);
request.setRequestURI("/nacos/v2/console/namespace");
HttpParamExtractorManager manager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor extractor = manager.getExtractor(request.getRequestURI(), request.getMethod(), "console");
assertEquals(ConsoleDefaultHttpParamExtractor.class.getSimpleName(), extractor.getClass().getSimpleName());
}
}

View File

@ -0,0 +1,80 @@
/*
* 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.console.paramcheck;
import com.alibaba.nacos.console.controller.NamespaceController;
import com.alibaba.nacos.core.code.ControllerMethodsCache;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.ParamCheckerFilter;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.internal.verification.Times;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
/**
* Param Console ExtractorTest.
*
* @author 985492783@qq.com
* @date 2023/11/9 17:07
*/
@RunWith(MockitoJUnitRunner.class)
public class ParamExtractorTest {
@Mock
private ControllerMethodsCache methodsCache;
private ParamCheckerFilter filter;
@Test
public void testDefaultFilter() throws Exception {
MockedStatic<EnvUtil> mockedStatic = Mockito.mockStatic(EnvUtil.class);
final Method check = NamespaceController.class.getMethod("getNamespaces");
ExtractorManager.Extractor annotation = NamespaceController.class.getAnnotation(
ExtractorManager.Extractor.class);
AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation));
MockedStatic<ExtractorManager> managerMockedStatic = Mockito.mockStatic(ExtractorManager.class);
mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any()))
.thenAnswer((k) -> k.getArgument(2));
filter = new ParamCheckerFilter(methodsCache);
managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(annotation)).thenReturn(httpExtractor);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Mockito.when(methodsCache.getMethod(request)).thenReturn(check);
filter.doFilter(request, response, (servletRequest, servletResponse) -> {
});
assertEquals(httpExtractor.getClass(), ConsoleDefaultHttpParamExtractor.class);
Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any());
managerMockedStatic.close();
mockedStatic.close();
}
}

View File

@ -16,10 +16,10 @@
package com.alibaba.nacos.core.paramcheck;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
@ -27,59 +27,16 @@ import java.util.List;
*
* @author zhuoguang
*/
public abstract class AbstractHttpParamExtractor implements ParamExtractor<HttpServletRequest> {
private static final String SPLITTER = "@@";
private static final String NACOS_SERVER_CONTEXT = "/nacos";
private final List<String> targetRequestList;
/**
* Instantiates a new Abstract http param extractor.
*/
public AbstractHttpParamExtractor() {
targetRequestList = new ArrayList<>();
init();
}
/**
* Init,add target request to the target request list.
*/
public abstract void init();
@Override
public List<String> getTargetRequestList() {
return targetRequestList;
}
public abstract class AbstractHttpParamExtractor implements ParamExtractor<HttpServletRequest, ParamInfo> {
/**
* Extract param.
*
* @param request the request
* @return the list
* @throws Exception the exception
* @throws NacosException the exception
*/
@Override
public abstract List<ParamInfo> extractParam(HttpServletRequest request) throws Exception;
public abstract List<ParamInfo> extractParam(HttpServletRequest request) throws NacosException;
/**
* Add target request.
*
* @param uri the uri
* @param method the method
*/
public void addTargetRequest(String uri, String method) {
targetRequestList.add(NACOS_SERVER_CONTEXT + uri + SPLITTER + method);
targetRequestList.add(uri + SPLITTER + method);
}
/**
* Add default target request.
*
* @param module the module
*/
public void addDefaultTargetRequest(String module) {
targetRequestList.add("default" + SPLITTER + module);
}
}

View File

@ -16,10 +16,10 @@
package com.alibaba.nacos.core.paramcheck;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import java.util.ArrayList;
import java.util.List;
/**
@ -27,36 +27,16 @@ import java.util.List;
*
* @author zhuoguang
*/
public abstract class AbstractRpcParamExtractor implements ParamExtractor<Request> {
public abstract class AbstractRpcParamExtractor implements ParamExtractor<Request, ParamInfo> {
private final List<String> targetrequestlist;
public AbstractRpcParamExtractor() {
targetrequestlist = new ArrayList<>();
init();
}
/**
* Init, add target request to the target request list.
*/
public abstract void init();
@Override
public List<String> getTargetRequestList() {
return targetrequestlist;
}
/**
* Extract param.
*
* @param request the request
* @return the list
* @throws Exception the exception
* @throws NacosException the exception
*/
@Override
public abstract List<ParamInfo> extractParam(Request request) throws Exception;
public void addTargetRequest(String type) {
targetrequestlist.add(type);
}
public abstract List<ParamInfo> extractParam(Request request) throws NacosException;
}

View File

@ -14,34 +14,34 @@
* limitations under the License.
*/
package com.alibaba.nacos.console.config;
package com.alibaba.nacos.core.paramcheck;
import com.alibaba.nacos.console.filter.ConsoleParamCheckFilter;
import com.alibaba.nacos.core.code.ControllerMethodsCache;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Console filter config.
* ParamCheckerFilter registration.
*
* @author zhuoguang
* @author 985492783@qq.com
* @date 2023/11/7 17:52
*/
@Configuration
public class ConsoleFilterConfig {
public class CheckConfiguration {
@Bean
public FilterRegistrationBean<ConsoleParamCheckFilter> consoleParamCheckFilterRegistration() {
FilterRegistrationBean<ConsoleParamCheckFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(consoleParamCheckFilter());
registration.addUrlPatterns("/v1/console/*");
registration.addUrlPatterns("/v2/console/*");
registration.setName("consoleparamcheckfilter");
public FilterRegistrationBean<ParamCheckerFilter> checkerFilterRegistration(ParamCheckerFilter checkerFilter) {
FilterRegistrationBean<ParamCheckerFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(checkerFilter);
registration.addUrlPatterns("/*");
registration.setName("checkerFilter");
registration.setOrder(8);
return registration;
}
@Bean
public ConsoleParamCheckFilter consoleParamCheckFilter() {
return new ConsoleParamCheckFilter();
public ParamCheckerFilter checkerFilter(ControllerMethodsCache methodsCache) {
return new ParamCheckerFilter(methodsCache);
}
}

View File

@ -0,0 +1,104 @@
/*
* 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.core.paramcheck;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.common.spi.NacosServiceLoader;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* param checker to manager Extractor.
*
* @author 985492783@qq.com
* @date 2023/11/7 16:29
*/
public class ExtractorManager {
/**
* ParamChecker will first look for the Checker annotation in the handler method, and if that annotation is null, it
* will try to find the Checker annotation on the class where the handler method is located, and then load in the
* target ParamExtractor in the Checker annotation.
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Extractor {
/**
* Configure a Class to locate a specific Extractor, which takes effect only on the @Controller annotated class
* or method.
*
* @return Class<? extends AbstractHttpParamExtractor>
*/
Class<? extends AbstractHttpParamExtractor> httpExtractor() default DefaultHttpExtractor.class;
/**
* Configure a Class to locate a specific Extractor, which takes effect only on grpcHandler.
*
* @return Class<? extends AbstractRpcParamExtractor>
*/
Class<? extends AbstractRpcParamExtractor> rpcExtractor() default DefaultGrpcExtractor.class;
}
public static class DefaultHttpExtractor extends AbstractHttpParamExtractor {
@Override
public List<ParamInfo> extractParam(HttpServletRequest params) {
return Collections.emptyList();
}
}
public static class DefaultGrpcExtractor extends AbstractRpcParamExtractor {
@Override
public List<ParamInfo> extractParam(Request request) {
return Collections.emptyList();
}
}
private static HashMap<Class<? extends AbstractRpcParamExtractor>, AbstractRpcParamExtractor> rpcManager = new HashMap<>();
private static HashMap<Class<? extends AbstractHttpParamExtractor>, AbstractHttpParamExtractor> httpManager = new HashMap<>();
static {
NacosServiceLoader.load(AbstractHttpParamExtractor.class).forEach(checker -> {
httpManager.put(checker.getClass(), checker);
});
NacosServiceLoader.load(AbstractRpcParamExtractor.class).forEach(checker -> {
rpcManager.put(checker.getClass(), checker);
});
}
public static AbstractRpcParamExtractor getRpcExtractor(Extractor extractor) {
return rpcManager.computeIfAbsent(extractor.rpcExtractor(), (key) -> new DefaultGrpcExtractor());
}
public static AbstractHttpParamExtractor getHttpExtractor(Extractor extractor) {
return httpManager.computeIfAbsent(extractor.httpExtractor(), (key) -> new DefaultHttpExtractor());
}
}

View File

@ -1,75 +0,0 @@
/*
* 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.core.paramcheck;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.common.spi.NacosServiceLoader;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* HttpParamExtractor Manager.
*
* @author zhuoguang
*/
public class HttpParamExtractorManager {
private static final String SPLITTER = "@@";
private static final HttpParamExtractorManager INSTANCE = new HttpParamExtractorManager();
private static final AbstractHttpParamExtractor DEFAULT_EXTRACTOR = new AbstractHttpParamExtractor() {
@Override
public void init() {
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest params) throws Exception {
return Collections.emptyList();
}
};
private final Map<String, AbstractHttpParamExtractor> extractorMap = new ConcurrentHashMap<>(32);
private HttpParamExtractorManager() {
Collection<AbstractHttpParamExtractor> extractors = NacosServiceLoader.load(AbstractHttpParamExtractor.class);
for (AbstractHttpParamExtractor extractor : extractors) {
List<String> targetrequestlist = extractor.getTargetRequestList();
for (String targetrequest : targetrequestlist) {
extractorMap.put(targetrequest, extractor);
}
}
}
public static HttpParamExtractorManager getInstance() {
return INSTANCE;
}
public AbstractHttpParamExtractor getExtractor(String uri, String method, String module) {
AbstractHttpParamExtractor extractor = extractorMap.get(uri + SPLITTER + method);
if (extractor == null) {
extractor = extractorMap.get("default" + SPLITTER + module);
}
return extractor == null ? DEFAULT_EXTRACTOR : extractor;
}
}

View File

@ -14,15 +14,16 @@
* limitations under the License.
*/
package com.alibaba.nacos.config.server.filter;
package com.alibaba.nacos.core.paramcheck;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.common.paramcheck.AbstractParamChecker;
import com.alibaba.nacos.common.paramcheck.ParamCheckResponse;
import com.alibaba.nacos.common.paramcheck.ParamCheckerManager;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import com.alibaba.nacos.core.paramcheck.ServerParamCheckConfig;
import com.alibaba.nacos.core.code.ControllerMethodsCache;
import com.alibaba.nacos.core.exception.ErrorCode;
import com.alibaba.nacos.plugin.control.Loggers;
import javax.servlet.Filter;
@ -33,16 +34,22 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
/**
* Config param check filter.
* ParamCheckerFilter to http filter.
*
* @author zhuoguang
* @author 985492783@qq.com
* @date 2023/11/7 17:40
*/
public class ConfigParamCheckFilter implements Filter {
public class ParamCheckerFilter implements Filter {
private static final String MODULE = "config";
private final ControllerMethodsCache methodsCache;
public ParamCheckerFilter(ControllerMethodsCache methodsCache) {
this.methodsCache = methodsCache;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
@ -55,22 +62,29 @@ public class ConfigParamCheckFilter implements Filter {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
try {
String uri = req.getRequestURI();
String method = req.getMethod();
HttpParamExtractorManager extractorManager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor paramExtractor = extractorManager.getExtractor(uri, method, MODULE);
List<ParamInfo> paramInfoList = paramExtractor.extractParam(req);
Method method = methodsCache.getMethod(req);
ExtractorManager.Extractor extractor = method.getAnnotation(ExtractorManager.Extractor.class);
if (extractor == null) {
extractor = method.getDeclaringClass().getAnnotation(ExtractorManager.Extractor.class);
if (extractor == null) {
chain.doFilter(request, response);
return;
}
}
AbstractHttpParamExtractor httpParamExtractor = ExtractorManager.getHttpExtractor(extractor);
List<ParamInfo> paramInfoList = httpParamExtractor.extractParam(req);
ParamCheckerManager paramCheckerManager = ParamCheckerManager.getInstance();
AbstractParamChecker paramChecker = paramCheckerManager.getParamChecker(ServerParamCheckConfig.getInstance().getActiveParamChecker());
ParamCheckResponse paramCheckResponse = paramChecker.checkParamInfoList(paramInfoList);
if (paramCheckResponse.isSuccess()) {
chain.doFilter(req, resp);
} else {
Loggers.CONTROL.info("Param check invalid,{},url:{}", paramCheckResponse.getMessage(), uri);
Loggers.CONTROL.info("Param check invalid,{},url:{}", paramCheckResponse.getMessage(), req.getRequestURI());
generate400Response(resp, paramCheckResponse.getMessage());
}
} catch (Exception e) {
generate400Response(resp, e.getMessage());
} catch (NacosException e) {
Loggers.CONTROL.error("exception: {}", e.getMessage());
throw new NacosRuntimeException(ErrorCode.UnKnowError.getCode(), e);
}
}

View File

@ -16,8 +16,6 @@
package com.alibaba.nacos.core.paramcheck;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import java.util.List;
/**
@ -26,14 +24,7 @@ import java.util.List;
* @param <T> the type parameter
* @author zhuoguang
*/
public interface ParamExtractor<T> {
/**
* Gets target request list.
*
* @return the target request list
*/
List<String> getTargetRequestList();
public interface ParamExtractor<T, R> {
/**
* Extract param.
@ -42,5 +33,5 @@ public interface ParamExtractor<T> {
* @return the list
* @throws Exception the exception
*/
List<ParamInfo> extractParam(T params) throws Exception;
List<R> extractParam(T params) throws Exception;
}

View File

@ -1,77 +0,0 @@
/*
* 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.core.paramcheck;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.common.spi.NacosServiceLoader;
import com.alibaba.nacos.common.utils.StringUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* HttpParamExtractor Manager.
*
* @author zhuoguang
*/
public class RpcParamExtractorManager {
private static final RpcParamExtractorManager INSTANCE = new RpcParamExtractorManager();
private static final AbstractRpcParamExtractor DEFAULT_EXTRACTOR = new AbstractRpcParamExtractor() {
@Override
public void init() {
}
@Override
public List<ParamInfo> extractParam(Request request) throws Exception {
return Collections.emptyList();
}
};
private final Map<String, AbstractRpcParamExtractor> extractorMap = new ConcurrentHashMap<>(32);
private RpcParamExtractorManager() {
Collection<AbstractRpcParamExtractor> extractors = NacosServiceLoader.load(AbstractRpcParamExtractor.class);
for (AbstractRpcParamExtractor extractor : extractors) {
List<String> targetrequestlist = extractor.getTargetRequestList();
for (String targetRequest : targetrequestlist) {
extractorMap.put(targetRequest, extractor);
}
}
}
public static RpcParamExtractorManager getInstance() {
return INSTANCE;
}
public AbstractRpcParamExtractor getExtractor(String type) {
if (StringUtils.isBlank(type)) {
return DEFAULT_EXTRACTOR;
}
AbstractRpcParamExtractor extractor = extractorMap.get(type);
if (extractor == null) {
extractor = DEFAULT_EXTRACTOR;
}
return extractor;
}
}

View File

@ -33,12 +33,7 @@ import java.util.List;
public class BatchInstanceRequestParamExtractor extends AbstractRpcParamExtractor {
@Override
public void init() {
addTargetRequest(BatchInstanceRequest.class.getSimpleName());
}
@Override
public List<ParamInfo> extractParam(Request request) throws Exception {
public List<ParamInfo> extractParam(Request request) {
BatchInstanceRequest req = (BatchInstanceRequest) request;
ParamInfo paramInfo = new ParamInfo();
paramInfo.setNamespaceId(req.getNamespace());

View File

@ -32,12 +32,7 @@ import java.util.List;
public class ConfigBatchListenRequestParamExtractor extends AbstractRpcParamExtractor {
@Override
public void init() {
addTargetRequest(ConfigBatchListenRequest.class.getSimpleName());
}
@Override
public List<ParamInfo> extractParam(Request request) throws Exception {
public List<ParamInfo> extractParam(Request request) {
ConfigBatchListenRequest req = (ConfigBatchListenRequest) request;
List<ConfigBatchListenRequest.ConfigListenContext> configListenContextList = req.getConfigListenContexts();
ArrayList<ParamInfo> paramInfos = new ArrayList<>();

View File

@ -17,10 +17,6 @@
package com.alibaba.nacos.core.paramcheck.impl;
import com.alibaba.nacos.api.config.remote.request.AbstractConfigRequest;
import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest;
import com.alibaba.nacos.api.config.remote.request.ConfigQueryRequest;
import com.alibaba.nacos.api.config.remote.request.ConfigRemoveRequest;
import com.alibaba.nacos.api.config.remote.request.cluster.ConfigChangeClusterSyncRequest;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
@ -36,15 +32,7 @@ import java.util.List;
public class ConfigRequestParamExtractor extends AbstractRpcParamExtractor {
@Override
public void init() {
addTargetRequest(ConfigRemoveRequest.class.getSimpleName());
addTargetRequest(ConfigQueryRequest.class.getSimpleName());
addTargetRequest(ConfigPublishRequest.class.getSimpleName());
addTargetRequest(ConfigChangeClusterSyncRequest.class.getSimpleName());
}
@Override
public List<ParamInfo> extractParam(Request request) throws Exception {
public List<ParamInfo> extractParam(Request request) {
AbstractConfigRequest req = (AbstractConfigRequest) request;
ParamInfo paramInfo = new ParamInfo();
paramInfo.setDataId(req.getDataId());

View File

@ -33,12 +33,7 @@ import java.util.List;
public class InstanceRequestParamExtractor extends AbstractRpcParamExtractor {
@Override
public void init() {
addTargetRequest(InstanceRequest.class.getSimpleName());
}
@Override
public List<ParamInfo> extractParam(Request request) throws Exception {
public List<ParamInfo> extractParam(Request request) {
InstanceRequest req = (InstanceRequest) request;
ParamInfo paramInfo = new ParamInfo();
paramInfo.setNamespaceId(req.getNamespace());

View File

@ -32,12 +32,7 @@ import java.util.List;
public class ServiceListRequestParamExtractor extends AbstractRpcParamExtractor {
@Override
public void init() {
addTargetRequest(ServiceListRequest.class.getSimpleName());
}
@Override
public List<ParamInfo> extractParam(Request request) throws Exception {
public List<ParamInfo> extractParam(Request request) {
ServiceListRequest req = (ServiceListRequest) request;
ParamInfo paramInfo = new ParamInfo();
paramInfo.setNamespaceId(req.getNamespace());

View File

@ -32,12 +32,7 @@ import java.util.List;
public class ServiceQueryRequestParamExtractor extends AbstractRpcParamExtractor {
@Override
public void init() {
addTargetRequest(ServiceQueryRequest.class.getSimpleName());
}
@Override
public List<ParamInfo> extractParam(Request request) throws Exception {
public List<ParamInfo> extractParam(Request request) {
ServiceQueryRequest req = (ServiceQueryRequest) request;
ParamInfo paramInfo = new ParamInfo();
paramInfo.setNamespaceId(req.getNamespace());

View File

@ -32,12 +32,7 @@ import java.util.List;
public class SubscribeServiceRequestParamExtractor extends AbstractRpcParamExtractor {
@Override
public void init() {
addTargetRequest(SubscribeServiceRequest.class.getSimpleName());
}
@Override
public List<ParamInfo> extractParam(Request request) throws Exception {
public List<ParamInfo> extractParam(Request request) {
SubscribeServiceRequest req = (SubscribeServiceRequest) request;
ParamInfo paramInfo = new ParamInfo();
paramInfo.setNamespaceId(req.getNamespace());

View File

@ -25,7 +25,7 @@ import com.alibaba.nacos.common.paramcheck.ParamCheckResponse;
import com.alibaba.nacos.common.paramcheck.ParamCheckerManager;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
import com.alibaba.nacos.core.paramcheck.RpcParamExtractorManager;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.ServerParamCheckConfig;
import com.alibaba.nacos.core.remote.AbstractRequestFilter;
import com.alibaba.nacos.plugin.control.Loggers;
@ -43,11 +43,20 @@ public class RemoteParamCheckFilter extends AbstractRequestFilter {
@Override
protected Response filter(Request request, RequestMeta meta, Class handlerClazz) throws NacosException {
String className = request.getClass().getSimpleName();
boolean paramCheckEnabled = ServerParamCheckConfig.getInstance().isParamCheckEnabled();
if (!paramCheckEnabled) {
return null;
}
try {
RpcParamExtractorManager extractorManager = RpcParamExtractorManager.getInstance();
AbstractRpcParamExtractor extractor = extractorManager.getExtractor(className);
List<ParamInfo> paramInfoList = extractor.extractParam(request);
ExtractorManager.Extractor extractor = getHandleMethod(handlerClazz).getAnnotation(ExtractorManager.Extractor.class);
if (extractor == null) {
extractor = (ExtractorManager.Extractor) handlerClazz.getAnnotation(ExtractorManager.Extractor.class);
if (extractor == null) {
return null;
}
}
AbstractRpcParamExtractor paramExtractor = ExtractorManager.getRpcExtractor(extractor);
List<ParamInfo> paramInfoList = paramExtractor.extractParam(request);
ParamCheckerManager paramCheckerManager = ParamCheckerManager.getInstance();
AbstractParamChecker paramChecker = paramCheckerManager.getParamChecker(
ServerParamCheckConfig.getInstance().getActiveParamChecker());

View File

@ -21,8 +21,9 @@ import com.alibaba.nacos.core.distributed.distro.DistroConstants;
import com.alibaba.nacos.core.distributed.raft.RaftSysConstants;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.module.ModuleStateHolder;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.mock.env.MockEnvironment;
@ -33,28 +34,31 @@ import static org.junit.Assert.assertFalse;
/**
* cluster module-state-builder test.
*
* @author 985492783@qq.com
* @date 2023/4/8 0:13
*/
public class ModuleStateStandaloneTest {
private ConfigurableEnvironment environment;
private ModuleStateHolder moduleStateHolder;
@Before
public void setUp() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
environment = new MockEnvironment();
EnvUtil.setEnvironment(environment);
EnvUtil.setIsStandalone(true);
Constructor<ModuleStateHolder> constructor = ModuleStateHolder.class.getDeclaredConstructor();
constructor.setAccessible(true);
moduleStateHolder = constructor.newInstance();
@Test
public void testStandaloneBuilder()
throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
try (MockedStatic<EnvUtil> mockedStatic = Mockito.mockStatic(EnvUtil.class)) {
environment = new MockEnvironment();
mockedStatic.when(EnvUtil::getEnvironment).thenReturn(environment);
mockedStatic.when(EnvUtil::getStandaloneMode).thenReturn(true);
Constructor<ModuleStateHolder> constructor = ModuleStateHolder.class.getDeclaredConstructor();
constructor.setAccessible(true);
moduleStateHolder = constructor.newInstance();
assertFalse(moduleStateHolder.getModuleState(DistroConstants.DISTRO_MODULE).isPresent());
assertFalse(moduleStateHolder.getModuleState(RaftSysConstants.RAFT_STATE).isPresent());
}
}
@Test
public void testStandaloneBuilder() {
assertFalse(moduleStateHolder.getModuleState(DistroConstants.DISTRO_MODULE).isPresent());
assertFalse(moduleStateHolder.getModuleState(RaftSysConstants.RAFT_STATE).isPresent());
}
}

View File

@ -1,48 +0,0 @@
/*
* 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.core.paramcheck;
import com.alibaba.nacos.common.utils.HttpMethod;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* The type Http param extractor manager test.
*/
public class HttpParamExtractorManagerTest extends TestCase {
/**
* Test get instance.
*/
public void testGetInstance() {
HttpParamExtractorManager paramExtractorManager = HttpParamExtractorManager.getInstance();
}
/**
* Test get extractor.
*
* @throws Exception the exception
*/
public void testGetExtractor() throws Exception {
HttpParamExtractorManager paramExtractorManager = HttpParamExtractorManager.getInstance();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/nacos/v1/ns/instance");
request.setMethod(HttpMethod.POST);
AbstractHttpParamExtractor extractor = paramExtractorManager.getExtractor(request.getRequestURI(), request.getMethod(), "naming");
extractor.extractParam(request);
}
}

View File

@ -0,0 +1,68 @@
/*
* 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.core.paramcheck;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.core.paramcheck.impl.ConfigRequestParamExtractor;
import org.junit.Test;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* ParamCheckerTest.
*
* @author 985492783@qq.com
* @date 2023/11/7 20:16
*/
public class ParamExtractorTest {
@Test
public void testCheckAnnotation() {
ExtractorManager.Extractor extractor = Controller.class.getAnnotation(ExtractorManager.Extractor.class);
AbstractRpcParamExtractor paramExtractor = ExtractorManager.getRpcExtractor(extractor);
assertEquals(paramExtractor.getClass().getSimpleName(), ConfigRequestParamExtractor.class.getSimpleName());
}
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public static class Controller {
public void testCheckNull() {
}
@ExtractorManager.Extractor(httpExtractor = TestHttpChecker.class)
public void testCheck() {
}
}
public static class TestHttpChecker extends AbstractHttpParamExtractor {
@Override
public List<ParamInfo> extractParam(HttpServletRequest params) {
List<ParamInfo> list = new ArrayList<>();
ParamInfo paramInfo = new ParamInfo();
paramInfo.setDataId(params.getParameter("dataId"));
list.add(paramInfo);
return list;
}
}
}

View File

@ -1,45 +0,0 @@
/*
* 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.core.paramcheck;
import com.alibaba.nacos.api.config.remote.request.ConfigQueryRequest;
import junit.framework.TestCase;
/**
* The type Rpc param extractor manager test.
*/
public class RpcParamExtractorManagerTest extends TestCase {
/**
* Test get instance.
*/
public void testGetInstance() {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
}
/**
* Test get extractor.
*
* @throws Exception the exception
*/
public void testGetExtractor() throws Exception {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
ConfigQueryRequest request = new ConfigQueryRequest();
AbstractRpcParamExtractor extractor = paramExtractorManager.getExtractor(request.getClass().getSimpleName());
extractor.extractParam(request);
}
}

View File

@ -1,46 +0,0 @@
/*
* 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.core.paramcheck.impl;
import com.alibaba.nacos.api.naming.remote.request.BatchInstanceRequest;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
import com.alibaba.nacos.core.paramcheck.RpcParamExtractorManager;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BatchInstanceRequestParamExtractorTest {
private static BatchInstanceRequest req;
@BeforeClass
public static void initBatchInstanceRequest() {
req = new BatchInstanceRequest();
}
/**
* Test extract param and check.
*/
@Test
public void testExtractParamAndCheck() throws Exception {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
AbstractRpcParamExtractor extractor = paramExtractorManager.getExtractor(req.getClass().getSimpleName());
assertEquals(extractor.getClass().getSimpleName(), BatchInstanceRequestParamExtractor.class.getSimpleName());
extractor.extractParam(req);
}
}

View File

@ -1,46 +0,0 @@
/*
* 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.core.paramcheck.impl;
import com.alibaba.nacos.api.config.remote.request.ConfigBatchListenRequest;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
import com.alibaba.nacos.core.paramcheck.RpcParamExtractorManager;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConfigBatchListenRequestParamExtractorTest {
private static ConfigBatchListenRequest req;
@BeforeClass
public static void initConfigBatchListenRequest() {
req = new ConfigBatchListenRequest();
}
/**
* Test extract param and check.
*/
@Test
public void testExtractParamAndCheck() throws Exception {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
AbstractRpcParamExtractor extractor = paramExtractorManager.getExtractor(req.getClass().getSimpleName());
assertEquals(extractor.getClass().getSimpleName(), ConfigBatchListenRequestParamExtractor.class.getSimpleName());
extractor.extractParam(req);
}
}

View File

@ -1,71 +0,0 @@
/*
* 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.core.paramcheck.impl;
import com.alibaba.nacos.api.config.remote.request.AbstractConfigRequest;
import com.alibaba.nacos.api.config.remote.request.ConfigPublishRequest;
import com.alibaba.nacos.api.config.remote.request.ConfigQueryRequest;
import com.alibaba.nacos.api.config.remote.request.ConfigRemoveRequest;
import com.alibaba.nacos.api.config.remote.request.cluster.ConfigChangeClusterSyncRequest;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
import com.alibaba.nacos.core.paramcheck.RpcParamExtractorManager;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConfigRequestParamExtractorTest {
private static AbstractConfigRequest req1;
private static AbstractConfigRequest req2;
private static AbstractConfigRequest req3;
private static AbstractConfigRequest req4;
@BeforeClass
public static void initAbstractConfigRequest() {
req1 = new ConfigPublishRequest();
req2 = new ConfigQueryRequest();
req3 = new ConfigRemoveRequest();
req4 = new ConfigChangeClusterSyncRequest();
}
/**
* Test extract param and check.
*/
@Test
public void testExtractParamAndCheck() throws Exception {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
AbstractRpcParamExtractor extractor1 = paramExtractorManager.getExtractor(req1.getClass().getSimpleName());
assertEquals(extractor1.getClass().getSimpleName(), ConfigRequestParamExtractor.class.getSimpleName());
extractor1.extractParam(req1);
AbstractRpcParamExtractor extractor2 = paramExtractorManager.getExtractor(req2.getClass().getSimpleName());
assertEquals(extractor2.getClass().getSimpleName(), ConfigRequestParamExtractor.class.getSimpleName());
extractor2.extractParam(req2);
AbstractRpcParamExtractor extractor3 = paramExtractorManager.getExtractor(req3.getClass().getSimpleName());
assertEquals(extractor3.getClass().getSimpleName(), ConfigRequestParamExtractor.class.getSimpleName());
extractor3.extractParam(req3);
AbstractRpcParamExtractor extractor4 = paramExtractorManager.getExtractor(req4.getClass().getSimpleName());
assertEquals(extractor4.getClass().getSimpleName(), ConfigRequestParamExtractor.class.getSimpleName());
extractor4.extractParam(req4);
}
}

View File

@ -1,46 +0,0 @@
/*
* 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.core.paramcheck.impl;
import com.alibaba.nacos.api.naming.remote.request.InstanceRequest;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
import com.alibaba.nacos.core.paramcheck.RpcParamExtractorManager;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class InstanceRequestParamExtractorTest {
private static InstanceRequest req;
@BeforeClass
public static void initInstanceRequest() {
req = new InstanceRequest();
}
/**
* Test extract param and check.
*/
@Test
public void testExtractParamAndCheck() throws Exception {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
AbstractRpcParamExtractor extractor = paramExtractorManager.getExtractor(req.getClass().getSimpleName());
assertEquals(extractor.getClass().getSimpleName(), InstanceRequestParamExtractor.class.getSimpleName());
extractor.extractParam(req);
}
}

View File

@ -1,46 +0,0 @@
/*
* 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.core.paramcheck.impl;
import com.alibaba.nacos.api.naming.remote.request.ServiceListRequest;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
import com.alibaba.nacos.core.paramcheck.RpcParamExtractorManager;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ServiceListRequestParamExtractorTest {
private static ServiceListRequest req;
@BeforeClass
public static void initServiceListRequest() {
req = new ServiceListRequest();
}
/**
* Test extract param and check.
*/
@Test
public void testExtractParamAndCheck() throws Exception {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
AbstractRpcParamExtractor extractor = paramExtractorManager.getExtractor(req.getClass().getSimpleName());
assertEquals(extractor.getClass().getSimpleName(), ServiceListRequestParamExtractor.class.getSimpleName());
extractor.extractParam(req);
}
}

View File

@ -1,46 +0,0 @@
/*
* 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.core.paramcheck.impl;
import com.alibaba.nacos.api.naming.remote.request.ServiceQueryRequest;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
import com.alibaba.nacos.core.paramcheck.RpcParamExtractorManager;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ServiceQueryRequestParamExtractorTest {
private static ServiceQueryRequest req;
@BeforeClass
public static void initServiceQueryRequest() {
req = new ServiceQueryRequest();
}
/**
* Test extract param and check.
*/
@Test
public void testExtractParamAndCheck() throws Exception {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
AbstractRpcParamExtractor extractor = paramExtractorManager.getExtractor(req.getClass().getSimpleName());
assertEquals(extractor.getClass().getSimpleName(), ServiceQueryRequestParamExtractor.class.getSimpleName());
extractor.extractParam(req);
}
}

View File

@ -1,47 +0,0 @@
/*
* 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.core.paramcheck.impl;
import com.alibaba.nacos.api.naming.remote.request.SubscribeServiceRequest;
import com.alibaba.nacos.core.paramcheck.AbstractRpcParamExtractor;
import com.alibaba.nacos.core.paramcheck.RpcParamExtractorManager;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SubscribeServiceRequestParamExtractorTest {
private static SubscribeServiceRequest req;
@BeforeClass
public static void initSubscribeServiceRequest() {
req = new SubscribeServiceRequest();
}
/**
* Test extract param and check.
*/
@Test
public void testExtractParamAndCheck() throws Exception {
RpcParamExtractorManager paramExtractorManager = RpcParamExtractorManager.getInstance();
AbstractRpcParamExtractor extractor = paramExtractorManager.getExtractor(req.getClass().getSimpleName());
assertEquals(extractor.getClass().getSimpleName(), SubscribeServiceRequestParamExtractor.class.getSimpleName());
extractor.extractParam(req);
}
}

View File

@ -1,88 +0,0 @@
/*
* 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.core.remote.grpc;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.remote.request.BatchInstanceRequest;
import com.alibaba.nacos.api.naming.remote.request.InstanceRequest;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.core.remote.HealthCheckRequestHandler;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mockStatic;
@RunWith(SpringJUnit4ClassRunner.class)
public class RemoteParamCheckFilterTest {
private static RemoteParamCheckFilter remoteParamCheckFilter;
private static MockedStatic<EnvUtil> envUtilMockedStatic;
@BeforeClass
public static void init() {
envUtilMockedStatic = mockStatic(EnvUtil.class);
envUtilMockedStatic.when(
() -> EnvUtil.getProperty("nacos.core.param.check.enabled", Boolean.class, true))
.thenReturn(Boolean.TRUE);
envUtilMockedStatic.when(
() -> EnvUtil.getProperty("nacos.core.param.check.checker", String.class, "default")
).thenReturn("default");
remoteParamCheckFilter = new RemoteParamCheckFilter();
}
@AfterClass
public static void close() {
envUtilMockedStatic.close();
}
@Test
public void filter() {
Instance instance = new Instance();
instance.setIp("11.11.11.11");
instance.setPort(-1);
instance.setServiceName("test");
InstanceRequest instanceRequest = new InstanceRequest();
instanceRequest.setInstance(instance);
instanceRequest.setNamespace("public");
instanceRequest.setServiceName("test");
Response response = null;
try {
response = remoteParamCheckFilter.filter(instanceRequest, new RequestMeta(), HealthCheckRequestHandler.class);
} catch (Exception e) {
e.printStackTrace();
}
assertEquals(response.getMessage(), "Param check invalid:Param 'port' is illegal, the value should be between 0 and 65535.");
BatchInstanceRequest batchInstanceRequest = new BatchInstanceRequest();
batchInstanceRequest.setServiceName("test@@@@");
try {
response = remoteParamCheckFilter.filter(batchInstanceRequest, new RequestMeta(), HealthCheckRequestHandler.class);
} catch (Exception e) {
e.printStackTrace();
}
assertEquals(response.getMessage(), "Param check invalid:Param 'serviceName' is illegal, illegal characters should not appear in the param.");
}
}

View File

@ -0,0 +1,17 @@
#
# Copyright 1999-2021 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.core.paramcheck.ParamExtractorTest$TestHttpChecker

View File

@ -23,9 +23,11 @@ import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.naming.core.CatalogService;
import com.alibaba.nacos.naming.core.CatalogServiceV2Impl;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
@ -43,6 +45,7 @@ import java.util.List;
*/
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_CATALOG_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class CatalogController {
@Autowired

View File

@ -24,11 +24,13 @@ import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.NumberUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.ClusterOperator;
import com.alibaba.nacos.naming.core.ClusterOperatorV2Impl;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -43,6 +45,7 @@ import javax.servlet.http.HttpServletRequest;
*/
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_CLUSTER_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class ClusterController {
private final ClusterOperatorV2Impl clusterOperatorV2;

View File

@ -25,12 +25,14 @@ import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.HealthOperator;
import com.alibaba.nacos.naming.core.HealthOperatorV2Impl;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.monitor.MetricsMonitor;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.naming.web.CanDistro;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.sys.env.EnvUtil;
@ -61,6 +63,7 @@ import static com.alibaba.nacos.naming.constants.RequestConstant.VALID_KEY;
*/
@RestController("namingHealthController")
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_HEALTH_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class HealthController {
@Autowired

View File

@ -32,6 +32,7 @@ import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.InstanceOperator;
import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl;
@ -41,6 +42,10 @@ import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.misc.SwitchEntry;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.naming.paramcheck.NamingInstanceBeatHttpParamExtractor;
import com.alibaba.nacos.naming.paramcheck.NamingInstanceListHttpParamExtractor;
import com.alibaba.nacos.naming.paramcheck.NamingInstanceMetadataBatchHttpParamExtractor;
import com.alibaba.nacos.naming.pojo.InstanceOperationInfo;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.pojo.instance.BeatInfoInstanceBuilder;
@ -77,6 +82,7 @@ import static com.alibaba.nacos.naming.misc.UtilsAndCommons.DEFAULT_CLUSTER_NAME
*/
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class InstanceController {
@Autowired
@ -181,6 +187,7 @@ public class InstanceController {
@PutMapping(value = "/metadata/batch")
@TpsControl(pointName = "NamingInstanceMetadataUpdate", name = "HttpNamingInstanceMetadataBatchUpdate")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceMetadataBatchHttpParamExtractor.class)
public ObjectNode batchUpdateInstanceMetadata(HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
Constants.DEFAULT_NAMESPACE_ID);
@ -215,6 +222,7 @@ public class InstanceController {
@DeleteMapping("/metadata/batch")
@TpsControl(pointName = "NamingInstanceMetadataUpdate", name = "HttpNamingInstanceMetadataBatchUpdate")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceMetadataBatchHttpParamExtractor.class)
public ObjectNode batchDeleteInstanceMetadata(HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
Constants.DEFAULT_NAMESPACE_ID);
@ -311,6 +319,7 @@ public class InstanceController {
@GetMapping("/list")
@TpsControl(pointName = "NamingServiceSubscribe", name = "HttpNamingServiceSubscribe")
@Secured(action = ActionTypes.READ)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceListHttpParamExtractor.class)
public Object list(HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
@ -373,6 +382,7 @@ public class InstanceController {
@PutMapping("/beat")
@TpsControl(pointName = "HttpHealthCheck", name = "HttpHealthCheck")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceBeatHttpParamExtractor.class)
public ObjectNode beat(HttpServletRequest request) throws Exception {
ObjectNode result = JacksonUtils.createEmptyJsonNode();

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.naming.controllers;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.cluster.ServerStatusManager;
import com.alibaba.nacos.naming.constants.ClientConstants;
@ -32,6 +33,7 @@ import com.alibaba.nacos.naming.misc.SwitchEntry;
import com.alibaba.nacos.naming.misc.SwitchManager;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.monitor.MetricsMonitor;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
@ -52,6 +54,7 @@ import java.util.Collection;
@RestController
@RequestMapping({UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_OPERATOR_CONTEXT,
UtilsAndCommons.NACOS_NAMING_CONTEXT + "/ops"})
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class OperatorController {
private final SwitchManager switchManager;

View File

@ -32,6 +32,7 @@ import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.NumberUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.ServiceOperator;
import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;
@ -39,6 +40,7 @@ import com.alibaba.nacos.naming.core.SubscribeManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.selector.NoneSelector;
import com.alibaba.nacos.naming.selector.SelectorManager;
@ -71,6 +73,7 @@ import java.util.Optional;
*/
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_SERVICE_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class ServiceController {
@Autowired

View File

@ -22,8 +22,10 @@ import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.naming.core.CatalogServiceV2Impl;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.beans.factory.annotation.Autowired;
@ -43,6 +45,7 @@ import java.util.stream.Stream;
*/
@RestController
@RequestMapping(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_CATALOG_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class CatalogControllerV2 {
@Autowired

View File

@ -23,6 +23,7 @@ import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.model.v2.Result;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.remote.Connection;
import com.alibaba.nacos.core.remote.ConnectionManager;
import com.alibaba.nacos.core.remote.ConnectionMeta;
@ -34,6 +35,7 @@ import com.alibaba.nacos.naming.core.v2.index.ClientServiceIndexesManager;
import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.fasterxml.jackson.databind.node.ObjectNode;
@ -58,6 +60,7 @@ import java.util.Objects;
@NacosApi
@RestController
@RequestMapping(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_CLIENT_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class ClientInfoControllerV2 {
private final ClientManager clientManager;

View File

@ -21,9 +21,11 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.model.v2.Result;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.naming.core.HealthOperatorV2Impl;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.model.form.UpdateHealthForm;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.naming.web.CanDistro;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import org.springframework.beans.factory.annotation.Autowired;
@ -39,6 +41,7 @@ import org.springframework.web.bind.annotation.RestController;
@NacosApi
@RestController
@RequestMapping(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_HEALTH_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class HealthControllerV2 {
@Autowired

View File

@ -37,6 +37,7 @@ import com.alibaba.nacos.common.trace.event.naming.UpdateInstanceTraceEvent;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl;
import com.alibaba.nacos.naming.core.InstancePatchObject;
import com.alibaba.nacos.naming.healthcheck.RsInfo;
@ -48,6 +49,10 @@ import com.alibaba.nacos.naming.model.form.InstanceForm;
import com.alibaba.nacos.naming.model.form.InstanceMetadataBatchOperationForm;
import com.alibaba.nacos.naming.model.vo.InstanceDetailInfoVo;
import com.alibaba.nacos.naming.model.vo.InstanceMetadataBatchOperationVo;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.naming.paramcheck.NamingInstanceBeatHttpParamExtractor;
import com.alibaba.nacos.naming.paramcheck.NamingInstanceListHttpParamExtractor;
import com.alibaba.nacos.naming.paramcheck.NamingInstanceMetadataBatchHttpParamExtractor;
import com.alibaba.nacos.naming.pojo.InstanceOperationInfo;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.pojo.instance.BeatInfoInstanceBuilder;
@ -85,6 +90,7 @@ import static com.alibaba.nacos.naming.misc.UtilsAndCommons.DEFAULT_CLUSTER_NAME
@NacosApi
@RestController
@RequestMapping(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class InstanceControllerV2 {
@Autowired
@ -165,6 +171,7 @@ public class InstanceControllerV2 {
@PutMapping(value = "/metadata/batch")
@TpsControl(pointName = "NamingInstanceMetadataUpdate", name = "HttpNamingInstanceMetadataBatchUpdate")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceMetadataBatchHttpParamExtractor.class)
public Result<InstanceMetadataBatchOperationVo> batchUpdateInstanceMetadata(InstanceMetadataBatchOperationForm form)
throws NacosException {
form.validate();
@ -188,6 +195,7 @@ public class InstanceControllerV2 {
@DeleteMapping("/metadata/batch")
@TpsControl(pointName = "NamingInstanceMetadataUpdate", name = "HttpNamingInstanceMetadataBatchUpdate")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceMetadataBatchHttpParamExtractor.class)
public Result<InstanceMetadataBatchOperationVo> batchDeleteInstanceMetadata(InstanceMetadataBatchOperationForm form)
throws NacosException {
form.validate();
@ -280,6 +288,7 @@ public class InstanceControllerV2 {
@GetMapping("/list")
@TpsControl(pointName = "NamingServiceSubscribe", name = "HttpNamingServiceSubscribe")
@Secured(action = ActionTypes.READ)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceListHttpParamExtractor.class)
public Result<ServiceInfo> list(
@RequestParam(value = "namespaceId", defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam(value = "groupName", defaultValue = Constants.DEFAULT_GROUP) String groupName,
@ -354,6 +363,7 @@ public class InstanceControllerV2 {
@PutMapping("/beat")
@TpsControl(pointName = "HttpHealthCheck", name = "HttpHealthCheck")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(httpExtractor = NamingInstanceBeatHttpParamExtractor.class)
public ObjectNode beat(@RequestParam(defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam String serviceName, @RequestParam(defaultValue = StringUtils.EMPTY) String ip,
@RequestParam(defaultValue = UtilsAndCommons.DEFAULT_CLUSTER_NAME) String clusterName,

View File

@ -21,6 +21,7 @@ import com.alibaba.nacos.api.exception.api.NacosApiException;
import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.model.v2.Result;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.naming.cluster.ServerStatusManager;
import com.alibaba.nacos.naming.constants.ClientConstants;
import com.alibaba.nacos.naming.core.v2.client.impl.IpPortBasedClient;
@ -31,6 +32,7 @@ import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.model.form.UpdateSwitchForm;
import com.alibaba.nacos.naming.model.vo.MetricsInfoVo;
import com.alibaba.nacos.naming.monitor.MetricsMonitor;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.http.HttpStatus;
@ -52,6 +54,7 @@ import java.util.Collection;
@RestController
@RequestMapping({UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_OPERATOR_CONTEXT,
UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + "/ops"})
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class OperatorControllerV2 {
private final SwitchManager switchManager;

View File

@ -31,11 +31,13 @@ import com.alibaba.nacos.common.trace.event.naming.UpdateServiceTraceEvent;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.model.form.ServiceForm;
import com.alibaba.nacos.naming.paramcheck.NamingDefaultHttpParamExtractor;
import com.alibaba.nacos.naming.pojo.ServiceDetailInfo;
import com.alibaba.nacos.naming.pojo.ServiceNameView;
import com.alibaba.nacos.naming.selector.NoneSelector;
@ -65,6 +67,7 @@ import java.util.Optional;
@NacosApi
@RestController
@RequestMapping(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_SERVICE_CONTEXT)
@ExtractorManager.Extractor(httpExtractor = NamingDefaultHttpParamExtractor.class)
public class ServiceControllerV2 {
private final ServiceOperatorV2Impl serviceOperatorV2;

View File

@ -34,11 +34,6 @@ import java.util.List;
*/
public class NamingDefaultHttpParamExtractor extends AbstractHttpParamExtractor {
@Override
public void init() {
addDefaultTargetRequest("naming");
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) throws NacosException {
ParamInfo paramInfo = new ParamInfo();

View File

@ -18,12 +18,10 @@ package com.alibaba.nacos.naming.paramcheck;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.naming.healthcheck.RsInfo;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
@ -37,15 +35,7 @@ import java.util.List;
public class NamingInstanceBeatHttpParamExtractor extends AbstractHttpParamExtractor {
@Override
public void init() {
addTargetRequest(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/beat",
HttpMethod.PUT);
addTargetRequest(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT
+ "/beat", HttpMethod.PUT);
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) throws Exception {
public List<ParamInfo> extractParam(HttpServletRequest request) {
ParamInfo paramInfo = new ParamInfo();
String serviceName = request.getParameter("serviceName");
String groupName = request.getParameter("groupName");

View File

@ -19,9 +19,7 @@ package com.alibaba.nacos.naming.paramcheck;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
@ -35,13 +33,7 @@ import java.util.List;
public class NamingInstanceListHttpParamExtractor extends AbstractHttpParamExtractor {
@Override
public void init() {
addTargetRequest(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/list",
HttpMethod.GET);
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) throws Exception {
public List<ParamInfo> extractParam(HttpServletRequest request) {
ParamInfo paramInfo = new ParamInfo();
String serviceName = request.getParameter("serviceName");
String groupName = request.getParameter("groupName");

View File

@ -17,9 +17,9 @@
package com.alibaba.nacos.naming.paramcheck;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
@ -38,19 +38,7 @@ import java.util.List;
public class NamingInstanceMetadataBatchHttpParamExtractor extends AbstractHttpParamExtractor {
@Override
public void init() {
addTargetRequest(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/metadata/batch",
HttpMethod.PUT);
addTargetRequest(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/metadata/batch",
HttpMethod.DELETE);
addTargetRequest(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/metadata/batch",
HttpMethod.PUT);
addTargetRequest(UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/metadata/batch",
HttpMethod.DELETE);
}
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) throws Exception {
public List<ParamInfo> extractParam(HttpServletRequest request) throws NacosException {
ParamInfo paramInfo = new ParamInfo();
String serviceName = request.getParameter("serviceName");
String groupName = request.getParameter("groupName");

View File

@ -23,6 +23,8 @@ import com.alibaba.nacos.api.naming.remote.response.BatchInstanceResponse;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.BatchInstanceRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.service.impl.EphemeralClientOperationServiceImpl;
@ -47,6 +49,7 @@ public class BatchInstanceRequestHandler extends RequestHandler<BatchInstanceReq
@Override
@TpsControl(pointName = "RemoteNamingInstanceBatchRegister", name = "RemoteNamingInstanceBatchRegister")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(rpcExtractor = BatchInstanceRequestParamExtractor.class)
public BatchInstanceResponse handle(BatchInstanceRequest request, RequestMeta meta) throws NacosException {
Service service = Service.newService(request.getNamespace(), request.getGroupName(), request.getServiceName(),
true);

View File

@ -27,6 +27,8 @@ import com.alibaba.nacos.common.trace.DeregisterInstanceReason;
import com.alibaba.nacos.common.trace.event.naming.DeregisterInstanceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.RegisterInstanceTraceEvent;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.InstanceRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.service.impl.EphemeralClientOperationServiceImpl;
@ -51,6 +53,7 @@ public class InstanceRequestHandler extends RequestHandler<InstanceRequest, Inst
@Override
@TpsControl(pointName = "RemoteNamingInstanceRegisterDeregister", name = "RemoteNamingInstanceRegisterDeregister")
@Secured(action = ActionTypes.WRITE)
@ExtractorManager.Extractor(rpcExtractor = InstanceRequestParamExtractor.class)
public InstanceResponse handle(InstanceRequest request, RequestMeta meta) throws NacosException {
Service service = Service
.newService(request.getNamespace(), request.getGroupName(), request.getServiceName(), true);

View File

@ -22,6 +22,8 @@ import com.alibaba.nacos.api.naming.remote.response.ServiceListResponse;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.ServiceListRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
@ -46,6 +48,7 @@ public class ServiceListRequestHandler extends RequestHandler<ServiceListRequest
@Override
@TpsControl(pointName = "RemoteNamingServiceListQuery", name = "RemoteNamingServiceListQuery")
@Secured(action = ActionTypes.READ)
@ExtractorManager.Extractor(rpcExtractor = ServiceListRequestParamExtractor.class)
public ServiceListResponse handle(ServiceListRequest request, RequestMeta meta) throws NacosException {
Collection<Service> serviceSet = ServiceManager.getInstance().getSingletons(request.getNamespace());
ServiceListResponse result = ServiceListResponse.buildSuccessResponse(0, new LinkedList<>());

View File

@ -23,6 +23,8 @@ import com.alibaba.nacos.api.naming.remote.response.QueryServiceResponse;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.ServiceQueryRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
@ -52,6 +54,7 @@ public class ServiceQueryRequestHandler extends RequestHandler<ServiceQueryReque
@Override
@TpsControl(pointName = "RemoteNamingServiceQuery", name = "RemoteNamingServiceQuery")
@Secured(action = ActionTypes.READ)
@ExtractorManager.Extractor(rpcExtractor = ServiceQueryRequestParamExtractor.class)
public QueryServiceResponse handle(ServiceQueryRequest request, RequestMeta meta) throws NacosException {
String namespaceId = request.getNamespace();
String groupName = request.getGroupName();

View File

@ -28,6 +28,8 @@ import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.trace.event.naming.SubscribeServiceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.UnsubscribeServiceTraceEvent;
import com.alibaba.nacos.core.control.TpsControl;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.impl.SubscribeServiceRequestParamExtractor;
import com.alibaba.nacos.core.remote.RequestHandler;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
@ -63,6 +65,7 @@ public class SubscribeServiceRequestHandler extends RequestHandler<SubscribeServ
@Override
@TpsControl(pointName = "RemoteNamingServiceSubscribeUnSubscribe", name = "RemoteNamingServiceSubscribeUnsubscribe")
@Secured(action = ActionTypes.READ)
@ExtractorManager.Extractor(rpcExtractor = SubscribeServiceRequestParamExtractor.class)
public SubscribeServiceResponse handle(SubscribeServiceRequest request, RequestMeta meta) throws NacosException {
String namespaceId = request.getNamespace();
String serviceName = request.getServiceName();

View File

@ -82,16 +82,6 @@ public class NamingConfig {
return registration;
}
@Bean
public FilterRegistrationBean<NamingParamCheckFilter> paramCheckFilterRegistration() {
FilterRegistrationBean<NamingParamCheckFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(namingParamCheckFilter());
registration.addUrlPatterns(URL_PATTERNS, URL_PATTERNS_V2);
registration.setName(NAMING_PARAM_CHECK_FILTER);
registration.setOrder(10);
return registration;
}
@Bean
public DistroFilter distroFilter() {
return new DistroFilter();
@ -111,9 +101,4 @@ public class NamingConfig {
public ClientAttributesFilter clientAttributesFilter() {
return new ClientAttributesFilter();
}
@Bean
public NamingParamCheckFilter namingParamCheckFilter() {
return new NamingParamCheckFilter();
}
}

View File

@ -1,95 +0,0 @@
/*
* 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.naming.web;
import com.alibaba.nacos.common.paramcheck.AbstractParamChecker;
import com.alibaba.nacos.common.paramcheck.ParamCheckResponse;
import com.alibaba.nacos.common.paramcheck.ParamCheckerManager;
import com.alibaba.nacos.common.paramcheck.ParamInfo;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import com.alibaba.nacos.core.paramcheck.ServerParamCheckConfig;
import com.alibaba.nacos.plugin.control.Loggers;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Naming param check filter.
*
* @author zhuoguang
*/
public class NamingParamCheckFilter implements Filter {
private static final String MODULE = "naming";
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
boolean paramCheckEnabled = ServerParamCheckConfig.getInstance().isParamCheckEnabled();
if (!paramCheckEnabled) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
try {
String uri = request.getRequestURI();
String method = request.getMethod();
HttpParamExtractorManager extractorManager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor paramExtractor = extractorManager.getExtractor(uri, method, MODULE);
List<ParamInfo> paramInfoList = paramExtractor.extractParam(request);
ParamCheckerManager paramCheckerManager = ParamCheckerManager.getInstance();
AbstractParamChecker paramChecker = paramCheckerManager.getParamChecker(ServerParamCheckConfig.getInstance().getActiveParamChecker());
ParamCheckResponse paramCheckResponse = paramChecker.checkParamInfoList(paramInfoList);
if (paramCheckResponse.isSuccess()) {
filterChain.doFilter(request, resp);
} else {
Loggers.CONTROL.info("Param check invalid,{},url:{}", paramCheckResponse.getMessage(), uri);
generate400Response(resp, paramCheckResponse.getMessage());
}
} catch (Exception e) {
generate400Response(resp, e.getMessage());
}
}
/**
* Generate 400 response.
*
* @param response the response
* @param message the message
*/
public void generate400Response(HttpServletResponse response, String message) {
try {
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache,no-store");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getOutputStream().println(message);
} catch (Exception ex) {
Loggers.CONTROL.error("Error to generate tps 400 response", ex);
}
}
}

View File

@ -1,43 +0,0 @@
/*
* 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.naming.paramcheck;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.Assert.assertEquals;
/**
* The type Naming default http param extractor test.
*
* @author zhuoguang
*/
public class NamingDefaultHttpParamExtractorTest {
@Test
public void extractParamAndCheck() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/nacos/v1/ns/instance/lalala");
request.setMethod(HttpMethod.DELETE);
HttpParamExtractorManager manager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor extractor = manager.getExtractor(request.getRequestURI(), request.getMethod(), "naming");
assertEquals(NamingDefaultHttpParamExtractor.class.getSimpleName(), extractor.getClass().getSimpleName());
}
}

View File

@ -1,45 +0,0 @@
/*
* 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.naming.paramcheck;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.Assert.assertEquals;
/**
* The type Naming instance beat http param extractor test.
*
* @author zhuoguang
*/
public class NamingInstanceBeatHttpParamExtractorTest {
@Test
public void extractParamAndCheck() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/nacos" + UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT
+ "/beat");
request.setMethod(HttpMethod.PUT);
HttpParamExtractorManager manager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor extractor = manager.getExtractor(request.getRequestURI(), request.getMethod(), "naming");
assertEquals(NamingInstanceBeatHttpParamExtractor.class.getSimpleName(), extractor.getClass().getSimpleName());
}
}

View File

@ -1,44 +0,0 @@
/*
* 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.naming.paramcheck;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.Assert.assertEquals;
/**
* The type Naming instance list http param extractor test.
*
* @author zhuoguang
*/
public class NamingInstanceListHttpParamExtractorTest {
@Test
public void extractParamAndCheck() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/nacos" + UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/list");
request.setMethod(HttpMethod.GET);
HttpParamExtractorManager manager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor extractor = manager.getExtractor(request.getRequestURI(), request.getMethod(), "naming");
assertEquals(NamingInstanceListHttpParamExtractor.class.getSimpleName(), extractor.getClass().getSimpleName());
}
}

View File

@ -1,44 +0,0 @@
/*
* 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.naming.paramcheck;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.HttpParamExtractorManager;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.Assert.assertEquals;
/**
* The type Naming instance metadata batch http param extractor test.
*
* @author zhuoguang
*/
public class NamingInstanceMetadataBatchHttpParamExtractorTest {
@Test
public void extractParamAndCheck() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/nacos" + UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/metadata/batch");
request.setMethod(HttpMethod.PUT);
HttpParamExtractorManager manager = HttpParamExtractorManager.getInstance();
AbstractHttpParamExtractor extractor = manager.getExtractor(request.getRequestURI(), request.getMethod(), "naming");
assertEquals(NamingInstanceMetadataBatchHttpParamExtractor.class.getSimpleName(), extractor.getClass().getSimpleName());
}
}

View File

@ -0,0 +1,124 @@
/*
* 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.naming.paramcheck;
import com.alibaba.nacos.core.code.ControllerMethodsCache;
import com.alibaba.nacos.core.paramcheck.AbstractHttpParamExtractor;
import com.alibaba.nacos.core.paramcheck.ExtractorManager;
import com.alibaba.nacos.core.paramcheck.ParamCheckerFilter;
import com.alibaba.nacos.naming.controllers.InstanceController;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.internal.verification.Times;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
/**
* Param Naming ExtractorTest.
*
* @author 985492783@qq.com
* @date 2023/11/9 17:18
*/
@RunWith(MockitoJUnitRunner.class)
public class ParamExtractorTest {
@Mock
private ControllerMethodsCache methodsCache;
private ParamCheckerFilter filter;
@Test
public void testBatchUpdateFilter() throws Exception {
AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class,
"batchUpdateInstanceMetadata", HttpServletRequest.class);
assertEquals(httpExtractor.getClass(), NamingInstanceMetadataBatchHttpParamExtractor.class);
Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any());
}
@Test
public void testListFilter() throws Exception {
AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, "list",
HttpServletRequest.class);
assertEquals(httpExtractor.getClass(), NamingInstanceListHttpParamExtractor.class);
Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any());
}
@Test
public void testMetadataFilter() throws Exception {
AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class,
"batchDeleteInstanceMetadata", HttpServletRequest.class);
assertEquals(httpExtractor.getClass(), NamingInstanceMetadataBatchHttpParamExtractor.class);
Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any());
}
@Test
public void testDefaultFilter() throws Exception {
AbstractHttpParamExtractor httpExtractor = testExtractor(methodsCache, InstanceController.class, "register",
HttpServletRequest.class);
assertEquals(httpExtractor.getClass(), NamingDefaultHttpParamExtractor.class);
Mockito.verify(httpExtractor, new Times(1)).extractParam(Mockito.any());
}
/**
* Create mock method about AbstractHttpParamExtractor to verify.
* @param methodsCache methodsCache
* @param clazz clazz
* @param methodName methodName
* @param parameterTypes parameterTypes
* @return AbstractHttpParamExtractor
*/
public AbstractHttpParamExtractor testExtractor(ControllerMethodsCache methodsCache, Class<?> clazz,
String methodName, Class<?>... parameterTypes) throws NoSuchMethodException, ServletException, IOException {
MockedStatic<EnvUtil> mockedStatic = Mockito.mockStatic(EnvUtil.class);
final Method check = clazz.getMethod(methodName, parameterTypes);
ExtractorManager.Extractor annotation = check.getAnnotation(ExtractorManager.Extractor.class);
if (annotation == null) {
annotation = clazz.getAnnotation(ExtractorManager.Extractor.class);
}
AbstractHttpParamExtractor httpExtractor = Mockito.spy(ExtractorManager.getHttpExtractor(annotation));
MockedStatic<ExtractorManager> managerMockedStatic = Mockito.mockStatic(ExtractorManager.class);
mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any()))
.thenAnswer((k) -> k.getArgument(2));
ParamCheckerFilter filter = new ParamCheckerFilter(methodsCache);
ExtractorManager.Extractor finalAnnotation = annotation;
managerMockedStatic.when(() -> ExtractorManager.getHttpExtractor(finalAnnotation)).thenReturn(httpExtractor);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Mockito.when(methodsCache.getMethod(request)).thenReturn(check);
filter.doFilter(request, response, (servletRequest, servletResponse) -> {
});
managerMockedStatic.close();
mockedStatic.close();
return httpExtractor;
}
}

View File

@ -0,0 +1,62 @@
/*
* 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.naming.paramcheck;
import com.alibaba.nacos.api.naming.remote.request.InstanceRequest;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.core.remote.grpc.RemoteParamCheckFilter;
import com.alibaba.nacos.naming.remote.rpc.handler.InstanceRequestHandler;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* RpcParamCheckTest.
* @author 985492783@qq.com
* @date 2023/11/7 21:44
*/
@RunWith(MockitoJUnitRunner.class)
public class RpcParamCheckTest {
@Test
public void testFilter()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
MockedStatic<EnvUtil> mockedStatic = Mockito.mockStatic(EnvUtil.class);
mockedStatic.when(() -> EnvUtil.getProperty(Mockito.any(), Mockito.any(), Mockito.any()))
.thenAnswer((k) -> k.getArgument(2));
RemoteParamCheckFilter filter = new RemoteParamCheckFilter();
Method method = filter.getClass().getDeclaredMethod("filter", Request.class, RequestMeta.class, Class.class);
method.setAccessible(true);
InstanceRequest request = new InstanceRequest();
request.setNamespace("test111");
Response response = (Response) method.invoke(filter, request, null, InstanceRequestHandler.class);
assertNull(response);
request.setNamespace("test@@@");
Response response2 = (Response) method.invoke(filter, request, null, InstanceRequestHandler.class);
assertEquals(response2.getErrorCode(), 400);
mockedStatic.close();
}
}

View File

@ -180,7 +180,8 @@ public final class DiskUtils {
* @return content
*/
public static String readFile(File file) {
try (FileChannel fileChannel = new FileInputStream(file).getChannel()) {
try (FileInputStream fis = new FileInputStream(file);
FileChannel fileChannel = fis.getChannel()) {
StringBuilder text = new StringBuilder();
ByteBuffer buffer = ByteBuffer.allocate(4096);
CharBuffer charBuffer = CharBuffer.allocate(4096);
@ -230,7 +231,8 @@ public final class DiskUtils {
* @return write success
*/
public static boolean writeFile(File file, byte[] content, boolean append) {
try (FileChannel fileChannel = new FileOutputStream(file, append).getChannel()) {
try (FileOutputStream fos = new FileOutputStream(file, append);
FileChannel fileChannel = fos.getChannel()) {
ByteBuffer buffer = ByteBuffer.wrap(content);
fileChannel.write(buffer);
return true;