提交 23a24c44 编写于 作者: L laohu

Seamless cloud

上级 87d85991
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for additional
information regarding copyright ownership. The ASF licenses this file to
You under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for additional
information regarding copyright ownership. The ASF licenses this file to
You under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License. -->
<project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.rocketmq</groupId>
......@@ -50,5 +49,17 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>1.7.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.common;
import org.apache.rocketmq.remoting.CommandCustomHeader;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import java.lang.reflect.Field;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.rocketmq.remoting.CommandCustomHeader;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import static org.apache.rocketmq.acl.common.SessionCredentials.AccessKey;
import static org.apache.rocketmq.acl.common.SessionCredentials.SecurityToken;
import static org.apache.rocketmq.acl.common.SessionCredentials.Signature;
public class AclClientRPCHook implements RPCHook {
protected ConcurrentHashMap<Class<? extends CommandCustomHeader>, Field[]> fieldCache =
new ConcurrentHashMap<Class<? extends CommandCustomHeader>, Field[]>();
private final SessionCredentials sessionCredentials;
protected ConcurrentHashMap<Class<? extends CommandCustomHeader>, Field[]> fieldCache =
new ConcurrentHashMap<Class<? extends CommandCustomHeader>, Field[]>();
public AclClientRPCHook(SessionCredentials sessionCredentials) {
this.sessionCredentials = sessionCredentials;
......@@ -37,7 +50,6 @@ public class AclClientRPCHook implements RPCHook {
}
}
@Override
public void doAfterResponse(String remoteAddr, RemotingCommand request, RemotingCommand response) {
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.common;
public class AclException extends RuntimeException {
......@@ -6,27 +22,31 @@ public class AclException extends RuntimeException {
private String status;
private int code;
public AclException(String status, int code) {
super();
this.status = status;
this.code = code;
}
public AclException(String status, int code, String message) {
super(message);
this.status = status;
this.code = code;
}
public AclException(String status, int code, Throwable throwable) {
super(throwable);
this.status = status;
this.code = code;
}
public AclException(String message) {
super(message);
}
public AclException(String message, Throwable throwable) {
super(message, throwable);
}
public AclException(String status, int code, String message, Throwable throwable) {
super(message, throwable);
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.common;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.logging.InternalLoggerFactory;
import java.nio.charset.Charset;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.logging.InternalLoggerFactory;
public class AclSigner {
public static final Charset defaultCharset = Charset.forName("UTF-8");
......@@ -20,12 +35,13 @@ public class AclSigner {
return calSignature(data, key, defaultAlgorithm, defaultCharset);
}
public static String calSignature(String data, String key, SigningAlgorithm algorithm, Charset charset) throws AclException {
public static String calSignature(String data, String key, SigningAlgorithm algorithm,
Charset charset) throws AclException {
return signAndBase64Encode(data, key, algorithm, charset);
}
private static String signAndBase64Encode(String data, String key, SigningAlgorithm algorithm, Charset charset)
throws AclException {
throws AclException {
try {
byte[] signature = sign(data.getBytes(charset), key.getBytes(charset), algorithm);
return new String(Base64.encodeBase64(signature), defaultCharset);
......@@ -52,12 +68,13 @@ public class AclSigner {
return calSignature(data, key, defaultAlgorithm, defaultCharset);
}
public static String calSignature(byte[] data, String key, SigningAlgorithm algorithm, Charset charset) throws AclException {
public static String calSignature(byte[] data, String key, SigningAlgorithm algorithm,
Charset charset) throws AclException {
return signAndBase64Encode(data, key, algorithm, charset);
}
private static String signAndBase64Encode(byte[] data, String key, SigningAlgorithm algorithm, Charset charset)
throws AclException {
throws AclException {
try {
byte[] signature = sign(data, key.getBytes(charset), algorithm);
return new String(Base64.encodeBase64(signature), defaultCharset);
......
......@@ -22,7 +22,6 @@ import java.io.IOException;
import java.util.Map;
import java.util.SortedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.acl.plain.AclPlugRuntimeException;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.yaml.snakeyaml.Yaml;
......@@ -45,7 +44,6 @@ public class AclUtils {
}
}
public static byte[] combineBytes(byte[] b1, byte[] b2) {
int size = (null != b1 ? b1.length : 0) + (null != b2 ? b2.length : 0);
byte[] total = new byte[size];
......@@ -56,7 +54,6 @@ public class AclUtils {
return total;
}
public static String calSignature(byte[] data, String secretKey) {
String signature = AclSigner.calSignature(data, secretKey);
return signature;
......@@ -64,7 +61,7 @@ public class AclUtils {
public static void verify(String netaddress, int index) {
if (!AclUtils.isScope(netaddress, index)) {
throw new AclPlugRuntimeException(String.format("netaddress examine scope Exception netaddress is %s", netaddress));
throw new AclException(String.format("netaddress examine scope Exception netaddress is %s", netaddress));
}
}
......@@ -128,15 +125,16 @@ public class AclUtils {
fis = new FileInputStream(new File(path));
return ymal.loadAs(fis, clazz);
} catch (Exception e) {
throw new AclPlugRuntimeException(String.format("The transport.yml file for Plain mode was not found , paths %s", path), e);
throw new AclException(String.format("The file for Plain mode was not found , paths %s", path), e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
throw new AclPlugRuntimeException("close transport fileInputStream Exception", e);
throw new AclException("close transport fileInputStream Exception", e);
}
}
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.common;
import com.alibaba.fastjson.JSONArray;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.acl.plain.PlainAccessResource;
public class Permission {
public static final byte DENY = 1;
......@@ -7,7 +29,22 @@ public class Permission {
public static final byte PUB = 1 << 2;
public static final byte SUB = 1 << 3;
public boolean checkPermission(byte neededPerm, byte ownedPerm) {
public static final Set<Integer> ADMIN_CODE = new HashSet<Integer>();
static {
// UPDATE_AND_CREATE_TOPIC
ADMIN_CODE.add(17);
// UPDATE_BROKER_CONFIG
ADMIN_CODE.add(25);
// DELETE_TOPIC_IN_BROKER
ADMIN_CODE.add(215);
// UPDATE_AND_CREATE_SUBSCRIPTIONGROUP
ADMIN_CODE.add(200);
// DELETE_SUBSCRIPTIONGROUP
ADMIN_CODE.add(207);
}
public static boolean checkPermission(byte neededPerm, byte ownedPerm) {
if ((ownedPerm & DENY) > 0) {
return false;
}
......@@ -17,4 +54,43 @@ public class Permission {
return (neededPerm & ownedPerm) > 0;
}
public static byte fromStringGetPermission(String permString) {
if (permString == null) {
return Permission.DENY;
}
switch (permString.trim()) {
case "PUB":
return Permission.PUB;
case "SUB":
return Permission.SUB;
case "ANY":
return Permission.ANY;
case "PUB|SUB":
return Permission.ANY;
case "SUB|PUB":
return Permission.ANY;
case "DENY":
return Permission.DENY;
default:
return Permission.DENY;
}
}
public static void setTopicPerm(PlainAccessResource plainAccessResource, Boolean isTopic, JSONArray topicArray) {
if (topicArray == null || topicArray.isEmpty()) {
return;
}
for (int i = 0; i < topicArray.size(); i++) {
String[] topicPrem = StringUtils.split(topicArray.getString(i), "=");
if (topicPrem.length == 2) {
plainAccessResource.addResourceAndPerm(isTopic ? topicPrem[0] : PlainAccessResource.getRetryTopic(topicPrem[0]), fromStringGetPermission(topicPrem[1]));
} else {
throw new AclException(String.format("%s Permission config erron %s", isTopic ? "topic" : "group", topicArray.getString(i)));
}
}
}
public static boolean checkAdminCode(Integer code) {
return ADMIN_CODE.contains(code);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.common;
import org.apache.rocketmq.common.MixAll;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Properties;
import org.apache.rocketmq.common.MixAll;
public class SessionCredentials {
public static final Charset CHARSET = Charset.forName("UTF-8");
......@@ -45,7 +61,6 @@ public class SessionCredentials {
this.securityToken = securityToken;
}
public void updateContent(Properties prop) {
{
String value = prop.getProperty(AccessKey);
......@@ -99,8 +114,6 @@ public class SessionCredentials {
this.securityToken = securityToken;
}
@Override
public int hashCode() {
final int prime = 31;
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.common;//package com.aliyun.openservices.ons.api.impl.rocketmq.spas;
public enum SigningAlgorithm {
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.plain;
/**
* Use AclException instead
*/
@Deprecated
public class AclPlugRuntimeException extends RuntimeException {
private static final long serialVersionUID = 6062101368637228900L;
public AclPlugRuntimeException(String message) {
super(message);
}
public AclPlugRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.plain;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
@Deprecated
public class AuthenticationInfo {
private PlainAccessResource plainAccessResource;
private RemoteAddressStrategy remoteAddressStrategy;
private Map<Integer, Boolean> authority;
public AuthenticationInfo(Map<Integer, Boolean> authority, PlainAccessResource plainAccessResource,
RemoteAddressStrategy remoteAddressStrategy) {
super();
this.authority = authority;
this.plainAccessResource = plainAccessResource;
this.remoteAddressStrategy = remoteAddressStrategy;
}
public PlainAccessResource getPlainAccessResource() {
return plainAccessResource;
}
public void setPlainAccessResource(PlainAccessResource plainAccessResource) {
this.plainAccessResource = plainAccessResource;
}
public RemoteAddressStrategy getRemoteAddressStrategy() {
return remoteAddressStrategy;
}
public void setRemoteAddressStrategy(RemoteAddressStrategy remoteAddressStrategy) {
this.remoteAddressStrategy = remoteAddressStrategy;
}
public Map<Integer, Boolean> getAuthority() {
return authority;
}
public void setAuthority(Map<Integer, Boolean> authority) {
this.authority = authority;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AuthenticationInfo [plainAccessResource=").append(plainAccessResource).append(", remoteAddressStrategy=")
.append(remoteAddressStrategy).append(", authority={");
Iterator<Entry<Integer, Boolean>> it = authority.entrySet().iterator();
while (it.hasNext()) {
Entry<Integer, Boolean> e = it.next();
if (!e.getValue()) {
builder.append(e.getKey().toString()).append(":").append(e.getValue()).append(",");
}
}
builder.append("}]");
return builder.toString();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.plain;
@Deprecated
public class AuthenticationResult {
private PlainAccessResource plainAccessResource;
private boolean succeed;
private Exception exception;
private String resultString;
public PlainAccessResource getPlainAccessResource() {
return plainAccessResource;
}
public void setPlainAccessResource(PlainAccessResource plainAccessResource) {
this.plainAccessResource = plainAccessResource;
}
public boolean isSucceed() {
return succeed;
}
public void setSucceed(boolean succeed) {
this.succeed = succeed;
}
public Exception getException() {
return exception;
}
public void setException(Exception exception) {
this.exception = exception;
}
public String getResultString() {
return resultString;
}
public void setResultString(String resultString) {
this.resultString = resultString;
}
}
......@@ -23,34 +23,56 @@ import org.apache.rocketmq.acl.AccessResource;
import org.apache.rocketmq.common.MixAll;
public class PlainAccessResource implements AccessResource {
//identify the user
private String accessKey;
private String signature;
//the content to calculate the content
private byte[] content;
private String secretKey;
private String secretToken;
private String whiteRemoteAddress;
private Map<String, Byte> resourcePermMap = new HashMap<>();
private boolean admin;
private String remoteAddr;
private byte defaultTopicPerm = 1;
private String recognition;
private byte defaultGroupPerm = 1;
private Map<String, Byte> resourcePermMap;
private RemoteAddressStrategy remoteAddressStrategy;
private int requestCode;
//the content to calculate the content
private byte[] content;
private String signature;
@Deprecated
private String topic;
private String secretToken;
private String recognition;
public PlainAccessResource() {
}
public static boolean isRetryTopic(String topic) {
return (null != topic && topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX));
}
public static String getRetryTopic(String group) {
if (group == null) {
return null;
}
return MixAll.getRetryTopic(group);
}
public void addResourceAndPerm(String resource, byte perm) {
if (resource == null) {
return;
}
if (resourcePermMap == null) {
resourcePermMap = new HashMap<>();
}
resourcePermMap.put(resource, perm);
}
......@@ -62,20 +84,48 @@ public class PlainAccessResource implements AccessResource {
this.accessKey = accessKey;
}
public String getSignature() {
return signature;
public String getSecretKey() {
return secretKey;
}
public void setSignature(String signature) {
this.signature = signature;
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getWhiteRemoteAddress() {
return whiteRemoteAddress;
}
public void setWhiteRemoteAddress(String whiteRemoteAddress) {
this.whiteRemoteAddress = whiteRemoteAddress;
}
public String getRemoteAddr() {
return remoteAddr;
public boolean isAdmin() {
return admin;
}
public void setRemoteAddr(String remoteAddr) {
this.remoteAddr = remoteAddr;
public void setAdmin(boolean admin) {
this.admin = admin;
}
public byte getDefaultTopicPerm() {
return defaultTopicPerm;
}
public void setDefaultTopicPerm(byte defaultTopicPerm) {
this.defaultTopicPerm = defaultTopicPerm;
}
public byte getDefaultGroupPerm() {
return defaultGroupPerm;
}
public void setDefaultGroupPerm(byte defaultGroupPerm) {
this.defaultGroupPerm = defaultGroupPerm;
}
public Map<String, Byte> getResourcePermMap() {
return resourcePermMap;
}
public String getRecognition() {
......@@ -94,14 +144,6 @@ public class PlainAccessResource implements AccessResource {
this.requestCode = requestCode;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getSecretToken() {
return secretToken;
}
......@@ -110,21 +152,25 @@ public class PlainAccessResource implements AccessResource {
this.secretToken = secretToken;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
public RemoteAddressStrategy getRemoteAddressStrategy() {
return remoteAddressStrategy;
}
public void setRemoteAddressStrategy(RemoteAddressStrategy remoteAddressStrategy) {
this.remoteAddressStrategy = remoteAddressStrategy;
}
public static boolean isRetryTopic(String topic) {
return (null != topic && topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX));
public String getSignature() {
return signature;
}
public static String getRetryTopic(String group) {
if (group == null) {
return null;
}
return MixAll.getRetryTopic(group);
public void setSignature(String signature) {
this.signature = signature;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public byte[] getContent() {
......
......@@ -21,8 +21,8 @@ import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.rocketmq.acl.AccessResource;
import org.apache.rocketmq.acl.AccessValidator;
import org.apache.rocketmq.acl.common.AclUtils;
import org.apache.rocketmq.acl.common.AclException;
import org.apache.rocketmq.acl.common.AclUtils;
import org.apache.rocketmq.acl.common.Permission;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.common.protocol.RequestCode;
......@@ -47,7 +47,7 @@ public class PlainAccessValidator implements AccessValidator {
@Override
public AccessResource parse(RemotingCommand request, String remoteAddr) {
PlainAccessResource accessResource = new PlainAccessResource();
accessResource.setRemoteAddr(remoteAddr);
accessResource.setWhiteRemoteAddress(remoteAddr);
accessResource.setRequestCode(request.getCode());
accessResource.setAccessKey(request.getExtFields().get(SessionCredentials.AccessKey));
accessResource.setSignature(request.getExtFields().get(SessionCredentials.Signature));
......@@ -77,7 +77,7 @@ public class PlainAccessValidator implements AccessValidator {
HeartbeatData heartbeatData = HeartbeatData.decode(request.getBody(), HeartbeatData.class);
for (ConsumerData data : heartbeatData.getConsumerDataSet()) {
accessResource.addResourceAndPerm(getRetryTopic(data.getGroupName()), Permission.SUB);
for (SubscriptionData subscriptionData: data.getSubscriptionDataSet()) {
for (SubscriptionData subscriptionData : data.getSubscriptionDataSet()) {
accessResource.addResourceAndPerm(subscriptionData.getTopic(), Permission.SUB);
}
}
......@@ -106,10 +106,8 @@ public class PlainAccessValidator implements AccessValidator {
}
} catch (Throwable t) {
throw new AclException(t.getMessage(), -1, t);
throw new AclException(t.getMessage(), t);
}
// content
SortedMap<String, String> map = new TreeMap<String, String>();
for (Map.Entry<String, String> entry : request.getExtFields().entrySet()) {
......@@ -118,26 +116,12 @@ public class PlainAccessValidator implements AccessValidator {
}
}
accessResource.setContent(AclUtils.combineRequestContent(request, map));
return accessResource;
}
@Override
public void validate(AccessResource accessResource) {
AuthenticationResult authenticationResult = null;
try {
authenticationResult = aclPlugEngine.eachCheckAuthentication((PlainAccessResource) accessResource);
if (authenticationResult.isSucceed())
return;
} catch (Exception e) {
throw new AclPlugRuntimeException(String.format("validate exception AccessResource data %s", accessResource.toString()), e);
}
if (authenticationResult.getException() != null) {
throw new AclPlugRuntimeException(String.format("eachCheck the inspection appear exception, accessControl data is %s", accessResource.toString()), authenticationResult.getException());
}
if (authenticationResult.getPlainAccessResource() != null || !authenticationResult.isSucceed()) {
throw new AclPlugRuntimeException(String.format("%s accessControl data is %s", authenticationResult.getResultString(), accessResource.toString()));
}
aclPlugEngine.eachCheckPlainAccessResource((PlainAccessResource) accessResource);
}
}
......@@ -19,6 +19,7 @@ package org.apache.rocketmq.acl.plain;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.acl.common.AclException;
import org.apache.rocketmq.acl.common.AclUtils;
public class RemoteAddressStrategyFactory {
......@@ -26,7 +27,11 @@ public class RemoteAddressStrategyFactory {
public static final NullRemoteAddressStrategy NULL_NET_ADDRESS_STRATEGY = new NullRemoteAddressStrategy();
public RemoteAddressStrategy getNetaddressStrategy(PlainAccessResource plainAccessResource) {
String netaddress = plainAccessResource.getRemoteAddr();
return getNetaddressStrategy(plainAccessResource.getWhiteRemoteAddress());
}
public RemoteAddressStrategy getNetaddressStrategy(String netaddress) {
if (StringUtils.isBlank(netaddress) || "*".equals(netaddress)) {
return NULL_NET_ADDRESS_STRATEGY;
}
......@@ -34,7 +39,7 @@ public class RemoteAddressStrategyFactory {
String[] strArray = StringUtils.split(netaddress, ".");
String four = strArray[3];
if (!four.startsWith("{")) {
throw new AclPlugRuntimeException(String.format("MultipleRemoteAddressStrategy netaddress examine scope Exception netaddress", netaddress));
throw new AclException(String.format("MultipleRemoteAddressStrategy netaddress examine scope Exception netaddress", netaddress));
}
return new MultipleRemoteAddressStrategy(AclUtils.getAddreeStrArray(netaddress, four));
} else if (AclUtils.isColon(netaddress)) {
......@@ -67,7 +72,7 @@ public class RemoteAddressStrategyFactory {
@Override
public boolean match(PlainAccessResource plainAccessResource) {
return multipleSet.contains(plainAccessResource.getRemoteAddr());
return multipleSet.contains(plainAccessResource.getWhiteRemoteAddress());
}
}
......@@ -83,7 +88,7 @@ public class RemoteAddressStrategyFactory {
@Override
public boolean match(PlainAccessResource plainAccessResource) {
return netaddress.equals(plainAccessResource.getRemoteAddr());
return netaddress.equals(plainAccessResource.getWhiteRemoteAddress());
}
}
......@@ -117,14 +122,14 @@ public class RemoteAddressStrategyFactory {
setValue(0, 255);
} else if (AclUtils.isMinus(value)) {
if (value.indexOf("-") == 0) {
throw new AclPlugRuntimeException(String.format("RangeRemoteAddressStrategy netaddress examine scope Exception value %s ", value));
throw new AclException(String.format("RangeRemoteAddressStrategy netaddress examine scope Exception value %s ", value));
}
String[] valueArray = StringUtils.split(value, "-");
this.start = Integer.valueOf(valueArray[0]);
this.end = Integer.valueOf(valueArray[1]);
if (!(AclUtils.isScope(end) && AclUtils.isScope(start) && start <= end)) {
throw new AclPlugRuntimeException(String.format("RangeRemoteAddressStrategy netaddress examine scope Exception start is %s , end is %s", start, end));
throw new AclException(String.format("RangeRemoteAddressStrategy netaddress examine scope Exception start is %s , end is %s", start, end));
}
}
return this.end > 0 ? true : false;
......@@ -137,7 +142,7 @@ public class RemoteAddressStrategyFactory {
@Override
public boolean match(PlainAccessResource plainAccessResource) {
String netAddress = plainAccessResource.getRemoteAddr();
String netAddress = plainAccessResource.getWhiteRemoteAddress();
if (netAddress.startsWith(this.head)) {
String value;
if (index == 3) {
......
......@@ -14,12 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.plain;
package org.apache.rocketmq.acl.common;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.acl.common.AclUtils;
import org.junit.Assert;
import org.junit.Test;
......@@ -125,7 +125,17 @@ public class AclUtilsTest {
Assert.assertFalse(isMinus);
}
@SuppressWarnings("unchecked")
@Test
public void getYamlDataObjectTest() {
Map<String, Object> map = AclUtils.getYamlDataObject("src/test/resources/conf/transport.yml", Map.class);
Assert.assertFalse(map.isEmpty());
}
@Test(expected = Exception.class)
public void getYamlDataObjectExceptionTest() {
AclUtils.getYamlDataObject("transport.yml", Map.class);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.common;
import com.alibaba.fastjson.JSONArray;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.rocketmq.acl.plain.PlainAccessResource;
import org.junit.Assert;
import org.junit.Test;
public class PermissionTest {
@Test
public void fromStringGetPermissionTest() {
byte perm = Permission.fromStringGetPermission("PUB");
Assert.assertEquals(perm, Permission.PUB);
perm = Permission.fromStringGetPermission("SUB");
Assert.assertEquals(perm, Permission.SUB);
perm = Permission.fromStringGetPermission("ANY");
Assert.assertEquals(perm, Permission.ANY);
perm = Permission.fromStringGetPermission("PUB|SUB");
Assert.assertEquals(perm, Permission.ANY);
perm = Permission.fromStringGetPermission("SUB|PUB");
Assert.assertEquals(perm, Permission.ANY);
perm = Permission.fromStringGetPermission("DENY");
Assert.assertEquals(perm, Permission.DENY);
perm = Permission.fromStringGetPermission("1");
Assert.assertEquals(perm, Permission.DENY);
perm = Permission.fromStringGetPermission(null);
Assert.assertEquals(perm, Permission.DENY);
}
@Test
public void checkPermissionTest() {
boolean boo = Permission.checkPermission(Permission.DENY, Permission.DENY);
Assert.assertFalse(boo);
boo = Permission.checkPermission(Permission.PUB, Permission.PUB);
Assert.assertTrue(boo);
boo = Permission.checkPermission(Permission.SUB, Permission.SUB);
Assert.assertTrue(boo);
boo = Permission.checkPermission(Permission.ANY, Permission.ANY);
Assert.assertFalse(boo);
boo = Permission.checkPermission(Permission.ANY, Permission.SUB);
Assert.assertTrue(boo);
boo = Permission.checkPermission(Permission.ANY, Permission.PUB);
Assert.assertTrue(boo);
boo = Permission.checkPermission(Permission.DENY, Permission.ANY);
Assert.assertFalse(boo);
boo = Permission.checkPermission(Permission.DENY, Permission.PUB);
Assert.assertFalse(boo);
boo = Permission.checkPermission(Permission.DENY, Permission.SUB);
Assert.assertFalse(boo);
}
@Test(expected = AclException.class)
public void setTopicPermTest() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
Map<String, Byte> resourcePermMap = plainAccessResource.getResourcePermMap();
Permission.setTopicPerm(plainAccessResource, false, null);
Assert.assertNull(resourcePermMap);
JSONArray groups = new JSONArray();
Permission.setTopicPerm(plainAccessResource, false, groups);
Assert.assertNull(resourcePermMap);
groups.add("groupA=DENY");
groups.add("groupB=PUB|SUB");
groups.add("groupC=PUB");
Permission.setTopicPerm(plainAccessResource, false, groups);
resourcePermMap = plainAccessResource.getResourcePermMap();
byte perm = resourcePermMap.get(PlainAccessResource.getRetryTopic("groupA"));
Assert.assertEquals(perm, Permission.DENY);
perm = resourcePermMap.get(PlainAccessResource.getRetryTopic("groupB"));
Assert.assertEquals(perm, Permission.ANY);
perm = resourcePermMap.get(PlainAccessResource.getRetryTopic("groupC"));
Assert.assertEquals(perm, Permission.PUB);
JSONArray topics = new JSONArray();
topics.add("topicA=DENY");
topics.add("topicB=PUB|SUB");
topics.add("topicC=PUB");
Permission.setTopicPerm(plainAccessResource, true, topics);
perm = resourcePermMap.get("topicA");
Assert.assertEquals(perm, Permission.DENY);
perm = resourcePermMap.get("topicB");
Assert.assertEquals(perm, Permission.ANY);
perm = resourcePermMap.get("topicC");
Assert.assertEquals(perm, Permission.PUB);
JSONArray erron = new JSONArray();
erron.add("");
Permission.setTopicPerm(plainAccessResource, false, erron);
}
@Test
public void checkAdminCodeTest() {
Set<Integer> code = new HashSet<>();
code.add(17);
code.add(25);
code.add(215);
code.add(200);
code.add(207);
for (int i = 0; i < 400; i++) {
boolean boo = Permission.checkAdminCode(i);
if (boo) {
Assert.assertTrue(code.contains(i));
}
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.plain;
import java.nio.ByteBuffer;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.AclUtils;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class PlainAccessValidatorTest {
PlainAccessValidator plainAccessValidator;
@Before
public void init() {
System.setProperty("rocketmq.home.dir", "src/test/resources");
plainAccessValidator = new PlainAccessValidator();
}
@Test
public void contentTest() {
SessionCredentials sessionCredentials = new SessionCredentials();
sessionCredentials.setAccessKey("RocketMQ");
sessionCredentials.setSecretKey("12345678");
sessionCredentials.setSecurityToken("87654321");
AclClientRPCHook aclClient = new AclClientRPCHook(sessionCredentials);
SendMessageRequestHeader messageRequestHeader = new SendMessageRequestHeader();
messageRequestHeader.setTopic("topicA");
RemotingCommand remotingCommand = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, messageRequestHeader);
aclClient.doBeforeRequest("", remotingCommand);
ByteBuffer buf = remotingCommand.encodeHeader();
buf.getInt();
buf = ByteBuffer.allocate(buf.limit() - buf.position()).put(buf);
buf.position(0);
PlainAccessResource accessResource = (PlainAccessResource) plainAccessValidator.parse(RemotingCommand.decode(buf), "127.0.0.1");
String signature = AclUtils.calSignature(accessResource.getContent(), sessionCredentials.getSecretKey());
Assert.assertEquals(accessResource.getSignature(), signature);
}
@Test
public void validateTest() {
SessionCredentials sessionCredentials = new SessionCredentials();
sessionCredentials.setAccessKey("RocketMQ");
sessionCredentials.setSecretKey("12345678");
sessionCredentials.setSecurityToken("87654321");
AclClientRPCHook aclClient = new AclClientRPCHook(sessionCredentials);
SendMessageRequestHeader messageRequestHeader = new SendMessageRequestHeader();
messageRequestHeader.setTopic("topicA");
RemotingCommand remotingCommand = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, messageRequestHeader);
aclClient.doBeforeRequest("", remotingCommand);
ByteBuffer buf = remotingCommand.encodeHeader();
buf.getInt();
buf = ByteBuffer.allocate(buf.limit() - buf.position()).put(buf);
buf.position(0);
PlainAccessResource accessResource = (PlainAccessResource) plainAccessValidator.parse(RemotingCommand.decode(buf), "192.168.0.1");
plainAccessValidator.validate(accessResource);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.plain;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.rocketmq.acl.plain.PlainPermissionLoader.AccessContralAnalysis;
import org.apache.rocketmq.acl.plain.PlainPermissionLoader.BrokerAccessControlTransport;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class PlainAclPlugEngineTest {
PlainPermissionLoader plainPermissionLoader;
AccessContralAnalysis accessContralAnalysis = new AccessContralAnalysis();
PlainAccessResource plainAccessResource;
PlainAccessResource plainAccessResourceTwo;
AuthenticationInfo authenticationInfo;
BrokerAccessControl brokerAccessControl;
Set<Integer> adminCode = new HashSet<>();
@Before
public void init() throws NoSuchFieldException, SecurityException, IOException {
// UPDATE_AND_CREATE_TOPIC
adminCode.add(17);
// UPDATE_BROKER_CONFIG
adminCode.add(25);
// DELETE_TOPIC_IN_BROKER
adminCode.add(215);
// UPDATE_AND_CREATE_SUBSCRIPTIONGROUP
adminCode.add(200);
// DELETE_SUBSCRIPTIONGROUP
adminCode.add(207);
accessContralAnalysis.analysisClass(RequestCode.class);
brokerAccessControl = new BrokerAccessControl();
// 321
brokerAccessControl.setQueryConsumeQueue(false);
Set<String> permitSendTopic = new HashSet<>();
permitSendTopic.add("permitSendTopic");
brokerAccessControl.setPermitSendTopic(permitSendTopic);
Set<String> noPermitSendTopic = new HashSet<>();
noPermitSendTopic.add("noPermitSendTopic");
brokerAccessControl.setNoPermitSendTopic(noPermitSendTopic);
Set<String> permitPullTopic = new HashSet<>();
permitPullTopic.add("permitPullTopic");
brokerAccessControl.setPermitPullTopic(permitPullTopic);
Set<String> noPermitPullTopic = new HashSet<>();
noPermitPullTopic.add("noPermitPullTopic");
brokerAccessControl.setNoPermitPullTopic(noPermitPullTopic);
AccessContralAnalysis accessContralAnalysis = new AccessContralAnalysis();
accessContralAnalysis.analysisClass(RequestCode.class);
Map<Integer, Boolean> map = accessContralAnalysis.analysis(brokerAccessControl);
authenticationInfo = new AuthenticationInfo(map, brokerAccessControl, RemoteAddressStrategyFactory.NULL_NET_ADDRESS_STRATEGY);
System.setProperty("rocketmq.home.dir", "src/test/resources");
plainPermissionLoader = new PlainPermissionLoader();
plainAccessResource = new BrokerAccessControl();
plainAccessResource.setAccessKey("rokcetmq");
plainAccessResource.setSignature("aliyun11");
plainAccessResource.setRemoteAddr("127.0.0.1");
plainAccessResource.setRecognition("127.0.0.1:1");
plainAccessResourceTwo = new BrokerAccessControl();
plainAccessResourceTwo.setAccessKey("rokcet1");
plainAccessResourceTwo.setSignature("aliyun1");
plainAccessResourceTwo.setRemoteAddr("127.0.0.1");
plainAccessResourceTwo.setRecognition("127.0.0.1:2");
}
@Test(expected = AclPlugRuntimeException.class)
public void accountNullTest() {
plainAccessResource.setAccessKey(null);
plainPermissionLoader.setAccessControl(plainAccessResource);
}
@Test(expected = AclPlugRuntimeException.class)
public void accountThanTest() {
plainAccessResource.setAccessKey("123");
plainPermissionLoader.setAccessControl(plainAccessResource);
}
@Test(expected = AclPlugRuntimeException.class)
public void passWordtNullTest() {
plainAccessResource.setAccessKey(null);
plainPermissionLoader.setAccessControl(plainAccessResource);
}
@Test(expected = AclPlugRuntimeException.class)
public void passWordThanTest() {
plainAccessResource.setAccessKey("123");
plainPermissionLoader.setAccessControl(plainAccessResource);
}
@Test(expected = AclPlugRuntimeException.class)
public void testPlainAclPlugEngineInit() {
System.setProperty("rocketmq.home.dir", "");
new PlainPermissionLoader().initialize();
}
@Test
public void authenticationInfoOfSetAccessControl() {
plainPermissionLoader.setAccessControl(plainAccessResource);
AuthenticationInfo authenticationInfo = plainPermissionLoader.getAccessControl(plainAccessResource);
PlainAccessResource getPlainAccessResource = authenticationInfo.getPlainAccessResource();
Assert.assertEquals(plainAccessResource, getPlainAccessResource);
PlainAccessResource testPlainAccessResource = new PlainAccessResource();
testPlainAccessResource.setAccessKey("rokcetmq");
testPlainAccessResource.setSignature("aliyun11");
testPlainAccessResource.setRemoteAddr("127.0.0.1");
testPlainAccessResource.setRecognition("127.0.0.1:1");
testPlainAccessResource.setAccessKey("rokcetmq1");
authenticationInfo = plainPermissionLoader.getAccessControl(testPlainAccessResource);
Assert.assertNull(authenticationInfo);
testPlainAccessResource.setAccessKey("rokcetmq");
testPlainAccessResource.setSignature("1234567");
authenticationInfo = plainPermissionLoader.getAccessControl(testPlainAccessResource);
Assert.assertNull(authenticationInfo);
testPlainAccessResource.setRemoteAddr("127.0.0.2");
authenticationInfo = plainPermissionLoader.getAccessControl(testPlainAccessResource);
Assert.assertNull(authenticationInfo);
}
@Test
public void setAccessControlList() {
List<PlainAccessResource> plainAccessResourceList = new ArrayList<>();
plainAccessResourceList.add(plainAccessResource);
plainAccessResourceList.add(plainAccessResourceTwo);
plainPermissionLoader.setAccessControlList(plainAccessResourceList);
AuthenticationInfo newAccessControl = plainPermissionLoader.getAccessControl(plainAccessResource);
Assert.assertEquals(plainAccessResource, newAccessControl.getPlainAccessResource());
newAccessControl = plainPermissionLoader.getAccessControl(plainAccessResourceTwo);
Assert.assertEquals(plainAccessResourceTwo, newAccessControl.getPlainAccessResource());
}
@Test
public void setNetaddressAccessControl() {
PlainAccessResource plainAccessResource = new BrokerAccessControl();
plainAccessResource.setAccessKey("RocketMQ");
plainAccessResource.setSignature("RocketMQ");
plainAccessResource.setRemoteAddr("127.0.0.1");
plainPermissionLoader.setAccessControl(plainAccessResource);
plainPermissionLoader.setNetaddressAccessControl(plainAccessResource);
AuthenticationInfo authenticationInfo = plainPermissionLoader.getAccessControl(plainAccessResource);
PlainAccessResource getPlainAccessResource = authenticationInfo.getPlainAccessResource();
Assert.assertEquals(plainAccessResource, getPlainAccessResource);
plainAccessResource.setRemoteAddr("127.0.0.2");
authenticationInfo = plainPermissionLoader.getAccessControl(plainAccessResource);
Assert.assertNull(authenticationInfo);
}
public void eachCheckLoginAndAuthentication() {
}
@Test(expected = AclPlugRuntimeException.class)
public void BrokerAccessControlTransportTestNull() {
BrokerAccessControlTransport accessControlTransport = new BrokerAccessControlTransport();
plainPermissionLoader.setBrokerAccessControlTransport(accessControlTransport);
}
@Test
public void BrokerAccessControlTransportTest() {
BrokerAccessControlTransport accessControlTransport = new BrokerAccessControlTransport();
List<BrokerAccessControl> list = new ArrayList<>();
list.add((BrokerAccessControl) this.plainAccessResourceTwo);
accessControlTransport.setOnlyNetAddress((BrokerAccessControl) this.plainAccessResource);
accessControlTransport.setList(list);
plainPermissionLoader.setBrokerAccessControlTransport(accessControlTransport);
PlainAccessResource plainAccessResource = new BrokerAccessControl();
plainAccessResource.setAccessKey("RocketMQ");
plainAccessResource.setSignature("RocketMQ");
plainAccessResource.setRemoteAddr("127.0.0.1");
plainPermissionLoader.setAccessControl(plainAccessResource);
AuthenticationInfo authenticationInfo = plainPermissionLoader.getAccessControl(plainAccessResource);
Assert.assertNotNull(authenticationInfo.getPlainAccessResource());
authenticationInfo = plainPermissionLoader.getAccessControl(plainAccessResourceTwo);
Assert.assertEquals(plainAccessResourceTwo, authenticationInfo.getPlainAccessResource());
}
@Test
public void authenticationTest() {
AuthenticationResult authenticationResult = new AuthenticationResult();
plainAccessResource.setRequestCode(317);
boolean isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertTrue(isReturn);
plainAccessResource.setRequestCode(321);
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertFalse(isReturn);
plainAccessResource.setRequestCode(10);
plainAccessResource.setTopic("permitSendTopic");
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertTrue(isReturn);
plainAccessResource.setRequestCode(310);
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertTrue(isReturn);
plainAccessResource.setRequestCode(320);
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertTrue(isReturn);
plainAccessResource.setTopic("noPermitSendTopic");
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertFalse(isReturn);
plainAccessResource.setTopic("nopermitSendTopic");
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertFalse(isReturn);
plainAccessResource.setRequestCode(11);
plainAccessResource.setTopic("permitPullTopic");
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertTrue(isReturn);
plainAccessResource.setTopic("noPermitPullTopic");
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertFalse(isReturn);
plainAccessResource.setTopic("nopermitPullTopic");
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertFalse(isReturn);
}
@Test
public void isEmptyTest() {
AuthenticationResult authenticationResult = new AuthenticationResult();
plainAccessResource.setRequestCode(10);
plainAccessResource.setTopic("absentTopic");
boolean isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertFalse(isReturn);
Set<String> permitSendTopic = new HashSet<>();
brokerAccessControl.setPermitSendTopic(permitSendTopic);
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertTrue(isReturn);
plainAccessResource.setRequestCode(11);
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertFalse(isReturn);
brokerAccessControl.setPermitPullTopic(permitSendTopic);
isReturn = plainPermissionLoader.authentication(authenticationInfo, plainAccessResource, authenticationResult);
Assert.assertTrue(isReturn);
}
@Test
public void adminBrokerAccessControlTest() {
BrokerAccessControl admin = new BrokerAccessControl();
admin.setAccessKey("adminTest");
admin.setSignature("adminTest");
admin.setRemoteAddr("127.0.0.1");
plainPermissionLoader.setAccessControl(admin);
Assert.assertFalse(admin.isUpdateAndCreateTopic());
admin.setAdmin(true);
plainPermissionLoader.setAccessControl(admin);
Assert.assertTrue(admin.isUpdateAndCreateTopic());
}
@Test
public void adminEachCheckAuthentication() {
BrokerAccessControl accessControl = new BrokerAccessControl();
accessControl.setAccessKey("RocketMQ1");
accessControl.setSignature("1234567");
accessControl.setRemoteAddr("127.0.0.1");
plainPermissionLoader.setAccessControl(accessControl);
for (Integer code : adminCode) {
accessControl.setRequestCode(code);
AuthenticationResult authenticationResult = plainPermissionLoader.eachCheckAuthentication(accessControl);
Assert.assertFalse(authenticationResult.isSucceed());
}
plainPermissionLoader.cleanAuthenticationInfo();
accessControl.setAdmin(true);
plainPermissionLoader.setAccessControl(accessControl);
for (Integer code : adminCode) {
accessControl.setRequestCode(code);
AuthenticationResult authenticationResult = plainPermissionLoader.eachCheckAuthentication(accessControl);
Assert.assertTrue(authenticationResult.isSucceed());
}
}
@Test
public void cleanAuthenticationInfoTest() {
plainPermissionLoader.setAccessControl(plainAccessResource);
plainAccessResource.setRequestCode(202);
AuthenticationResult authenticationResult = plainPermissionLoader.eachCheckAuthentication(plainAccessResource);
Assert.assertTrue(authenticationResult.isSucceed());
plainPermissionLoader.cleanAuthenticationInfo();
authenticationResult = plainPermissionLoader.eachCheckAuthentication(plainAccessResource);
Assert.assertFalse(authenticationResult.isSucceed());
}
@Test
public void isWatchStartTest() {
PlainPermissionLoader plainPermissionLoader = new PlainPermissionLoader();
Assert.assertTrue(plainPermissionLoader.isWatchStart());
System.setProperty("java.version", "1.6.11");
plainPermissionLoader = new PlainPermissionLoader();
Assert.assertFalse(plainPermissionLoader.isWatchStart());
}
@Test
public void watchTest() throws IOException {
System.setProperty("rocketmq.home.dir", "src/test/resources/watch");
File file = new File("src/test/resources/watch/conf");
file.mkdirs();
File transport = new File("src/test/resources/watch/conf/transport.yml");
transport.createNewFile();
FileWriter writer = new FileWriter(transport);
writer.write("list:\r\n");
writer.write("- account: rokcetmq\r\n");
writer.write(" password: aliyun11\r\n");
writer.write(" netaddress: 127.0.0.1\r\n");
writer.flush();
writer.close();
PlainPermissionLoader plainPermissionLoader = new PlainPermissionLoader();
plainAccessResource.setRequestCode(203);
AuthenticationResult authenticationResult = plainPermissionLoader.eachCheckAuthentication(plainAccessResource);
Assert.assertTrue(authenticationResult.isSucceed());
writer = new FileWriter(new File("src/test/resources/watch/conf/transport.yml"), true);
writer.write("- account: rokcet1\r\n");
writer.write(" password: aliyun1\r\n");
writer.write(" netaddress: 127.0.0.1\r\n");
writer.flush();
writer.close();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
plainAccessResourceTwo.setRequestCode(203);
authenticationResult = plainPermissionLoader.eachCheckAuthentication(plainAccessResourceTwo);
Assert.assertTrue(authenticationResult.isSucceed());
transport.delete();
file.delete();
file = new File("src/test/resources/watch");
file.delete();
}
@Test
public void analysisTest() {
BrokerAccessControl accessControl = new BrokerAccessControl();
accessControl.setSendMessage(false);
Map<Integer, Boolean> map = accessContralAnalysis.analysis(accessControl);
Iterator<Entry<Integer, Boolean>> it = map.entrySet().iterator();
long num = 0;
while (it.hasNext()) {
Entry<Integer, Boolean> e = it.next();
if (!e.getValue()) {
if (adminCode.contains(e.getKey())) {
continue;
}
Assert.assertEquals(e.getKey(), Integer.valueOf(10));
num++;
}
}
Assert.assertEquals(num, 1);
}
@Test(expected = AclPlugRuntimeException.class)
public void analysisExceptionTest() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
accessContralAnalysis.analysis(plainAccessResource);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.acl.plain;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.rocketmq.acl.common.AclException;
import org.apache.rocketmq.acl.common.AclUtils;
import org.apache.rocketmq.acl.common.Permission;
import org.apache.rocketmq.common.MixAll;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({AclUtils.class})
public class PlainPermissionLoaderTest {
PlainPermissionLoader plainPermissionLoader;
PlainAccessResource PUBPlainAccessResource;
PlainAccessResource SUBPlainAccessResource;
PlainAccessResource ANYPlainAccessResource;
PlainAccessResource DENYPlainAccessResource;
PlainAccessResource plainAccessResource = new PlainAccessResource();
PlainAccessResource plainAccessResourceTwo = new PlainAccessResource();
Set<Integer> adminCode = new HashSet<>();
private String fileName = System.getProperty("romcketmq.acl.plain.fileName", "/conf/transport.yml");
private Map<String/** account **/
, List<PlainAccessResource>> plainAccessResourceMap;
private List<RemoteAddressStrategy> globalWhiteRemoteAddressStrategy;
@Before
public void init() throws NoSuchFieldException, SecurityException, IOException {
// UPDATE_AND_CREATE_TOPIC
adminCode.add(17);
// UPDATE_BROKER_CONFIG
adminCode.add(25);
// DELETE_TOPIC_IN_BROKER
adminCode.add(215);
// UPDATE_AND_CREATE_SUBSCRIPTIONGROUP
adminCode.add(200);
// DELETE_SUBSCRIPTIONGROUP
adminCode.add(207);
PUBPlainAccessResource = clonePlainAccessResource(Permission.PUB);
SUBPlainAccessResource = clonePlainAccessResource(Permission.SUB);
ANYPlainAccessResource = clonePlainAccessResource(Permission.ANY);
DENYPlainAccessResource = clonePlainAccessResource(Permission.DENY);
System.setProperty("java.version", "1.6.11");
System.setProperty("rocketmq.home.dir", "src/test/resources");
plainPermissionLoader = new PlainPermissionLoader();
}
public PlainAccessResource clonePlainAccessResource(byte perm) {
PlainAccessResource painAccessResource = new PlainAccessResource();
painAccessResource.setAccessKey("RocketMQ");
painAccessResource.setSecretKey("12345678");
painAccessResource.setWhiteRemoteAddress("127.0." + perm + ".*");
painAccessResource.setDefaultGroupPerm(perm);
painAccessResource.setDefaultTopicPerm(perm);
painAccessResource.addResourceAndPerm(PlainAccessResource.getRetryTopic("groupA"), Permission.PUB);
painAccessResource.addResourceAndPerm(PlainAccessResource.getRetryTopic("groupB"), Permission.SUB);
painAccessResource.addResourceAndPerm(PlainAccessResource.getRetryTopic("groupC"), Permission.ANY);
painAccessResource.addResourceAndPerm(PlainAccessResource.getRetryTopic("groupD"), Permission.DENY);
painAccessResource.addResourceAndPerm("topicA", Permission.PUB);
painAccessResource.addResourceAndPerm("topicB", Permission.SUB);
painAccessResource.addResourceAndPerm("topicC", Permission.ANY);
painAccessResource.addResourceAndPerm("topicD", Permission.DENY);
return painAccessResource;
}
@SuppressWarnings("unchecked")
private void getField(PlainPermissionLoader plainPermissionLoader) {
try {
this.globalWhiteRemoteAddressStrategy = (List<RemoteAddressStrategy>) FieldUtils.readDeclaredField(plainPermissionLoader, "globalWhiteRemoteAddressStrategy", true);
this.plainAccessResourceMap = (Map<String/** account **/, List<PlainAccessResource>>) FieldUtils.readDeclaredField(plainPermissionLoader, "plainAccessResourceMap", true);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Test(expected = AclException.class)
public void initializeTest() {
System.setProperty("romcketmq.acl.plain.fileName", "/conf/transport-null.yml");
new PlainPermissionLoader();
}
@Test
public void initializeIngetYamlDataObject() {
String fileHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
PowerMockito.mockStatic(AclUtils.class);
JSONObject json = new JSONObject();
json.put("", "");
PowerMockito.when(AclUtils.getYamlDataObject(fileHome + "/conf/transport.yml", JSONObject.class)).thenReturn(json);
PlainPermissionLoader plainPermissionLoader = new PlainPermissionLoader();
getField(plainPermissionLoader);
Assert.assertTrue(globalWhiteRemoteAddressStrategy.isEmpty());
Assert.assertTrue(plainAccessResourceMap.isEmpty());
}
@Test
public void getPlainAccessResourceTest() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
JSONObject account = new JSONObject();
account.put("accessKey", "RocketMQ");
plainAccessResource = plainPermissionLoader.getPlainAccessResource(account);
Assert.assertEquals(plainAccessResource.getAccessKey(), "RocketMQ");
account.put("secretKey", "12345678");
plainAccessResource = plainPermissionLoader.getPlainAccessResource(account);
Assert.assertEquals(plainAccessResource.getSecretKey(), "12345678");
account.put("whiteRemoteAddress", "127.0.0.1");
plainAccessResource = plainPermissionLoader.getPlainAccessResource(account);
Assert.assertEquals(plainAccessResource.getWhiteRemoteAddress(), "127.0.0.1");
account.put("admin", true);
plainAccessResource = plainPermissionLoader.getPlainAccessResource(account);
Assert.assertEquals(plainAccessResource.isAdmin(), true);
account.put("defaultGroupPerm", "ANY");
plainAccessResource = plainPermissionLoader.getPlainAccessResource(account);
Assert.assertEquals(plainAccessResource.getDefaultGroupPerm(), Permission.ANY);
account.put("defaultTopicPerm", "ANY");
plainAccessResource = plainPermissionLoader.getPlainAccessResource(account);
Assert.assertEquals(plainAccessResource.getDefaultTopicPerm(), Permission.ANY);
JSONArray groups = new JSONArray();
groups.add("groupA=DENY");
groups.add("groupB=PUB|SUB");
groups.add("groupC=PUB");
account.put("groups", groups);
plainAccessResource = plainPermissionLoader.getPlainAccessResource(account);
Map<String, Byte> resourcePermMap = plainAccessResource.getResourcePermMap();
Assert.assertEquals(resourcePermMap.size(), 3);
Assert.assertEquals(resourcePermMap.get("groupA").byteValue(), Permission.DENY);
Assert.assertEquals(resourcePermMap.get("groupB").byteValue(), Permission.ANY);
Assert.assertEquals(resourcePermMap.get("groupC").byteValue(), Permission.PUB);
JSONArray topics = new JSONArray();
topics.add("topicA=DENY");
topics.add("topicB=PUB|SUB");
topics.add("topicC=PUB");
account.put("topics", topics);
plainAccessResource = plainPermissionLoader.getPlainAccessResource(account);
resourcePermMap = plainAccessResource.getResourcePermMap();
Assert.assertEquals(resourcePermMap.size(), 3);
Assert.assertEquals(resourcePermMap.get("topicA").byteValue(), Permission.DENY);
Assert.assertEquals(resourcePermMap.get("topicB").byteValue(), Permission.ANY);
Assert.assertEquals(resourcePermMap.get("topicC").byteValue(), Permission.PUB);
}
@Test(expected = AclException.class)
public void checkPermAdmin() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRequestCode(17);
plainPermissionLoader.checkPerm(plainAccessResource, PUBPlainAccessResource);
}
@Test
public void checkPerm() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.addResourceAndPerm("pub", Permission.PUB);
plainPermissionLoader.checkPerm(PUBPlainAccessResource, plainAccessResource);
plainAccessResource.addResourceAndPerm("sub", Permission.SUB);
plainPermissionLoader.checkPerm(ANYPlainAccessResource, plainAccessResource);
plainAccessResource = new PlainAccessResource();
plainAccessResource.addResourceAndPerm("sub", Permission.SUB);
plainPermissionLoader.checkPerm(SUBPlainAccessResource, plainAccessResource);
plainAccessResource.addResourceAndPerm("pub", Permission.PUB);
plainPermissionLoader.checkPerm(ANYPlainAccessResource, plainAccessResource);
}
@Test(expected = AclException.class)
public void accountNullTest() {
plainAccessResource.setAccessKey(null);
plainPermissionLoader.setPlainAccessResource(plainAccessResource);
}
@Test(expected = AclException.class)
public void accountThanTest() {
plainAccessResource.setAccessKey("123");
plainPermissionLoader.setPlainAccessResource(plainAccessResource);
}
@Test(expected = AclException.class)
public void passWordtNullTest() {
plainAccessResource.setAccessKey(null);
plainPermissionLoader.setPlainAccessResource(plainAccessResource);
}
@Test(expected = AclException.class)
public void passWordThanTest() {
plainAccessResource.setAccessKey("123");
plainPermissionLoader.setPlainAccessResource(plainAccessResource);
}
@Test(expected = AclException.class)
public void testPlainAclPlugEngineInit() {
System.setProperty("rocketmq.home.dir", "");
new PlainPermissionLoader().initialize();
}
@Test
public void cleanAuthenticationInfoTest() {
plainPermissionLoader.setPlainAccessResource(plainAccessResource);
plainAccessResource.setRequestCode(202);
plainPermissionLoader.eachCheckPlainAccessResource(plainAccessResource);
plainPermissionLoader.cleanAuthenticationInfo();
plainPermissionLoader.eachCheckPlainAccessResource(plainAccessResource);
}
@Test
public void isWatchStartTest() {
PlainPermissionLoader plainPermissionLoader = new PlainPermissionLoader();
Assert.assertTrue(plainPermissionLoader.isWatchStart());
System.setProperty("java.version", "1.6.11");
plainPermissionLoader = new PlainPermissionLoader();
Assert.assertFalse(plainPermissionLoader.isWatchStart());
}
@Test
public void watchTest() throws IOException {
System.setProperty("rocketmq.home.dir", "src/test/resources/watch");
File file = new File("src/test/resources/watch/conf");
file.mkdirs();
File transport = new File("src/test/resources/watch/conf/transport.yml");
transport.createNewFile();
FileWriter writer = new FileWriter(transport);
writer.write("list:\r\n");
writer.write("- account: rokcetmq\r\n");
writer.write(" password: aliyun11\r\n");
writer.write(" netaddress: 127.0.0.1\r\n");
writer.flush();
writer.close();
PlainPermissionLoader plainPermissionLoader = new PlainPermissionLoader();
plainAccessResource.setRequestCode(203);
plainPermissionLoader.eachCheckPlainAccessResource(plainAccessResource);
writer = new FileWriter(new File("src/test/resources/watch/conf/transport.yml"), true);
writer.write("- account: rokcet1\r\n");
writer.write(" password: aliyun1\r\n");
writer.write(" netaddress: 127.0.0.1\r\n");
writer.flush();
writer.close();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
plainAccessResourceTwo.setRequestCode(203);
plainPermissionLoader.eachCheckPlainAccessResource(plainAccessResourceTwo);
transport.delete();
file.delete();
file = new File("src/test/resources/watch");
file.delete();
}
}
......@@ -16,6 +16,7 @@
*/
package org.apache.rocketmq.acl.plain;
import org.apache.rocketmq.acl.common.AclException;
import org.junit.Assert;
import org.junit.Test;
......@@ -29,41 +30,41 @@ public class RemoteAddressStrategyTest {
RemoteAddressStrategy remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
Assert.assertEquals(remoteAddressStrategy, RemoteAddressStrategyFactory.NULL_NET_ADDRESS_STRATEGY);
plainAccessResource.setRemoteAddr("*");
plainAccessResource.setWhiteRemoteAddress("*");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
Assert.assertEquals(remoteAddressStrategy, RemoteAddressStrategyFactory.NULL_NET_ADDRESS_STRATEGY);
plainAccessResource.setRemoteAddr("127.0.0.1");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
Assert.assertEquals(remoteAddressStrategy.getClass(), RemoteAddressStrategyFactory.OneRemoteAddressStrategy.class);
plainAccessResource.setRemoteAddr("127.0.0.1,127.0.0.2,127.0.0.3");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1,127.0.0.2,127.0.0.3");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
Assert.assertEquals(remoteAddressStrategy.getClass(), RemoteAddressStrategyFactory.MultipleRemoteAddressStrategy.class);
plainAccessResource.setRemoteAddr("127.0.0.{1,2,3}");
plainAccessResource.setWhiteRemoteAddress("127.0.0.{1,2,3}");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
Assert.assertEquals(remoteAddressStrategy.getClass(), RemoteAddressStrategyFactory.MultipleRemoteAddressStrategy.class);
plainAccessResource.setRemoteAddr("127.0.0.1-200");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1-200");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
Assert.assertEquals(remoteAddressStrategy.getClass(), RemoteAddressStrategyFactory.RangeRemoteAddressStrategy.class);
plainAccessResource.setRemoteAddr("127.0.0.*");
plainAccessResource.setWhiteRemoteAddress("127.0.0.*");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
Assert.assertEquals(remoteAddressStrategy.getClass(), RemoteAddressStrategyFactory.RangeRemoteAddressStrategy.class);
plainAccessResource.setRemoteAddr("127.0.1-20.*");
plainAccessResource.setWhiteRemoteAddress("127.0.1-20.*");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
Assert.assertEquals(remoteAddressStrategy.getClass(), RemoteAddressStrategyFactory.RangeRemoteAddressStrategy.class);
}
@Test(expected = AclPlugRuntimeException.class)
@Test(expected = AclException.class)
public void verifyTest() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRemoteAddr("127.0.0.1");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1");
remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
plainAccessResource.setRemoteAddr("256.0.0.1");
plainAccessResource.setWhiteRemoteAddress("256.0.0.1");
remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
}
......@@ -75,17 +76,17 @@ public class RemoteAddressStrategyTest {
public void oneNetaddressStrategyTest() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRemoteAddr("127.0.0.1");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1");
RemoteAddressStrategy remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
plainAccessResource.setRemoteAddr("");
plainAccessResource.setWhiteRemoteAddress("");
boolean match = remoteAddressStrategy.match(plainAccessResource);
Assert.assertFalse(match);
plainAccessResource.setRemoteAddr("127.0.0.2");
plainAccessResource.setWhiteRemoteAddress("127.0.0.2");
match = remoteAddressStrategy.match(plainAccessResource);
Assert.assertFalse(match);
plainAccessResource.setRemoteAddr("127.0.0.1");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1");
match = remoteAddressStrategy.match(plainAccessResource);
Assert.assertTrue(match);
}
......@@ -93,42 +94,42 @@ public class RemoteAddressStrategyTest {
@Test
public void multipleNetaddressStrategyTest() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRemoteAddr("127.0.0.1,127.0.0.2,127.0.0.3");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1,127.0.0.2,127.0.0.3");
RemoteAddressStrategy remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
multipleNetaddressStrategyTest(remoteAddressStrategy);
plainAccessResource.setRemoteAddr("127.0.0.{1,2,3}");
plainAccessResource.setWhiteRemoteAddress("127.0.0.{1,2,3}");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
multipleNetaddressStrategyTest(remoteAddressStrategy);
}
@Test(expected = AclPlugRuntimeException.class)
@Test(expected = AclException.class)
public void multipleNetaddressStrategyExceptionTest() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRemoteAddr("127.0.0.1,2,3}");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1,2,3}");
remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
}
private void multipleNetaddressStrategyTest(RemoteAddressStrategy remoteAddressStrategy) {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRemoteAddr("127.0.0.1");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1");
boolean match = remoteAddressStrategy.match(plainAccessResource);
Assert.assertTrue(match);
plainAccessResource.setRemoteAddr("127.0.0.2");
plainAccessResource.setWhiteRemoteAddress("127.0.0.2");
match = remoteAddressStrategy.match(plainAccessResource);
Assert.assertTrue(match);
plainAccessResource.setRemoteAddr("127.0.0.3");
plainAccessResource.setWhiteRemoteAddress("127.0.0.3");
match = remoteAddressStrategy.match(plainAccessResource);
Assert.assertTrue(match);
plainAccessResource.setRemoteAddr("127.0.0.4");
plainAccessResource.setWhiteRemoteAddress("127.0.0.4");
match = remoteAddressStrategy.match(plainAccessResource);
Assert.assertFalse(match);
plainAccessResource.setRemoteAddr("127.0.0.0");
plainAccessResource.setWhiteRemoteAddress("127.0.0.0");
match = remoteAddressStrategy.match(plainAccessResource);
Assert.assertFalse(match);
......@@ -138,23 +139,24 @@ public class RemoteAddressStrategyTest {
public void rangeNetaddressStrategyTest() {
String head = "127.0.0.";
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRemoteAddr("127.0.0.1-200");
plainAccessResource.setWhiteRemoteAddress("127.0.0.1-200");
RemoteAddressStrategy remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
rangeNetaddressStrategyTest(remoteAddressStrategy, head, 1, 200, true);
plainAccessResource.setRemoteAddr("127.0.0.*");
plainAccessResource.setWhiteRemoteAddress("127.0.0.*");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
rangeNetaddressStrategyTest(remoteAddressStrategy, head, 0, 255, true);
plainAccessResource.setRemoteAddr("127.0.1-200.*");
plainAccessResource.setWhiteRemoteAddress("127.0.1-200.*");
remoteAddressStrategy = remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
rangeNetaddressStrategyThirdlyTest(remoteAddressStrategy, head, 1, 200);
}
private void rangeNetaddressStrategyTest(RemoteAddressStrategy remoteAddressStrategy, String head, int start, int end,
private void rangeNetaddressStrategyTest(RemoteAddressStrategy remoteAddressStrategy, String head, int start,
int end,
boolean isFalse) {
PlainAccessResource plainAccessResource = new PlainAccessResource();
for (int i = -10; i < 300; i++) {
plainAccessResource.setRemoteAddr(head + i);
plainAccessResource.setWhiteRemoteAddress(head + i);
boolean match = remoteAddressStrategy.match(plainAccessResource);
if (isFalse && i >= start && i <= end) {
Assert.assertTrue(match);
......@@ -176,24 +178,24 @@ public class RemoteAddressStrategyTest {
}
}
@Test(expected = AclPlugRuntimeException.class)
@Test(expected = AclException.class)
public void rangeNetaddressStrategyExceptionStartGreaterEndTest() {
rangeNetaddressStrategyExceptionTest("127.0.0.2-1");
}
@Test(expected = AclPlugRuntimeException.class)
@Test(expected = AclException.class)
public void rangeNetaddressStrategyExceptionScopeTest() {
rangeNetaddressStrategyExceptionTest("127.0.0.-1-200");
}
@Test(expected = AclPlugRuntimeException.class)
@Test(expected = AclException.class)
public void rangeNetaddressStrategyExceptionScopeTwoTest() {
rangeNetaddressStrategyExceptionTest("127.0.0.0-256");
}
private void rangeNetaddressStrategyExceptionTest(String netaddress) {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRemoteAddr(netaddress);
plainAccessResource.setWhiteRemoteAddress(netaddress);
remoteAddressStrategyFactory.getNetaddressStrategy(plainAccessResource);
}
......
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
## suggested format
......@@ -13,36 +13,15 @@
# See the License for the specific language governing permissions and
# limitations under the License.
onlyNetAddress:
remoteAddr: 10.10.103.*
noPermitPullTopic:
- broker-a
list:
- accessKey: RocketMQ
signature: 1234567
remoteAddr: 192.0.0.*
admin: true
permitSendTopic:
- test1
- test2
- accessKey: RocketMQ
signature: 1234567
remoteAddr: 192.0.2.1
permitSendTopic:
- test3
- test4
## suggested format
globalWhiteRemoteAddresses:
- 10.10.103.*
- 192.168.0.*
- 10.10.103.*
- 192.168.0.*
accounts:
- accessKey: ak1
secretKey: sk1
- accessKey: RocketMQ
secretKey: 12345678
whiteRemoteAddress: 192.168.0.*
admin: false
defaultTopicPerm: DENY
......@@ -57,8 +36,8 @@ accounts:
- groupB=SUB
- groupC=SUB
- accessKey: ak2
secretKey: sk2
- accessKey: aliyun.com
secretKey: 12345678
whiteRemoteAddress: 192.168.1.*
# if it is admin, it could access all resources
admin: true
......
......@@ -19,13 +19,13 @@ onlyNetAddress:
- broker-a
list:
- account: RocketMQ
- accessKey: RocketMQ
signature: 1234567
remoteAddr: 192.168.0.*
permitSendTopic:
- TopicTest
- test2
- account: RocketMQ
- accessKey: RocketMQ
signature: 1234567
remoteAddr: 192.168.2.1
permitSendTopic:
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册