Skip to content

Commit

Permalink
Develop client ut (#11516)
Browse files Browse the repository at this point in the history
* Add ut for client module auth package.

* Add ut for client module env package.

* Add ut for client module env package.

* For copyright

* Fix UT might failed problem.
  • Loading branch information
KomachiSion committed Dec 18, 2023
1 parent d84a566 commit ab2ddac
Show file tree
Hide file tree
Showing 23 changed files with 946 additions and 146 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,6 @@ public void free() {

@Override
public Credentials getCredential() {
Credentials localCredential = credentials;
if (localCredential.valid()) {
return localCredential;
}
return credentials;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -59,8 +60,8 @@ public CredentialWatcher(String appName, CredentialService serviceInstance) {
this.serviceInstance = serviceInstance;
loadCredential(true);

executor = ExecutorFactory
.newSingleScheduledExecutorService(new NameThreadFactory("com.alibaba.nacos.client.auth.ram.identify.watcher"));
executor = ExecutorFactory.newSingleScheduledExecutorService(
new NameThreadFactory("com.alibaba.nacos.client.auth.ram.identify.watcher"));

executor.scheduleWithFixedDelay(new Runnable() {
private long modified = 0;
Expand Down Expand Up @@ -107,6 +108,94 @@ public void stop() {
}

private void loadCredential(boolean init) {
loadPropertyPath(init);
InputStream propertiesIS = loadPropertyPathToStream();
Credentials credentials = new Credentials();
boolean loadResult = Objects.isNull(propertiesIS) ? loadCredentialFromEnv(init, credentials)
: loadCredentialFromProperties(propertiesIS, init, credentials);
if (!loadResult) {
return;
}
if (!credentials.valid()) {
SPAS_LOGGER
.warn("[1] Credential file missing required property {} Credential file missing {} or {}", appName,
IdentifyConstants.ACCESS_KEY, IdentifyConstants.SECRET_KEY);
propertyPath = null;
// return;
}
serviceInstance.setCredential(credentials);
}

private boolean loadCredentialFromProperties(InputStream propertiesIS, boolean init, Credentials credentials) {
Properties properties = new Properties();
try {
properties.load(propertiesIS);
} catch (IOException e) {
SPAS_LOGGER
.error("[26] Unable to load credential file, appName:" + appName + "Unable to load credential file "
+ propertyPath, e);
propertyPath = null;
return false;
} finally {
try {
propertiesIS.close();
} catch (IOException e) {
SPAS_LOGGER.error("[27] Unable to close credential file, appName:" + appName
+ "Unable to close credential file " + propertyPath, e);
}
}

if (init) {
SPAS_LOGGER.info("[{}] Load credential file {}", appName, propertyPath);
}

String accessKey = null;
String secretKey = null;
String tenantId = null;
if (!IdentifyConstants.DOCKER_CREDENTIAL_PATH.equals(propertyPath)) {
if (properties.containsKey(IdentifyConstants.ACCESS_KEY)) {
accessKey = properties.getProperty(IdentifyConstants.ACCESS_KEY);
}
if (properties.containsKey(IdentifyConstants.SECRET_KEY)) {
secretKey = properties.getProperty(IdentifyConstants.SECRET_KEY);
}
if (properties.containsKey(IdentifyConstants.TENANT_ID)) {
tenantId = properties.getProperty(IdentifyConstants.TENANT_ID);
}
} else {
if (properties.containsKey(IdentifyConstants.DOCKER_ACCESS_KEY)) {
accessKey = properties.getProperty(IdentifyConstants.DOCKER_ACCESS_KEY);
}
if (properties.containsKey(IdentifyConstants.DOCKER_SECRET_KEY)) {
secretKey = properties.getProperty(IdentifyConstants.DOCKER_SECRET_KEY);
}

if (properties.containsKey(IdentifyConstants.DOCKER_TENANT_ID)) {
tenantId = properties.getProperty(IdentifyConstants.DOCKER_TENANT_ID);
}
}
setAccessKey(credentials, accessKey);
setSecretKey(credentials, secretKey);
setTenantId(credentials, tenantId);
return true;
}

private boolean loadCredentialFromEnv(boolean init, Credentials credentials) {
propertyPath = null;
String accessKey = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.ENV_ACCESS_KEY);
String secretKey = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.ENV_SECRET_KEY);
if (accessKey == null && secretKey == null) {
if (init) {
SPAS_LOGGER.info("{} No credential found", appName);
}
return false;
}
setAccessKey(credentials, accessKey);
setSecretKey(credentials, secretKey);
return true;
}

private void loadPropertyPath(boolean init) {
if (propertyPath == null) {
URL url = ClassLoader.getSystemResource(IdentifyConstants.PROPERTIES_FILENAME);
if (url != null) {
Expand Down Expand Up @@ -134,7 +223,9 @@ private void loadCredential(boolean init) {
}
}
}

}

private InputStream loadPropertyPathToStream() {
InputStream propertiesIS = null;
do {
try {
Expand All @@ -152,86 +243,24 @@ private void loadCredential(boolean init) {
}
break;
} while (true);

String accessKey = null;
String secretKey = null;
String tenantId = null;
if (propertiesIS == null) {
propertyPath = null;
accessKey = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.ENV_ACCESS_KEY);
secretKey = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.ENV_SECRET_KEY);
if (accessKey == null && secretKey == null) {
if (init) {
SPAS_LOGGER.info("{} No credential found", appName);
}
return;
}
} else {
Properties properties = new Properties();
try {
properties.load(propertiesIS);
} catch (IOException e) {
SPAS_LOGGER.error("[26] Unable to load credential file, appName:" + appName
+ "Unable to load credential file " + propertyPath, e);
propertyPath = null;
return;
} finally {
try {
propertiesIS.close();
} catch (IOException e) {
SPAS_LOGGER.error("[27] Unable to close credential file, appName:" + appName
+ "Unable to close credential file " + propertyPath, e);
}
}

if (init) {
SPAS_LOGGER.info("[{}] Load credential file {}", appName, propertyPath);
}

if (!IdentifyConstants.DOCKER_CREDENTIAL_PATH.equals(propertyPath)) {
if (properties.containsKey(IdentifyConstants.ACCESS_KEY)) {
accessKey = properties.getProperty(IdentifyConstants.ACCESS_KEY);
}
if (properties.containsKey(IdentifyConstants.SECRET_KEY)) {
secretKey = properties.getProperty(IdentifyConstants.SECRET_KEY);
}
if (properties.containsKey(IdentifyConstants.TENANT_ID)) {
tenantId = properties.getProperty(IdentifyConstants.TENANT_ID);
}
} else {
if (properties.containsKey(IdentifyConstants.DOCKER_ACCESS_KEY)) {
accessKey = properties.getProperty(IdentifyConstants.DOCKER_ACCESS_KEY);
}
if (properties.containsKey(IdentifyConstants.DOCKER_SECRET_KEY)) {
secretKey = properties.getProperty(IdentifyConstants.DOCKER_SECRET_KEY);
}

if (properties.containsKey(IdentifyConstants.DOCKER_TENANT_ID)) {
tenantId = properties.getProperty(IdentifyConstants.DOCKER_TENANT_ID);
}
}
}

if (accessKey != null) {
accessKey = accessKey.trim();
}
if (secretKey != null) {
secretKey = secretKey.trim();
return propertiesIS;
}

private void setAccessKey(Credentials credentials, String accessKey) {
if (!Objects.isNull(accessKey)) {
credentials.setAccessKey(accessKey.trim());
}

if (tenantId != null) {
tenantId = tenantId.trim();
}

private void setSecretKey(Credentials credentials, String secretKey) {
if (!Objects.isNull(secretKey)) {
credentials.setSecretKey(secretKey.trim());
}

Credentials credential = new Credentials(accessKey, secretKey, tenantId);
if (!credential.valid()) {
SPAS_LOGGER
.warn("[1] Credential file missing required property {} Credential file missing {} or {}", appName,
IdentifyConstants.ACCESS_KEY, IdentifyConstants.SECRET_KEY);
propertyPath = null;
// return;
}

private void setTenantId(Credentials credentials, String tenantId) {
if (!Objects.isNull(tenantId)) {
credentials.setTenantId(tenantId.trim());
}

serviceInstance.setCredential(credential);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,16 @@ public class Credentials implements SpasCredential {

private volatile String tenantId;

public Credentials() {
this(null, null, null);
}

public Credentials(String accessKey, String secretKey, String tenantId) {
this.accessKey = accessKey;
this.secretKey = secretKey;
this.tenantId = tenantId;
}

public Credentials() {
this(null, null, null);
}

@Override
public String getAccessKey() {
return accessKey;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static String sign(String data, String key) throws Exception {
}
}

private static byte[] sign(byte[] data, byte[] key, SignUtil.SigningAlgorithm algorithm) throws Exception {
static byte[] sign(byte[] data, byte[] key, SignUtil.SigningAlgorithm algorithm) throws Exception {
try {
Mac mac = Mac.getInstance(algorithm.toString());
mac.init(new SecretKeySpec(key, algorithm.toString()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ class SearchableProperties implements NacosClientProperties {
private static final CompositeConverter CONVERTER = new CompositeConverter();

static {
SEARCH_ORDER = init();
StringBuilder orderInfo = new StringBuilder("properties search order:");
for (int i = 0; i < SEARCH_ORDER.size(); i++) {
orderInfo.append(SEARCH_ORDER.get(i).toString());
if (i < SEARCH_ORDER.size() - 1) {
orderInfo.append("->");
}
}
LOGGER.debug(orderInfo.toString());
}

private static List<SourceType> init() {
List<SourceType> initOrder = Arrays.asList(SourceType.PROPERTIES, SourceType.JVM, SourceType.ENV);

String firstEnv = JVM_ARGS_PROPERTY_SOURCE.getProperty(Constants.SysEnv.NACOS_ENV_FIRST);
Expand All @@ -67,15 +79,7 @@ class SearchableProperties implements NacosClientProperties {
LOGGER.warn("first source type parse error, it will be used default order!", e);
}
}
SEARCH_ORDER = initOrder;
StringBuilder orderInfo = new StringBuilder("properties search order:");
for (int i = 0; i < SEARCH_ORDER.size(); i++) {
orderInfo.append(SEARCH_ORDER.get(i).toString());
if (i < SEARCH_ORDER.size() - 1) {
orderInfo.append("->");
}
}
LOGGER.debug(orderInfo.toString());
return initOrder;
}

static final SearchableProperties INSTANCE = new SearchableProperties();
Expand Down Expand Up @@ -183,21 +187,11 @@ public boolean containsKey(String key) {
}

private <T> Optional<T> search(String key, Class<T> targetType) {
if (targetType == null) {
throw new IllegalArgumentException("target type must not be null!");
}

for (AbstractPropertySource propertySource : propertySources) {
final String value = propertySource.getProperty(key);
if (value != null) {
if (String.class.isAssignableFrom(targetType)) {
try {
return (Optional<T>) Optional.of(value);
} catch (Exception e) {
LOGGER.error("target type convert error", e);
return Optional.empty();
}

if (targetType.isAssignableFrom(String.class)) {
return (Optional<T>) Optional.of(value);
}
return Optional.ofNullable(CONVERTER.convert(value, targetType));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,9 @@ public enum SourceType {
/**
* get value from system environment.
*/
ENV
ENV,
/**
* get value from unknown environment, will be search in all properties by orders.
*/
UNKNOWN
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* 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.client.ability;

import com.alibaba.nacos.api.ability.constant.AbilityKey;
import com.alibaba.nacos.api.ability.constant.AbilityMode;
import org.junit.Before;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class ClientAbilityControlManagerTest {

ClientAbilityControlManager clientAbilityControlManager;

@Before
public void setUp() {
clientAbilityControlManager = new ClientAbilityControlManager();
}

@Test
public void testInitCurrentNodeAbilities() {
Map<AbilityMode, Map<AbilityKey, Boolean>> actual = clientAbilityControlManager.initCurrentNodeAbilities();
assertEquals(1, actual.size());
assertTrue(actual.containsKey(AbilityMode.SDK_CLIENT));
// Current not define sdk ability.
assertEquals(0, actual.get(AbilityMode.SDK_CLIENT).size());
}

@Test
public void testGetPriority() {
assertEquals(0, clientAbilityControlManager.getPriority());
}
}
Loading

0 comments on commit ab2ddac

Please sign in to comment.