diff options
| author | Alex Rudyy <orudyy@apache.org> | 2015-04-15 09:47:28 +0000 |
|---|---|---|
| committer | Alex Rudyy <orudyy@apache.org> | 2015-04-15 09:47:28 +0000 |
| commit | 0a0baee45ebcff44635907d457c4ff6810b09c87 (patch) | |
| tree | 8bfb0f9eddbc23cff88af69be80ab3ce7d47011c /qpid/java/broker-plugins/access-control | |
| parent | 54aa3d7070da16ce55c28ccad3f7d0871479e461 (diff) | |
| download | qpid-python-0a0baee45ebcff44635907d457c4ff6810b09c87.tar.gz | |
QPID-6481: Move java source tree to top level
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1673693 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'qpid/java/broker-plugins/access-control')
31 files changed, 0 insertions, 4756 deletions
diff --git a/qpid/java/broker-plugins/access-control/pom.xml b/qpid/java/broker-plugins/access-control/pom.xml deleted file mode 100644 index ab6cf90a21..0000000000 --- a/qpid/java/broker-plugins/access-control/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - 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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-access-control</artifactId> - <name>Qpid Access Control Broker Plug-in</name> - <description>Access Control broker plug-in</description> - - <properties> - <generated-logmessages-dir>${project.build.directory}/generated-sources/generated-logmessages</generated-logmessages-dir> - </properties> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <type>test-jar</type> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/java</directory> - <excludes> - <exclude>**/*.java</exclude> - </excludes> - </resource> - <resource> - <directory>src/main/resources</directory> - <includes> - <include>META-INF/</include> - </includes> - </resource> - </resources> - </build> - -</project> diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java deleted file mode 100644 index e4bf21a082..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -public class AclAction -{ - private Action _action; - private FirewallRule _firewallRule; - - public AclAction(Operation operation, ObjectType object, AclRulePredicates predicates) - { - _action = new Action(operation, object, predicates.getObjectProperties()); - _firewallRule = predicates.getFirewallRule(); - } - - public AclAction(Operation operation) - { - _action = new Action(operation); - } - - public AclAction(Operation operation, ObjectType object, ObjectProperties properties) - { - _action = new Action(operation, object, properties); - } - - public FirewallRule getFirewallRule() - { - return _firewallRule; - } - - public Action getAction() - { - return _action; - } - - public boolean isAllowed() - { - return _action.isAllowed(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(_action) - .append(_firewallRule).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - AclAction rhs = (AclAction) obj; - return new EqualsBuilder() - .append(_action, rhs._action) - .append(_firewallRule, rhs._firewallRule).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_action) - .append(_firewallRule).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java deleted file mode 100644 index ebe6df126f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectProperties.Property; -import org.apache.qpid.server.security.access.firewall.FirewallRule; -import org.apache.qpid.server.security.access.firewall.FirewallRuleFactory; - -/** - * Represents the predicates on an ACL rule by combining predicates relating to the object being operated on - * (e.g. name=foo) with firewall rules. - */ -public class AclRulePredicates -{ - private static final Logger _logger = LoggerFactory.getLogger(AclRulePredicates.class); - - private static final String SEPARATOR = ","; - - private ObjectProperties _properties = new ObjectProperties(); - - private FirewallRule _firewallRule; - - private FirewallRuleFactory _firewallRuleFactory = new FirewallRuleFactory(); - - public void parse(String key, String value) - { - ObjectProperties.Property property = ObjectProperties.Property.parse(key); - - if(property == Property.FROM_HOSTNAME) - { - checkFirewallRuleNotAlreadyDefined(key, value); - _firewallRule = _firewallRuleFactory.createForHostname(value.split(SEPARATOR)); - } - else if(property == Property.FROM_NETWORK) - { - checkFirewallRuleNotAlreadyDefined(key, value); - _firewallRule = _firewallRuleFactory.createForNetwork(value.split(SEPARATOR)); - } - else - { - _properties.put(property, value); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Parsed " + property + " with value " + value); - } - } - - private void checkFirewallRuleNotAlreadyDefined(String key, String value) - { - if(_firewallRule != null) - { - throw new IllegalStateException( - "Cannot parse " + key + "=" + value - + " because firewall rule " + _firewallRule + " has already been defined"); - } - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_properties) - .append(_firewallRule).toString(); - } - - public FirewallRule getFirewallRule() - { - return _firewallRule; - } - - public ObjectProperties getObjectProperties() - { - return _properties; - } - - void setFirewallRuleFactory(FirewallRuleFactory firewallRuleFactory) - { - _firewallRuleFactory = firewallRuleFactory; - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java deleted file mode 100644 index e09935cf5c..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; - -/** - * An access control v2 rule action. - * - * An action consists of an {@link Operation} on an {@link ObjectType} with certain properties, stored in a {@link java.util.Map}. - * The operation and object should be an allowable combination, based on the {@link ObjectType#isAllowed(Operation)} - * method of the object, which is exposed as the {@link #isAllowed()} method here. The internal #propertiesMatch(Map) - * and #valueMatches(String, String) methods are used to determine wildcarded matching of properties, with - * the empty string or "*" matching all values, and "*" at the end of a rule value indicating prefix matching. - * <p> - * The {@link #matches(Action)} method is intended to be used when determining precedence of rules, and - * {@link #equals(Object)} and {@link #hashCode()} are intended for use in maps. This is due to the wildcard matching - * described above. - */ -public class Action -{ - private final Operation _operation; - private final ObjectType _object; - private final ObjectProperties _properties; - - public Action(Operation operation) - { - this(operation, ObjectType.ALL); - } - - public Action(Operation operation, ObjectType object, String name) - { - this(operation, object, new ObjectProperties(name)); - } - - public Action(Operation operation, ObjectType object) - { - this(operation, object, ObjectProperties.EMPTY); - } - - public Action(Operation operation, ObjectType object, ObjectProperties properties) - { - _operation = operation; - _object = object; - _properties = properties; - } - - public Operation getOperation() - { - return _operation; - } - - public ObjectType getObjectType() - { - return _object; - } - - public ObjectProperties getProperties() - { - return _properties; - } - - public boolean isAllowed() - { - return _object.isAllowed(_operation); - } - - public boolean matches(Action a) - { - if (!operationsMatch(a)) - { - return false; - } - - if (!objectTypesMatch(a)) - { - return false; - } - - if (!propertiesMatch(a)) - { - return false; - } - - return true; - } - - private boolean operationsMatch(Action a) - { - return Operation.ALL == a.getOperation() || getOperation() == a.getOperation(); - } - - private boolean objectTypesMatch(Action a) - { - return ObjectType.ALL == a.getObjectType() || getObjectType() == a.getObjectType(); - } - - private boolean propertiesMatch(Action a) - { - boolean propertiesMatch = false; - if (_properties != null) - { - propertiesMatch = _properties.matches(a.getProperties()); - } - else if (a.getProperties() == null) - { - propertiesMatch = true; - } - return propertiesMatch; - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof Action)) - { - return false; - } - Action a = (Action) o; - - return new EqualsBuilder() - .append(_operation, a.getOperation()) - .append(_object, a.getObjectType()) - .append(_properties, a.getProperties()) - .isEquals(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(_operation) - .append(_object) - .append(_properties) - .toHashCode(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("operation", _operation) - .append("objectType", _object) - .append("properties", _properties) - .toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java deleted file mode 100644 index fed20a56c8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import java.net.InetAddress; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -/** - * I represent an {@link Action} taken by a client from a known address. The address is used to - * determine if I match an {@link AclAction}, which may contain firewall rules. - */ -public class ClientAction -{ - private Action _clientAction; - - public ClientAction(Action clientAction) - { - _clientAction = clientAction; - } - - public ClientAction(Operation operation, ObjectType objectType, ObjectProperties properties) - { - _clientAction = new Action(operation, objectType, properties); - } - - public boolean matches(AclAction ruleAction, InetAddress addressOfClient) - { - return _clientAction.matches(ruleAction.getAction()) - && addressOfClientMatches(ruleAction, addressOfClient); - } - - private boolean addressOfClientMatches(AclAction ruleAction, InetAddress addressOfClient) - { - FirewallRule firewallRule = ruleAction.getFirewallRule(); - if(firewallRule == null || addressOfClient == null) - { - return true; - } - else - { - return firewallRule.matches(addressOfClient); - } - } - - public Operation getOperation() - { - return _clientAction.getOperation(); - } - - public ObjectType getObjectType() - { - return _clientAction.getObjectType(); - } - - public ObjectProperties getProperties() - { - return _clientAction.getProperties(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_clientAction).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java deleted file mode 100644 index 3405b6c155..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * - * 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.qpid.server.security.access.config; - -import java.io.Reader; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; - -public interface ConfigurationFile -{ - /** - * Load this configuration file's contents into a {@link RuleSet}. - * @throws IllegalConfigurationException if the configuration file has errors. - * @throws IllegalArgumentException if individual tokens cannot be parsed. - * @param configReader - */ - RuleSet load(final Reader configReader) throws IllegalConfigurationException; - - RuleSet getConfiguration(); - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java deleted file mode 100644 index 92b870f740..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * - * 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.qpid.server.security.access.config; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -import java.io.StreamTokenizer; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.Permission; - -public class PlainConfiguration implements ConfigurationFile -{ - private static final Logger _logger = LoggerFactory.getLogger(PlainConfiguration.class); - - public static final Character COMMENT = '#'; - public static final Character CONTINUATION = '\\'; - - public static final String ACL = "acl"; - public static final String CONFIG = "config"; - - static final String UNRECOGNISED_INITIAL_MSG = "Unrecognised initial token '%s' at line %d"; - static final String NOT_ENOUGH_TOKENS_MSG = "Not enough tokens at line %d"; - static final String NUMBER_NOT_ALLOWED_MSG = "Number not allowed before '%s' at line %d"; - static final String CANNOT_LOAD_MSG = "Cannot load config file %s"; - static final String CANNOT_CLOSE_MSG = "Cannot close config file %s"; - static final String PREMATURE_CONTINUATION_MSG = "Premature continuation character at line %d"; - static final String PREMATURE_EOF_MSG = "Premature end of file reached at line %d"; - static final String PARSE_TOKEN_FAILED_MSG = "Failed to parse token at line %d"; - static final String CONFIG_NOT_FOUND_MSG = "Cannot find config file %s"; - static final String NOT_ENOUGH_ACL_MSG = "Not enough data for an acl at line %d"; - static final String NOT_ENOUGH_CONFIG_MSG = "Not enough data for config at line %d"; - static final String BAD_ACL_RULE_NUMBER_MSG = "Invalid rule number at line %d"; - static final String PROPERTY_KEY_ONLY_MSG = "Incomplete property (key only) at line %d"; - static final String PROPERTY_NO_EQUALS_MSG = "Incomplete property (no equals) at line %d"; - static final String PROPERTY_NO_VALUE_MSG = "Incomplete property (no value) at line %d"; - private final EventLoggerProvider _eventLogger; - private final String _name; - - private StreamTokenizer _st; - private RuleSet _config; - - public PlainConfiguration(String name, final EventLoggerProvider eventLogger) - { - _eventLogger = eventLogger; - _name = name; - } - - @Override - public RuleSet load(final Reader configReader) - { - _config = new RuleSet(_eventLogger); - - try(Reader fileReader = configReader) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("About to load ACL file"); - } - - _st = new StreamTokenizer(new BufferedReader(fileReader)); - _st.resetSyntax(); // setup the tokenizer - - _st.commentChar(COMMENT); // single line comments - _st.eolIsSignificant(true); // return EOL as a token - _st.ordinaryChar('='); // equals is a token - _st.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) - _st.quoteChar('"'); // double quote - _st.quoteChar('\''); // single quote - _st.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly - _st.wordChars('a', 'z'); // unquoted token characters [a-z] - _st.wordChars('A', 'Z'); // [A-Z] - _st.wordChars('0', '9'); // [0-9] - _st.wordChars('_', '_'); // underscore - _st.wordChars('-', '-'); // dash - _st.wordChars('.', '.'); // dot - _st.wordChars('*', '*'); // star - _st.wordChars('@', '@'); // at - _st.wordChars(':', ':'); // colon - - // parse the acl file lines - Stack<String> stack = new Stack<String>(); - int current; - do { - current = _st.nextToken(); - switch (current) - { - case StreamTokenizer.TT_EOF: - case StreamTokenizer.TT_EOL: - if (stack.isEmpty()) - { - break; // blank line - } - - // pull out the first token from the bottom of the stack and check arguments exist - String first = stack.firstElement(); - stack.removeElementAt(0); - if (stack.isEmpty()) - { - throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, getLine())); - } - - // check for and parse optional initial number for ACL lines - Integer number = null; - if (StringUtils.isNumeric(first)) - { - // set the acl number and get the next element - number = Integer.valueOf(first); - first = stack.firstElement(); - stack.removeElementAt(0); - } - - if (StringUtils.equalsIgnoreCase(ACL, first)) - { - parseAcl(number, stack); - } - else if (number == null) - { - if(StringUtils.equalsIgnoreCase("GROUP", first)) - { - throw new IllegalConfigurationException(String.format("GROUP keyword not supported at line %d. Groups should defined via a Group Provider, not in the ACL file.", getLine())); - } - else if (StringUtils.equalsIgnoreCase(CONFIG, first)) - { - parseConfig(stack); - } - else - { - throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, getLine())); - } - } - else - { - throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, getLine())); - } - - // reset stack, start next line - stack.clear(); - break; - case StreamTokenizer.TT_NUMBER: - stack.push(Integer.toString(Double.valueOf(_st.nval).intValue())); - break; - case StreamTokenizer.TT_WORD: - stack.push(_st.sval); // token - break; - default: - if (_st.ttype == CONTINUATION) - { - int next = _st.nextToken(); - if (next == StreamTokenizer.TT_EOL) - { - break; // continue reading next line - } - - // invalid location for continuation character (add one to line because we ate the EOL) - throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, getLine() + 1)); - } - else if (_st.ttype == '\'' || _st.ttype == '"') - { - stack.push(_st.sval); // quoted token - } - else - { - stack.push(Character.toString((char) _st.ttype)); // single character - } - } - } while (current != StreamTokenizer.TT_EOF); - - if (!stack.isEmpty()) - { - throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, getLine())); - } - } - catch (IllegalArgumentException iae) - { - throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, getLine()), iae); - } - catch (FileNotFoundException fnfe) - { - throw new IllegalConfigurationException(String.format(CONFIG_NOT_FOUND_MSG, _name), fnfe); - } - catch (IOException ioe) - { - throw new IllegalConfigurationException(String.format(CANNOT_LOAD_MSG, _name), ioe); - } - - return _config; - } - - private void parseAcl(Integer number, List<String> args) - { - if (args.size() < 3) - { - throw new IllegalConfigurationException(String.format(NOT_ENOUGH_ACL_MSG, getLine())); - } - - Permission permission = Permission.parse(args.get(0)); - String identity = args.get(1); - Operation operation = Operation.parse(args.get(2)); - - if (number != null && !getConfiguration().isValidNumber(number)) - { - throw new IllegalConfigurationException(String.format(BAD_ACL_RULE_NUMBER_MSG, getLine())); - } - - if (args.size() == 3) - { - getConfiguration().grant(number, identity, permission, operation); - } - else - { - ObjectType object = ObjectType.parse(args.get(3)); - AclRulePredicates predicates = toRulePredicates(args.subList(4, args.size())); - - getConfiguration().grant(number, identity, permission, operation, object, predicates); - } - } - - private void parseConfig(List<String> args) - { - if (args.size() < 3) - { - throw new IllegalConfigurationException(String.format(NOT_ENOUGH_CONFIG_MSG, getLine())); - } - - Map<String, Boolean> properties = toPluginProperties(args); - - getConfiguration().configure(properties); - } - - private AclRulePredicates toRulePredicates(List<String> args) - { - AclRulePredicates predicates = new AclRulePredicates(); - Iterator<String> i = args.iterator(); - while (i.hasNext()) - { - String key = i.next(); - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_KEY_ONLY_MSG, getLine())); - } - if (!"=".equals(i.next())) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_EQUALS_MSG, getLine())); - } - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_VALUE_MSG, getLine())); - } - String value = i.next(); - - predicates.parse(key, value); - } - return predicates; - } - - /** Converts a {@link List} of "name", "=", "value" tokens into a {@link Map}. */ - protected Map<String, Boolean> toPluginProperties(List<String> args) - { - Map<String, Boolean> properties = new HashMap<String, Boolean>(); - Iterator<String> i = args.iterator(); - while (i.hasNext()) - { - String key = i.next().toLowerCase(); - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_KEY_ONLY_MSG, getLine())); - } - if (!"=".equals(i.next())) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_EQUALS_MSG, getLine())); - } - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_VALUE_MSG, getLine())); - } - - // parse property value and save - Boolean value = Boolean.valueOf(i.next()); - properties.put(key, value); - } - return properties; - } - - protected int getLine() - { - return _st.lineno() - 1; - } - - public RuleSet getConfiguration() - { - return _config; - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java deleted file mode 100644 index 9e9b33194e..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import org.apache.commons.lang.builder.CompareToBuilder; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.qpid.server.security.access.Permission; - -/** - * An access control v2 rule. - * - * A rule consists of {@link Permission} for a particular identity to perform an {@link Action}. The identity - * may be either a user or a group. - */ -public class Rule implements Comparable<Rule> -{ - /** String indicating all identified. */ - public static final String ALL = "all"; - - private Integer _number; - private Boolean _enabled = Boolean.TRUE; - private String _identity; - private AclAction _action; - private Permission _permission; - - public Rule(Integer number, String identity, AclAction action, Permission permission) - { - setNumber(number); - setIdentity(identity); - setAction(action); - setPermission(permission); - } - - public Rule(String identity, AclAction action, Permission permission) - { - this(null, identity, action, permission); - } - - public boolean isEnabled() - { - return _enabled; - } - - public void setEnabled(boolean enabled) - { - _enabled = enabled; - } - - public void enable() - { - _enabled = Boolean.TRUE; - } - - public void disable() - { - _enabled = Boolean.FALSE; - } - - public Integer getNumber() - { - return _number; - } - - public void setNumber(Integer number) - { - _number = number; - } - - public String getIdentity() - { - return _identity; - } - - public void setIdentity(String identity) - { - _identity = identity; - } - - public Action getAction() - { - return _action.getAction(); - } - - public AclAction getAclAction() - { - return _action; - } - - public void setAction(AclAction action) - { - _action = action; - } - - public Permission getPermission() - { - return _permission; - } - - public void setPermission(Permission permission) - { - _permission = permission; - } - - @Override - public int compareTo(Rule r) - { - return new CompareToBuilder() - .append(getAction(), r.getAction()) - .append(getIdentity(), r.getIdentity()) - .append(getPermission(), r.getPermission()) - .toComparison(); - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof Rule)) - { - return false; - } - Rule r = (Rule) o; - - return new EqualsBuilder() - .append(getIdentity(), r.getIdentity()) - .append(getAclAction(), r.getAclAction()) - .append(getPermission(), r.getPermission()) - .isEquals(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(getIdentity()) - .append(getAclAction()) - .append(getPermission()) - .toHashCode(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("#", getNumber()) - .append("identity", getIdentity()) - .append("action", getAclAction()) - .append("permission", getPermission()) - .append("enabled", isEnabled()) - .toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java deleted file mode 100644 index 7661951d8b..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import java.net.InetAddress; -import java.security.Principal; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.WeakHashMap; - -import javax.security.auth.Subject; - -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.messages.AccessControlMessages; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.Permission; - -/** - * Models the rule configuration for the access control plugin. - */ -public class RuleSet implements EventLoggerProvider -{ - private static final Logger _logger = LoggerFactory.getLogger(RuleSet.class); - - private static final String AT = "@"; - private static final String SLASH = "/"; - - public static final String DEFAULT_ALLOW = "defaultallow"; - public static final String DEFAULT_DENY = "defaultdeny"; - - public static final List<String> CONFIG_PROPERTIES = Arrays.asList(DEFAULT_ALLOW, DEFAULT_DENY); - - private static final Integer _increment = 10; - - private final SortedMap<Integer, Rule> _rules = new TreeMap<Integer, Rule>(); - private final Map<Subject, Map<Operation, Map<ObjectType, List<Rule>>>> _cache = - new WeakHashMap<Subject, Map<Operation, Map<ObjectType, List<Rule>>>>(); - private final Map<String, Boolean> _config = new HashMap<String, Boolean>(); - private final EventLoggerProvider _eventLogger; - - public RuleSet(EventLoggerProvider eventLogger) - { - _eventLogger = eventLogger; - // set some default configuration properties - configure(DEFAULT_DENY, Boolean.TRUE); - } - - /** - * Clear the contents, including acl rules and configuration. - */ - public void clear() - { - _rules.clear(); - _cache.clear(); - _config.clear(); - } - - public int getRuleCount() - { - return _rules.size(); - } - - /** - * Filtered rules list based on a subject and operation. - * - * Allows only enabled rules with identity equal to all, the same, or a group with identity as a member, - * and operation is either all or the same operation. - */ - public List<Rule> getRules(final Subject subject, final Operation operation, final ObjectType objectType) - { - final Map<ObjectType, List<Rule>> objects = getObjectToRuleCache(subject, operation); - - // Lookup object type rules for the operation - if (!objects.containsKey(objectType)) - { - final Set<Principal> principals = subject.getPrincipals(); - boolean controlled = false; - List<Rule> filtered = new LinkedList<Rule>(); - for (Rule rule : _rules.values()) - { - final Action ruleAction = rule.getAction(); - if (rule.isEnabled() - && (ruleAction.getOperation() == Operation.ALL || ruleAction.getOperation() == operation) - && (ruleAction.getObjectType() == ObjectType.ALL || ruleAction.getObjectType() == objectType)) - { - controlled = true; - - if (isRelevant(principals,rule)) - { - filtered.add(rule); - } - } - } - - // Return null if there are no rules at all for this operation and object type - if (filtered.isEmpty() && controlled == false) - { - filtered = null; - } - - // Save the rules we selected - objects.put(objectType, filtered); - if(_logger.isDebugEnabled()) - { - _logger.debug("Cached " + objectType + " RulesList: " + filtered); - } - } - - // Return the cached rules - List<Rule> rules = objects.get(objectType); - if(_logger.isDebugEnabled()) - { - _logger.debug("Returning RuleList: " + rules); - } - - return rules; - } - - public boolean isValidNumber(Integer number) - { - return !_rules.containsKey(number); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation) - { - AclAction action = new AclAction(operation); - addRule(number, identity, permission, action); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation, ObjectType object, ObjectProperties properties) - { - AclAction action = new AclAction(operation, object, properties); - addRule(number, identity, permission, action); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation, ObjectType object, AclRulePredicates predicates) - { - AclAction aclAction = new AclAction(operation, object, predicates); - addRule(number, identity, permission, aclAction); - } - - public boolean ruleExists(String identity, AclAction action) - { - for (Rule rule : _rules.values()) - { - if (rule.getIdentity().equals(identity) && rule.getAclAction().equals(action)) - { - return true; - } - } - return false; - } - - public void addRule(Integer number, String identity, Permission permission, AclAction action) - { - - if (!action.isAllowed()) - { - throw new IllegalArgumentException("Action is not allowed: " + action); - } - if (ruleExists(identity, action)) - { - return; - } - - // set rule number if needed - Rule rule = new Rule(number, identity, action, permission); - if (rule.getNumber() == null) - { - if (_rules.isEmpty()) - { - rule.setNumber(0); - } - else - { - rule.setNumber(_rules.lastKey() + _increment); - } - } - - // save rule - _cache.clear(); - _rules.put(rule.getNumber(), rule); - } - - public void enableRule(int ruleNumber) - { - _rules.get(Integer.valueOf(ruleNumber)).enable(); - } - - public void disableRule(int ruleNumber) - { - _rules.get(Integer.valueOf(ruleNumber)).disable(); - } - - /** Return true if the name is well-formed (contains legal characters). */ - protected boolean checkName(String name) - { - for (int i = 0; i < name.length(); i++) - { - Character c = name.charAt(i); - if (!Character.isLetterOrDigit(c) && c != '-' && c != '_' && c != '@' && c != '.' && c != '/') - { - return false; - } - } - return true; - } - - /** Returns true if a username has the name[@domain][/realm] format */ - protected boolean isvalidUserName(String name) - { - // check for '@' and '/' in name - int atPos = name.indexOf(AT); - int slashPos = name.indexOf(SLASH); - boolean atFound = atPos != StringUtils.INDEX_NOT_FOUND && atPos == name.lastIndexOf(AT); - boolean slashFound = slashPos != StringUtils.INDEX_NOT_FOUND && slashPos == name.lastIndexOf(SLASH); - - // must be at least one character after '@' or '/' - if (atFound && atPos > name.length() - 2) - { - return false; - } - if (slashFound && slashPos > name.length() - 2) - { - return false; - } - - // must be at least one character between '@' and '/' - if (atFound && slashFound) - { - return (atPos < (slashPos - 1)); - } - - // otherwise all good - return true; - } - - /** - * Checks for the case when the client's address is not known. - * - * @see #check(Subject, Operation, ObjectType, ObjectProperties, InetAddress) - */ - public Result check(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties) - { - return check(subject, operation, objectType, properties, null); - } - - /** - * Check the authorisation granted to a particular identity for an operation on an object type with - * specific properties. - * - * Looks up the entire ruleset, which may be cached, for the user and operation and goes through the rules - * in order to find the first one that matches. Either defers if there are no rules, returns the result of - * the first match found, or denies access if there are no matching rules. Normally, it would be expected - * to have a default deny or allow rule at the end of an access configuration however. - */ - public Result check(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties, InetAddress addressOfClient) - { - ClientAction action = new ClientAction(operation, objectType, properties); - - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking action: " + action); - } - - // get the list of rules relevant for this request - List<Rule> rules = getRules(subject, operation, objectType); - if (rules == null) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("No rules found, returning default result"); - } - return getDefault(); - } - - // Iterate through a filtered set of rules dealing with this identity and operation - for (Rule rule : rules) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking against rule: " + rule); - } - - if (action.matches(rule.getAclAction(), addressOfClient)) - { - Permission permission = rule.getPermission(); - - switch (permission) - { - case ALLOW_LOG: - getEventLogger().message(AccessControlMessages.ALLOWED( - action.getOperation().toString(), - action.getObjectType().toString(), - action.getProperties().toString())); - case ALLOW: - return Result.ALLOWED; - case DENY_LOG: - getEventLogger().message(AccessControlMessages.DENIED( - action.getOperation().toString(), - action.getObjectType().toString(), - action.getProperties().toString())); - case DENY: - return Result.DENIED; - } - - return Result.DENIED; - } - } - - // Defer to the next plugin of this type, if it exists - return Result.DEFER; - } - - /** Default deny. */ - public Result getDefault() - { - if (isSet(DEFAULT_ALLOW)) - { - return Result.ALLOWED; - } - if (isSet(DEFAULT_DENY)) - { - return Result.DENIED; - } - return Result.ABSTAIN; - } - - /** - * Check if a configuration property is set. - */ - protected boolean isSet(String key) - { - return BooleanUtils.isTrue(_config.get(key)); - } - - /** - * Configure properties for the plugin instance. - * - * @param properties - */ - public void configure(Map<String, Boolean> properties) - { - _config.putAll(properties); - } - - /** - * Configure a single property for the plugin instance. - * - * @param key - * @param value - */ - public void configure(String key, Boolean value) - { - _config.put(key, value); - } - - /** - * Returns all rules in the {@link RuleSet}. Primarily intended to support unit-testing. - * @return map of rules - */ - public Map<Integer, Rule> getAllRules() - { - return Collections.unmodifiableMap(_rules); - } - - private boolean isRelevant(final Set<Principal> principals, final Rule rule) - { - if (rule.getIdentity().equalsIgnoreCase(Rule.ALL)) - { - return true; - } - else - { - for (Iterator<Principal> iterator = principals.iterator(); iterator.hasNext();) - { - final Principal principal = iterator.next(); - - if (rule.getIdentity().equalsIgnoreCase(principal.getName())) - { - return true; - } - } - } - - return false; - } - - private Map<ObjectType, List<Rule>> getObjectToRuleCache(final Subject subject, final Operation operation) - { - // Lookup identity in cache and create empty operation map if required - Map<Operation, Map<ObjectType, List<Rule>>> operations = _cache.get(subject); - if (operations == null) - { - operations = new EnumMap<Operation, Map<ObjectType, List<Rule>>>(Operation.class); - _cache.put(subject, operations); - } - - // Lookup operation and create empty object type map if required - Map<ObjectType, List<Rule>> objects = operations.get(operation); - if (objects == null) - { - objects = new EnumMap<ObjectType, List<Rule>>(ObjectType.class); - operations.put(operation, objects); - } - return objects; - } - - public EventLogger getEventLogger() - { - return _eventLogger.getEventLogger(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java deleted file mode 100644 index d08a052efd..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * 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.qpid.server.security.access.firewall; - -public class AccessControlFirewallException extends RuntimeException -{ - /** serialVersionUID */ - private static final long serialVersionUID = 4526157149690917805L; - - public AccessControlFirewallException() - { - super(); - } - - public AccessControlFirewallException(String message) - { - super(message); - } - - public AccessControlFirewallException(String message, Throwable cause) - { - super(message, cause); - } - - public AccessControlFirewallException(Throwable cause) - { - super(cause); - } -}
\ No newline at end of file diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java deleted file mode 100644 index 482a795693..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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.qpid.server.security.access.firewall; - -import java.net.InetAddress; - -public interface FirewallRule -{ - boolean matches(InetAddress addressOfClient); -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java deleted file mode 100644 index 64be26c209..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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.qpid.server.security.access.firewall; - -public class FirewallRuleFactory -{ - public FirewallRule createForHostname(String[] hostnames) - { - return new HostnameFirewallRule(hostnames); - } - - public FirewallRule createForNetwork(String[] networks) - { - return new NetworkFirewallRule(networks); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java deleted file mode 100644 index 9d62c44658..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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.qpid.server.security.access.firewall; - -import java.net.InetAddress; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HostnameFirewallRule implements FirewallRule -{ - private static final Logger _logger = LoggerFactory.getLogger(HostnameFirewallRule.class); - - private static final long DNS_TIMEOUT = 30000; - private static final ExecutorService DNS_LOOKUP = Executors.newCachedThreadPool(); - - private Pattern[] _hostnamePatterns; - private String[] _hostnames; - - public HostnameFirewallRule(String... hostnames) - { - _hostnames = hostnames; - - int i = 0; - _hostnamePatterns = new Pattern[hostnames.length]; - for (String hostname : hostnames) - { - _hostnamePatterns[i++] = Pattern.compile(hostname); - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Created " + this); - } - } - - @Override - public boolean matches(InetAddress remote) - { - String hostname = getHostname(remote); - if (hostname == null) - { - throw new AccessControlFirewallException("DNS lookup failed for address " + remote); - } - for (Pattern pattern : _hostnamePatterns) - { - boolean hostnameMatches = pattern.matcher(hostname).matches(); - - if (hostnameMatches) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Hostname " + hostname + " matches rule " + pattern.toString()); - } - return true; - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Hostname " + hostname + " matches no configured hostname patterns"); - } - - return false; - } - - - /** - * @param remote - * the InetAddress to look up - * @return the hostname, null if not found, takes longer than - * {@value #DNS_LOOKUP} to find or otherwise fails - */ - private String getHostname(final InetAddress remote) throws AccessControlFirewallException - { - FutureTask<String> lookup = new FutureTask<String>(new Callable<String>() - { - public String call() - { - return remote.getCanonicalHostName(); - } - }); - DNS_LOOKUP.execute(lookup); - - try - { - return lookup.get(DNS_TIMEOUT, TimeUnit.MILLISECONDS); - } - catch (Exception e) - { - _logger.warn("Unable to look up hostname from address " + remote, e); - return null; - } - finally - { - lookup.cancel(true); - } - } - - @Override - public int hashCode() - { - return new HashCodeBuilder().append(_hostnames).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - HostnameFirewallRule rhs = (HostnameFirewallRule) obj; - return new EqualsBuilder().append(_hostnames, rhs._hostnames).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_hostnames).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java deleted file mode 100644 index 7294d9c5e8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 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.qpid.server.security.access.firewall; - -import java.net.InetAddress; - -class InetNetwork -{ - /* - * Implements network masking, and is compatible with RFC 1518 and - * RFC 1519, which describe CIDR: Classless Inter-Domain Routing. - */ - - private InetAddress network; - private InetAddress netmask; - - public InetNetwork(InetAddress ip, InetAddress netmask) - { - this.network = maskIP(ip, netmask); - this.netmask = netmask; - } - - public boolean contains(final String name) throws java.net.UnknownHostException - { - return network.equals(maskIP(InetAddress.getByName(name), netmask)); - } - - public boolean contains(final InetAddress ip) - { - return network.equals(maskIP(ip, netmask)); - } - - @Override - public String toString() - { - return network.getHostAddress() + "/" + netmask.getHostAddress(); - } - - @Override - public int hashCode() - { - return maskIP(network, netmask).hashCode(); - } - - @Override - public boolean equals(Object obj) - { - return (obj != null) && - (obj instanceof InetNetwork) && - ((InetNetwork) obj).network.equals(network) && - ((InetNetwork) obj).netmask.equals(netmask); - } - - public static InetNetwork getFromString(String netspec) throws java.net.UnknownHostException - { - if (netspec.endsWith("*")) - { - netspec = normalizeFromAsterisk(netspec); - } - else - { - int iSlash = netspec.indexOf('/'); - if (iSlash == -1) - { - netspec += "/255.255.255.255"; - } - else if (netspec.indexOf('.', iSlash) == -1) - { - netspec = normalizeFromCIDR(netspec); - } - } - - return new InetNetwork( - InetAddress.getByName(netspec.substring(0, netspec.indexOf('/'))), - InetAddress.getByName(netspec.substring(netspec.indexOf('/') + 1))); - } - - public static InetAddress maskIP(final byte[] ip, final byte[] mask) - { - try - { - return InetAddress.getByAddress(new byte[] - { - (byte) (mask[0] & ip[0]), - (byte) (mask[1] & ip[1]), - (byte) (mask[2] & ip[2]), - (byte) (mask[3] & ip[3]) - }); - } - catch (Exception _) - { - return null; - } - } - - public static InetAddress maskIP(final InetAddress ip, final InetAddress mask) - { - return maskIP(ip.getAddress(), mask.getAddress()); - } - - /* - * This converts from an uncommon "wildcard" CIDR format - * to "address + mask" format: - * - * * => 000.000.000.0/000.000.000.0 - * xxx.* => xxx.000.000.0/255.000.000.0 - * xxx.xxx.* => xxx.xxx.000.0/255.255.000.0 - * xxx.xxx.xxx.* => xxx.xxx.xxx.0/255.255.255.0 - */ - static private String normalizeFromAsterisk(final String netspec) - { - String[] masks = {"0.0.0.0/0.0.0.0", "0.0.0/255.0.0.0", "0.0/255.255.0.0", "0/255.255.255.0"}; - char[] srcb = netspec.toCharArray(); - int octets = 0; - for (int i = 1; i < netspec.length(); i++) - { - if (srcb[i] == '.') - { - octets++; - } - } - return (octets == 0) ? masks[0] : netspec.substring(0, netspec.length() - 1).concat(masks[octets]); - } - - /* - * RFC 1518, 1519 - Classless Inter-Domain Routing (CIDR) - * This converts from "prefix + prefix-length" format to - * "address + mask" format, e.g. from xxx.xxx.xxx.xxx/yy - * to xxx.xxx.xxx.xxx/yyy.yyy.yyy.yyy. - */ - static private String normalizeFromCIDR(final String netspec) - { - final int bits = 32 - Integer.parseInt(netspec.substring(netspec.indexOf('/') + 1)); - final int mask = (bits == 32) ? 0 : 0xFFFFFFFF - ((1 << bits) - 1); - - return netspec.substring(0, netspec.indexOf('/') + 1) + - Integer.toString(mask >> 24 & 0xFF, 10) + "." + - Integer.toString(mask >> 16 & 0xFF, 10) + "." + - Integer.toString(mask >> 8 & 0xFF, 10) + "." + - Integer.toString(mask >> 0 & 0xFF, 10); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java deleted file mode 100644 index 4d635a600e..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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.qpid.server.security.access.firewall; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NetworkFirewallRule implements FirewallRule -{ - private static final Logger _logger = LoggerFactory.getLogger(NetworkFirewallRule.class); - - private List<InetNetwork> _networks; - - public NetworkFirewallRule(String... networks) - { - _networks = new ArrayList<InetNetwork>(); - for (int i = 0; i < networks.length; i++) - { - String network = networks[i]; - try - { - InetNetwork inetNetwork = InetNetwork.getFromString(network); - if (!_networks.contains(inetNetwork)) - { - _networks.add(inetNetwork); - } - } - catch (java.net.UnknownHostException uhe) - { - _logger.error("Cannot resolve address: " + network, uhe); - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Created " + this); - } - } - - @Override - public boolean matches(InetAddress ip) - { - for (InetNetwork network : _networks) - { - if (network.contains(ip)) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Client address " + ip + " matches configured network " + network); - } - return true; - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Client address " + ip + " does not match any configured networks"); - } - - return false; - } - - @Override - public int hashCode() - { - return new HashCodeBuilder().append(_networks).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - NetworkFirewallRule rhs = (NetworkFirewallRule) obj; - return new EqualsBuilder().append(_networks, rhs._networks).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_networks).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java deleted file mode 100644 index 3e0f5b63f0..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * - * 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.qpid.server.security.access.plugins; - -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.ManagedObject; - -@ManagedObject( category = false, type="AclFile" ) -public interface ACLFileAccessControlProvider<X extends ACLFileAccessControlProvider<X>> extends AccessControlProvider<X> -{ - @ManagedAttribute( mandatory = true, description = "File location", oversize = true, oversizedAltText = OVER_SIZED_ATTRIBUTE_ALTERNATIVE_TEXT) - String getPath(); -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java deleted file mode 100644 index 7023a9a03b..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * - * 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.qpid.server.security.access.plugins; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.SettableFuture; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AbstractConfiguredObject; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.StateTransition; -import org.apache.qpid.server.security.AccessControl; -import org.apache.qpid.server.util.urlstreamhandler.data.Handler; - -public class ACLFileAccessControlProviderImpl - extends AbstractConfiguredObject<ACLFileAccessControlProviderImpl> - implements ACLFileAccessControlProvider<ACLFileAccessControlProviderImpl> -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ACLFileAccessControlProviderImpl.class); - - static - { - Handler.register(); - } - - protected DefaultAccessControl _accessControl; - protected final Broker _broker; - - @ManagedAttributeField( afterSet = "reloadAclFile") - private String _path; - - @ManagedObjectFactoryConstructor - public ACLFileAccessControlProviderImpl(Map<String, Object> attributes, Broker broker) - { - super(parentsMap(broker), attributes); - - - _broker = broker; - - } - - @Override - public void onValidate() - { - super.onValidate(); - if(!isDurable()) - { - throw new IllegalArgumentException(getClass().getSimpleName() + " must be durable"); - } - } - - @Override - protected void validateChange(final ConfiguredObject<?> proxyForValidation, final Set<String> changedAttributes) - { - super.validateChange(proxyForValidation, changedAttributes); - if(changedAttributes.contains(DURABLE) && !proxyForValidation.isDurable()) - { - throw new IllegalArgumentException(getClass().getSimpleName() + " must be durable"); - } - } - - @Override - protected void validateOnCreate() - { - DefaultAccessControl accessControl = null; - try - { - accessControl = new DefaultAccessControl(getPath(), _broker); - accessControl.validate(); - accessControl.open(); - } - catch(RuntimeException e) - { - throw new IllegalConfigurationException(e.getMessage(), e); - } - finally - { - if (accessControl != null) - { - accessControl.close(); - } - } - } - - @Override - protected void onOpen() - { - super.onOpen(); - _accessControl = new DefaultAccessControl(getPath(), _broker); - } - - @SuppressWarnings("unused") - private void reloadAclFile() - { - try - { - DefaultAccessControl accessControl = new DefaultAccessControl(getPath(), _broker); - accessControl.open(); - DefaultAccessControl oldAccessControl = _accessControl; - _accessControl = accessControl; - if(oldAccessControl != null) - { - oldAccessControl.close(); - } - } - catch(RuntimeException e) - { - throw new IllegalConfigurationException(e.getMessage(), e); - } - } - - @Override - public String getPath() - { - return _path; - } - - @Override - public <C extends ConfiguredObject> Collection<C> getChildren(Class<C> clazz) - { - return Collections.emptySet(); - } - - - @StateTransition(currentState = {State.UNINITIALIZED, State.QUIESCED, State.ERRORED}, desiredState = State.ACTIVE) - private ListenableFuture<Void> activate() - { - - if(_broker.isManagementMode()) - { - - setState(_accessControl.validate() ? State.QUIESCED : State.ERRORED); - } - else - { - try - { - _accessControl.open(); - setState(State.ACTIVE); - } - catch (RuntimeException e) - { - setState(State.ERRORED); - if (_broker.isManagementMode()) - { - LOGGER.warn("Failed to activate ACL provider: " + getName(), e); - } - else - { - throw e; - } - } - } - return Futures.immediateFuture(null); - } - - @Override - protected void onClose() - { - super.onClose(); - if (_accessControl != null) - { - _accessControl.close(); - } - } - - @StateTransition(currentState = State.UNINITIALIZED, desiredState = State.QUIESCED) - private ListenableFuture<Void> startQuiesced() - { - setState(State.QUIESCED); - return Futures.immediateFuture(null); - } - - @StateTransition(currentState = {State.ACTIVE, State.QUIESCED, State.ERRORED}, desiredState = State.DELETED) - private ListenableFuture<Void> doDelete() - { - final SettableFuture<Void> returnVal = SettableFuture.create(); - closeAsync().addListener( - new Runnable() - { - @Override - public void run() - { - try - { - - setState(State.DELETED); - deleted(); - } - finally - { - returnVal.set(null); - } - } - }, getTaskExecutor().getExecutor() - ); - return returnVal; - } - - public AccessControl getAccessControl() - { - return _accessControl; - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java deleted file mode 100644 index 8533166023..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * - * 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.qpid.server.security.access.plugins; - -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.SocketAddress; -import java.net.URL; -import java.security.AccessController; -import java.util.Set; - -import javax.security.auth.Subject; - -import org.apache.commons.lang.ObjectUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.AccessControl; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.config.ConfigurationFile; -import org.apache.qpid.server.security.access.config.PlainConfiguration; -import org.apache.qpid.server.security.access.config.RuleSet; - -public class DefaultAccessControl implements AccessControl -{ - private static final Logger _logger = LoggerFactory.getLogger(DefaultAccessControl.class); - private final String _fileName; - - private RuleSet _ruleSet; - private final EventLoggerProvider _eventLogger; - - public DefaultAccessControl(String name, final EventLoggerProvider eventLogger) - { - _fileName = name; - _eventLogger = eventLogger; - if (_logger.isDebugEnabled()) - { - _logger.debug("Creating AccessControl instance"); - } - } - - DefaultAccessControl(RuleSet rs) - { - _fileName = null; - _ruleSet = rs; - _eventLogger = rs; - } - - public void open() - { - if(_fileName != null) - { - ConfigurationFile configFile = new PlainConfiguration(_fileName, _eventLogger); - _ruleSet = configFile.load(getReaderFromURLString(_fileName)); - } - } - - @Override - public boolean validate() - { - try - { - getReaderFromURLString(_fileName); - return true; - } - catch(IllegalConfigurationException e) - { - return false; - } - } - - - private static Reader getReaderFromURLString(String urlString) - { - try - { - URL url; - - try - { - url = new URL(urlString); - } - catch (MalformedURLException e) - { - File file = new File(urlString); - try - { - url = file.toURI().toURL(); - } - catch (MalformedURLException notAFile) - { - throw new IllegalConfigurationException("Cannot convert " + urlString + " to a readable resource"); - } - - } - return new InputStreamReader(url.openStream()); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot convert " + urlString + " to a readable resource"); - } - } - - @Override - public void close() - { - //no-op - } - - @Override - public void onDelete() - { - //no-op - } - - @Override - public void onCreate() - { - if(_fileName != null) - { - //verify it is parsable - new PlainConfiguration(_fileName, _eventLogger).load(getReaderFromURLString(_fileName)); - } - } - - public Result getDefault() - { - return _ruleSet.getDefault(); - } - - /** - * Check if an operation is authorised by asking the configuration object about the access - * control rules granted to the current thread's {@link Subject}. If there is no current - * user the plugin will abstain. - */ - public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties) - { - InetAddress addressOfClient = null; - final Subject subject = Subject.getSubject(AccessController.getContext()); - - // Abstain if there is no subject/principal associated with this thread - if (subject == null || subject.getPrincipals().size() == 0) - { - return Result.ABSTAIN; - } - - Set<ConnectionPrincipal> principals = subject.getPrincipals(ConnectionPrincipal.class); - if(!principals.isEmpty()) - { - SocketAddress address = principals.iterator().next().getConnection().getRemoteAddress(); - if(address instanceof InetSocketAddress) - { - addressOfClient = ((InetSocketAddress) address).getAddress(); - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking " + operation + " " + objectType + " " + ObjectUtils.defaultIfNull(addressOfClient, "")); - } - - try - { - return _ruleSet.check(subject, operation, objectType, properties, addressOfClient); - } - catch(Exception e) - { - _logger.error("Unable to check " + operation + " " + objectType + " " + ObjectUtils.defaultIfNull(addressOfClient, ""), e); - return Result.DENIED; - } - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd b/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd deleted file mode 100644 index 9a165b50b8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - - - - 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. - - - --> -<xs:schema - xmlns="http://qpid.apache.org/schema/qpid/broker/security/acl.xsd" - xmlns:xs="http://www.w3.org/2001/XMLSchema" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - targetNamespace="http://qpid.apache.org/schema/qpid/broker/security/acl.xsd" - elementFormDefault="qualified"> - <xs:element name="aclv2" type="xs:string" /> -</xs:schema> diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java deleted file mode 100644 index 14620cff70..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import static org.mockito.Mockito.*; - -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -import junit.framework.TestCase; - -public class AclActionTest extends TestCase -{ - public void testEqualsAndHashCode() - { - AclRulePredicates predicates = createAclRulePredicates(); - ObjectType objectType = ObjectType.EXCHANGE; - Operation operation = Operation.ACCESS; - - AclAction aclAction = new AclAction(operation, objectType, predicates); - AclAction equalAclAction = new AclAction(operation, objectType, predicates); - - assertTrue(aclAction.equals(aclAction)); - assertTrue(aclAction.equals(equalAclAction)); - assertTrue(equalAclAction.equals(aclAction)); - - assertTrue(aclAction.hashCode() == equalAclAction.hashCode()); - - assertFalse("Different operation should cause aclActions to be unequal", - aclAction.equals(new AclAction(Operation.BIND, objectType, predicates))); - - assertFalse("Different operation type should cause aclActions to be unequal", - aclAction.equals(new AclAction(operation, ObjectType.GROUP, predicates))); - - assertFalse("Different predicates should cause aclActions to be unequal", - aclAction.equals(new AclAction(operation, objectType, createAclRulePredicates()))); - - } - - private AclRulePredicates createAclRulePredicates() - { - AclRulePredicates predicates = mock(AclRulePredicates.class); - when(predicates.getFirewallRule()).thenReturn(mock(FirewallRule.class)); - when(predicates.getObjectProperties()).thenReturn(mock(ObjectProperties.class)); - return predicates; - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java deleted file mode 100644 index 93b765d0fb..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import static org.apache.qpid.server.security.access.ObjectProperties.Property.*; - -import org.apache.qpid.server.security.access.firewall.FirewallRule; -import org.apache.qpid.server.security.access.firewall.FirewallRuleFactory; - -import static org.mockito.Mockito.*; - -import junit.framework.TestCase; - -public class AclRulePredicatesTest extends TestCase -{ - private AclRulePredicates _aclRulePredicates = new AclRulePredicates(); - private FirewallRuleFactory _firewallRuleFactory = mock(FirewallRuleFactory.class); - - @Override - protected void setUp() throws Exception - { - _aclRulePredicates.setFirewallRuleFactory(_firewallRuleFactory); - - when(_firewallRuleFactory.createForHostname((String[]) any())).thenReturn(mock(FirewallRule.class)); - when(_firewallRuleFactory.createForNetwork((String[]) any())).thenReturn(mock(FirewallRule.class)); - } - - public void testParse() - { - String name = "name"; - String className = "class"; - - _aclRulePredicates.parse(NAME.name(), name); - _aclRulePredicates.parse(CLASS.name(), className); - - assertEquals(name, _aclRulePredicates.getObjectProperties().get(NAME)); - assertEquals(className, _aclRulePredicates.getObjectProperties().get(CLASS)); - } - - public void testParseHostnameFirewallRule() - { - String hostname = "hostname1,hostname2"; - _aclRulePredicates.parse(FROM_HOSTNAME.name(), hostname); - - verify(_firewallRuleFactory).createForHostname(new String[] {"hostname1", "hostname2"}); - } - - public void testParseNetworkFirewallRule() - { - _aclRulePredicates.setFirewallRuleFactory(_firewallRuleFactory); - - String networks = "network1,network2"; - _aclRulePredicates.parse(FROM_NETWORK.name(), networks); - - verify(_firewallRuleFactory).createForNetwork(new String[] {"network1", "network2"}); - } - - public void testParseThrowsExceptionIfBothHostnameAndNetworkSpecified() - { - _aclRulePredicates.parse(FROM_NETWORK.name(), "network1,network2"); - try - { - _aclRulePredicates.parse(FROM_HOSTNAME.name(), "hostname1,hostname2"); - fail("Exception not thrown"); - } - catch(IllegalStateException e) - { - // pass - } - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java deleted file mode 100644 index 00e06106bf..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import static org.mockito.Mockito.*; - -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; - -import junit.framework.TestCase; - -public class ActionTest extends TestCase -{ - private ObjectProperties _properties1 = mock(ObjectProperties.class); - private ObjectProperties _properties2 = mock(ObjectProperties.class); - - public void testMatchesReturnsTrueForMatchingActions() - { - when(_properties1.matches(_properties2)).thenReturn(true); - - assertMatches( - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties1), - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties2)); - } - - public void testMatchesReturnsFalseWhenOperationsDiffer() - { - assertDoesntMatch( - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOperationTypesDiffer() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.EXCHANGE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOperationPropertiesDiffer() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties2)); - } - - public void testMatchesReturnsFalseWhenMyOperationPropertiesIsNull() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOtherOperationPropertiesIsNull() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null)); - } - - public void testMatchesReturnsTrueWhenBothOperationPropertiesAreNull() - { - assertMatches( - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null), - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null)); - } - - private void assertMatches(Action action1, Action action2) - { - assertTrue(action1 + " should match " + action2, action1.matches(action2)); - } - - private void assertDoesntMatch(Action action1, Action action2) - { - assertFalse(action1 + " should not match " + action2, action1.matches(action2)); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java deleted file mode 100644 index ae5d3fda74..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import static org.mockito.Mockito.*; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -import junit.framework.TestCase; - -public class ClientActionTest extends TestCase -{ - private Action _action = mock(Action.class); - private AclAction _ruleAction = mock(AclAction.class); - private InetAddress _addressOfClient = mock(InetAddress.class); - - private ClientAction _clientAction = new ClientAction(_action); - - public void testMatches_returnsTrueWhenActionsMatchAndNoFirewallRule() - { - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(null); - - assertTrue(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_returnsFalseWhenActionsDontMatch() - { - FirewallRule firewallRule = mock(FirewallRule.class); - when(firewallRule.matches(_addressOfClient)).thenReturn(true); - - when(_action.matches(any(Action.class))).thenReturn(false); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertFalse(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_returnsTrueWhenActionsAndFirewallRuleMatch() - { - FirewallRule firewallRule = mock(FirewallRule.class); - when(firewallRule.matches(_addressOfClient)).thenReturn(true); - - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertTrue(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_ignoresFirewallRuleIfClientAddressIsNull() - { - FirewallRule firewallRule = mock(FirewallRule.class); - - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertTrue(_clientAction.matches(_ruleAction, null)); - - verifyZeroInteractions(firewallRule); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java deleted file mode 100644 index 76435cbae4..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import static org.mockito.Mockito.mock; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.PrintWriter; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectProperties.Property; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; - -public class PlainConfigurationTest extends TestCase -{ - private PlainConfiguration writeACLConfig(String...aclData) throws Exception - { - File acl = File.createTempFile(getClass().getName() + getName(), "acl"); - acl.deleteOnExit(); - - // Write ACL file - PrintWriter aclWriter = new PrintWriter(new FileWriter(acl)); - for (String line : aclData) - { - aclWriter.println(line); - } - aclWriter.close(); - - // Load ruleset - PlainConfiguration configFile = new PlainConfiguration(acl.getName(), mock(EventLoggerProvider.class)); - configFile.load(new FileReader(acl)); - return configFile; - } - - public void testACLFileSyntaxContinuation() throws Exception - { - try - { - writeACLConfig("ACL ALLOW ALL \\ ALL"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PREMATURE_CONTINUATION_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxTokens() throws Exception - { - try - { - writeACLConfig("ACL unparsed ALL ALL"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PARSE_TOKEN_FAILED_MSG, 1), ce.getMessage()); - assertTrue(ce.getCause() instanceof IllegalArgumentException); - assertEquals("Not a valid permission: unparsed", ce.getCause().getMessage()); - } - } - - public void testACLFileSyntaxNotEnoughACL() throws Exception - { - try - { - writeACLConfig("ACL ALLOW"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_ACL_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxNotEnoughConfig() throws Exception - { - try - { - writeACLConfig("CONFIG"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_TOKENS_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxNotEnough() throws Exception - { - try - { - writeACLConfig("INVALID"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_TOKENS_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxPropertyKeyOnly() throws Exception - { - try - { - writeACLConfig("ACL ALLOW adk CREATE QUEUE name"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PROPERTY_KEY_ONLY_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxPropertyNoEquals() throws Exception - { - try - { - writeACLConfig("ACL ALLOW adk CREATE QUEUE name test"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PROPERTY_NO_EQUALS_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxPropertyNoValue() throws Exception - { - try - { - writeACLConfig("ACL ALLOW adk CREATE QUEUE name ="); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PROPERTY_NO_VALUE_MSG, 1), ce.getMessage()); - } - } - - /** - * Tests interpretation of an acl rule with no object properties. - * - */ - public void testValidRule() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL DENY-LOG user1 ACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties quoted in single quotes. - */ - public void testValidRuleWithSingleQuotedProperty() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE name = \'value\'"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("value"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties quoted in double quotes. - */ - public void testValidRuleWithDoubleQuotedProperty() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE name = \"value\""); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("value"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with many object properties. - */ - public void testValidRuleWithManyProperties() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW admin DELETE QUEUE name=name1 owner = owner1"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "admin", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.DELETE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.QUEUE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("name1"); - expectedProperties.put(Property.OWNER, "owner1"); - assertEquals("Rule has unexpected operation", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties containing wildcards. Values containing - * hashes must be quoted otherwise they are interpreted as comments. - */ - public void testValidRuleWithWildcardProperties() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE routingKey = \'news.#\'", - "ACL ALLOW all CREATE EXCHANGE routingKey = \'news.co.#\'", - "ACL ALLOW all CREATE EXCHANGE routingKey = *.co.medellin"); - final RuleSet rs = config.getConfiguration(); - assertEquals(3, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(3, rules.size()); - final Rule rule1 = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule1.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule1.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule1.getAction().getObjectType()); - final ObjectProperties expectedProperties1 = new ObjectProperties(); - expectedProperties1.put(Property.ROUTING_KEY,"news.#"); - assertEquals("Rule has unexpected object properties", expectedProperties1, rule1.getAction().getProperties()); - - final Rule rule2 = rules.get(10); - final ObjectProperties expectedProperties2 = new ObjectProperties(); - expectedProperties2.put(Property.ROUTING_KEY,"news.co.#"); - assertEquals("Rule has unexpected object properties", expectedProperties2, rule2.getAction().getProperties()); - - final Rule rule3 = rules.get(20); - final ObjectProperties expectedProperties3 = new ObjectProperties(); - expectedProperties3.put(Property.ROUTING_KEY,"*.co.medellin"); - assertEquals("Rule has unexpected object properties", expectedProperties3, rule3.getAction().getProperties()); - } - - /** - * Tests that rules are case insignificant. - */ - public void testMixedCaseRuleInterpretation() throws Exception - { - final PlainConfiguration config = writeACLConfig("AcL deny-LOG User1 BiND Exchange Name=AmQ.dIrect"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "User1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.BIND, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties("AmQ.dIrect"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests whitespace is supported. Note that currently the Java implementation permits comments to - * be introduced anywhere in the ACL, whereas the C++ supports only whitespace at the beginning of - * of line. - */ - public void testCommentsSupported() throws Exception - { - final PlainConfiguration config = writeACLConfig("#Comment", - "ACL DENY-LOG user1 ACCESS VIRTUALHOST # another comment", - " # final comment with leading whitespace"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule using mixtures of tabs/spaces as token separators. - * - */ - public void testWhitespace() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL\tDENY-LOG\t\t user1\t \tACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl utilising line continuation. - */ - public void testLineContinuation() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL DENY-LOG user1 \\", - "ACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - public void testUserRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CREATE USER"), - "user1", Operation.CREATE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 CREATE USER name=\"otherUser\""), - "user1", Operation.CREATE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 DELETE USER"), - "user1", Operation.DELETE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 DELETE USER name=\"otherUser\""), - "user1", Operation.DELETE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE USER"), - "user1", Operation.UPDATE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE USER name=\"otherUser\""), - "user1", Operation.UPDATE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 ALL USER"), - "user1", Operation.ALL, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL USER name=\"otherUser\""), - "user1", Operation.ALL, ObjectType.USER, new ObjectProperties("otherUser")); - } - - public void testGroupRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CREATE GROUP"), - "user1", Operation.CREATE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 CREATE GROUP name=\"groupName\""), - "user1", Operation.CREATE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 DELETE GROUP"), - "user1", Operation.DELETE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 DELETE GROUP name=\"groupName\""), - "user1", Operation.DELETE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE GROUP"), - "user1", Operation.UPDATE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE GROUP name=\"groupName\""), - "user1", Operation.UPDATE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 ALL GROUP"), - "user1", Operation.ALL, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL GROUP name=\"groupName\""), - "user1", Operation.ALL, ObjectType.GROUP, new ObjectProperties("groupName")); - } - - /** explicitly test for exception indicating that this functionality has been moved to Group Providers */ - public void testGroupDefinitionThrowsException() throws Exception - { - try - { - writeACLConfig("GROUP group1 bob alice"); - fail("Expected exception not thrown"); - } - catch(IllegalConfigurationException e) - { - assertTrue(e.getMessage().contains("GROUP keyword not supported")); - } - } - - public void testManagementRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 ALL MANAGEMENT"), - "user1", Operation.ALL, ObjectType.MANAGEMENT, ObjectProperties.EMPTY); - - validateRule(writeACLConfig("ACL ALLOW user1 ACCESS MANAGEMENT"), - "user1", Operation.ACCESS, ObjectType.MANAGEMENT, ObjectProperties.EMPTY); - } - - public void testBrokerRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CONFIGURE BROKER"), "user1", Operation.CONFIGURE, ObjectType.BROKER, - ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL BROKER"), "user1", Operation.ALL, ObjectType.BROKER, ObjectProperties.EMPTY); - } - - private void validateRule(final PlainConfiguration config, String username, Operation operation, ObjectType objectType, ObjectProperties objectProperties) - { - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", username, rule.getIdentity()); - assertEquals("Rule has unexpected operation", operation, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", objectType, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", objectProperties, rule.getAction().getProperties()); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java deleted file mode 100644 index 2ae7759679..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.qpid.server.security.access.config; - -import static org.mockito.Mockito.*; - -import org.apache.qpid.server.security.access.Permission; - -import junit.framework.TestCase; - -public class RuleTest extends TestCase -{ - public void testEqualsAndHashCode() - { - AclAction aclAction = mock(AclAction.class); - String identity = "identity"; - Permission allow = Permission.ALLOW; - - Rule rule = new Rule(identity, aclAction, allow); - Rule equalRule = new Rule(identity, aclAction, allow); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different identity should cause rules to be unequal", - rule.equals(new Rule("identity2", aclAction, allow))); - - assertFalse("Different action should cause rules to be unequal", - rule.equals(new Rule(identity, mock(AclAction.class), allow))); - - assertFalse("Different permission should cause rules to be unequal", - rule.equals(new Rule(identity, aclAction, Permission.DENY))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java deleted file mode 100644 index d2beebfb0f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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.qpid.server.security.access.firewall; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.HostnameFirewallRule; - -import junit.framework.TestCase; - -public class HostnameFirewallRuleTest extends TestCase -{ - private InetAddress _addressNotInRule; - - private HostnameFirewallRule _HostnameFirewallRule; - - @Override - protected void setUp() throws Exception - { - _addressNotInRule = InetAddress.getByName("127.0.0.1"); - } - - public void testSingleHostname() throws Exception - { - String hostnameInRule = "hostnameInRule"; - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); - - _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - - public void testSingleHostnameWildcard() throws Exception - { - String hostnameInRule = ".*FOO.*"; - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn("xxFOOxx"); - - _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - - public void testMultipleHostnames() throws Exception - { - String[] hostnamesInRule = new String[] {"hostnameInRule1", "hostnameInRule2"}; - - _HostnameFirewallRule = new HostnameFirewallRule(hostnamesInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - for (String hostnameInRule : hostnamesInRule) - { - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); - - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - } - - public void testEqualsAndHashCode() - { - String hostname1 = "hostname1"; - String hostname2 = "hostname2"; - - HostnameFirewallRule rule = new HostnameFirewallRule(hostname1, hostname2); - HostnameFirewallRule equalRule = new HostnameFirewallRule(hostname1, hostname2); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different hostnames should cause rules to be unequal", - rule.equals(new HostnameFirewallRule(hostname1, "different-hostname"))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java deleted file mode 100644 index e521039db2..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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.qpid.server.security.access.firewall; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.NetworkFirewallRule; - -import junit.framework.TestCase; - -public class NetworkFirewallRuleTest extends TestCase -{ - private static final String LOCALHOST_IP = "127.0.0.1"; - private static final String OTHER_IP_1 = "192.168.23.1"; - private static final String OTHER_IP_2 = "192.168.23.2"; - - private InetAddress _addressNotInRule; - - private NetworkFirewallRule _networkFirewallRule; - - @Override - protected void setUp() throws Exception - { - _addressNotInRule = InetAddress.getByName(LOCALHOST_IP); - } - - public void testIpRule() throws Exception - { - String ipAddressInRule = OTHER_IP_1; - - _networkFirewallRule = new NetworkFirewallRule(ipAddressInRule); - - assertFalse(_networkFirewallRule.matches(_addressNotInRule)); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName(ipAddressInRule))); - } - - public void testNetMask() throws Exception - { - String ipAddressInRule = "192.168.23.0/24"; - _networkFirewallRule = new NetworkFirewallRule(ipAddressInRule); - - assertFalse(_networkFirewallRule.matches(InetAddress.getByName("192.168.24.1"))); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName("192.168.23.0"))); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName("192.168.23.255"))); - } - - public void testWildcard() throws Exception - { - // Test xxx.xxx.* - - assertFalse(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.169.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.168.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.168.255.255"))); - - // Test xxx.xxx.xxx.* - - assertFalse(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.169.2.0"))); - - assertTrue(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.168.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.168.1.255"))); - } - - public void testMultipleNetworks() throws Exception - { - String[] ipAddressesInRule = new String[] {OTHER_IP_1, OTHER_IP_2}; - - _networkFirewallRule = new NetworkFirewallRule(ipAddressesInRule); - - assertFalse(_networkFirewallRule.matches(_addressNotInRule)); - for (String ipAddressInRule : ipAddressesInRule) - { - assertTrue(_networkFirewallRule.matches(InetAddress.getByName(ipAddressInRule))); - } - } - - public void testEqualsAndHashCode() - { - NetworkFirewallRule rule = new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_1); - NetworkFirewallRule equalRule = new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_1); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different networks should cause rules to be unequal", - rule.equals(new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_2))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java deleted file mode 100644 index c51ea64d9c..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * 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.qpid.server.security.access.plugins; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.regex.Pattern; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; -import org.apache.qpid.server.security.access.FileAccessControlProviderConstants; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class ACLFileAccessControlProviderFactoryTest extends QpidTestCase -{ - private Broker _broker; - private ConfiguredObjectFactoryImpl _objectFactory; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _broker = mock(Broker.class); - _objectFactory = new ConfiguredObjectFactoryImpl(BrokerModel.getInstance()); - - when(_broker.getObjectFactory()).thenReturn(_objectFactory); - when(_broker.getModel()).thenReturn(_objectFactory.getModel()); - when(_broker.getCategoryClass()).thenReturn(Broker.class); - TaskExecutor taskExecutor = new CurrentThreadTaskExecutor(); - taskExecutor.start(); - when(_broker.getTaskExecutor()).thenReturn(taskExecutor); - when(_broker.getChildExecutor()).thenReturn(taskExecutor); - - } - - public void testCreateInstanceWhenAclFileIsNotPresent() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - - try - { - AccessControlProvider acl = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - fail("ACL was created without a configuration file path specified"); - } - catch(IllegalArgumentException e) - { - // pass - } - } - - - public void testCreateInstanceWhenAclFileIsSpecified() - { - File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - attributes.put(FileAccessControlProviderConstants.PATH, aclFile.getAbsolutePath()); - AccessControlProvider acl = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - acl.getAccessControl().open(); - - assertNotNull("ACL was not created from acl file: " + aclFile.getAbsolutePath(), acl); - } - - public void testCreateInstanceWhenAclFileIsSpecifiedButDoesNotExist() - { - File aclFile = new File(TMP_FOLDER, "my-non-existing-acl-" + System.currentTimeMillis()); - assertFalse("ACL file " + aclFile.getAbsolutePath() + " actually exists but should not", aclFile.exists()); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - attributes.put(FileAccessControlProviderConstants.PATH, aclFile.getAbsolutePath()); - try - { - AccessControlProvider control = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - control.getAccessControl().open(); - fail("It should not be possible to create and initialise ACL with non existing file"); - } - catch (IllegalConfigurationException e) - { - assertTrue("Unexpected exception message: " + e.getMessage(), Pattern.matches("Cannot convert .* to a readable resource", e.getMessage())); - } - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java deleted file mode 100644 index abe8c6fd9f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * - * 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.qpid.server.security.access.plugins; - - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ACLFileAccessControlProviderImplTest extends QpidTestCase -{ - private TaskExecutor _taskExecutor; - private Model _model; - private Broker _broker; - - public void setUp() throws Exception - { - super.setUp(); - _taskExecutor = CurrentThreadTaskExecutor.newStartedInstance(); - _model = BrokerModel.getInstance(); - - _broker = mock(Broker.class); - when(_broker.getTaskExecutor()).thenReturn(_taskExecutor); - when(_broker.getChildExecutor()).thenReturn(_taskExecutor); - when(_broker.getModel()).thenReturn(_model); - when(_broker.getId()).thenReturn(UUID.randomUUID()); - } - - public void testValidationOnCreateWithNonExistingACLFile() - { - Map<String,Object> attributes = new HashMap<>(); - String aclFilePath = new File(TMP_FOLDER, "test_" + getTestName() + System.nanoTime() + ".acl").getAbsolutePath(); - - attributes.put("path", aclFilePath); - attributes.put(ACLFileAccessControlProvider.NAME, getTestName()); - - - ACLFileAccessControlProviderImpl aclProvider = new ACLFileAccessControlProviderImpl(attributes, _broker); - try - { - aclProvider.create(); - fail("Exception is expected on validation with non-existing ACL file"); - } - catch (IllegalConfigurationException e) - { - assertEquals("Unexpected exception message:" + e.getMessage(), String.format("Cannot convert %s to a readable resource", aclFilePath ), e.getMessage()); - } - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java deleted file mode 100644 index 072bd6a87f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java +++ /dev/null @@ -1,471 +0,0 @@ -/* - * - * 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.qpid.server.security.access.plugins; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; - -import javax.security.auth.Subject; - -import junit.framework.TestCase; - -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.UnitTestMessageLogger; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.Permission; -import org.apache.qpid.server.security.access.config.Rule; -import org.apache.qpid.server.security.access.config.RuleSet; -import org.apache.qpid.server.security.auth.TestPrincipalUtils; - -/** - * In these tests, the ruleset is configured programmatically rather than from an external file. - * - * @see RuleSetTest - */ -public class DefaultAccessControlTest extends TestCase -{ - private static final String ALLOWED_GROUP = "allowed_group"; - private static final String DENIED_GROUP = "denied_group"; - - private DefaultAccessControl _plugin = null; // Class under test - private UnitTestMessageLogger _messageLogger; - private EventLogger _eventLogger; - - public void setUp() throws Exception - { - super.setUp(); - _messageLogger = new UnitTestMessageLogger(); - _eventLogger = new EventLogger(_messageLogger); - _plugin = null; - } - - private void setUpGroupAccessControl() - { - configureAccessControl(createGroupRuleSet()); - } - - private void configureAccessControl(final RuleSet rs) - { - _plugin = new DefaultAccessControl(rs); - } - - private RuleSet createGroupRuleSet() - { - final EventLoggerProvider provider = mock(EventLoggerProvider.class); - when(provider.getEventLogger()).thenReturn(_eventLogger); - final RuleSet rs = new RuleSet(provider); - - // Rule expressed with username - rs.grant(0, "user1", Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - // Rules expressed with groups - rs.grant(1, ALLOWED_GROUP, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - rs.grant(2, DENIED_GROUP, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - // Catch all rule - rs.grant(3, Rule.ALL, Permission.DENY_LOG, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - return rs; - } - - /** - * ACL plugin must always abstain if there is no subject attached to the thread. - */ - public void testNoSubjectAlwaysAbstains() - { - setUpGroupAccessControl(); - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ABSTAIN, result); - } - - /** - * Tests that an allow rule expressed with a username allows an operation performed by a thread running - * with the same username. - */ - public void testUsernameAllowsOperation() - { - setUpGroupAccessControl(); - Subject.doAs(TestPrincipalUtils.createTestSubject("user1"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - } - - /** - * Tests that an allow rule expressed with an <b>ACL groupname</b> allows an operation performed by a thread running - * by a user who belongs to the same group.. - */ - public void testGroupMembershipAllowsOperation() - { - setUpGroupAccessControl(); - - authoriseAndAssertResult(Result.ALLOWED, "member of allowed group", ALLOWED_GROUP); - authoriseAndAssertResult(Result.DENIED, "member of denied group", DENIED_GROUP); - authoriseAndAssertResult(Result.ALLOWED, "another member of allowed group", ALLOWED_GROUP); - } - - /** - * Tests that a deny rule expressed with a <b>groupname</b> denies an operation performed by a thread running - * by a user who belongs to the same group. - */ - public void testGroupMembershipDeniesOperation() - { - setUpGroupAccessControl(); - authoriseAndAssertResult(Result.DENIED, "user3", DENIED_GROUP); - } - - /** - * Tests that the catch all deny denies the operation and logs with the logging actor. - */ - public void testCatchAllRuleDeniesUnrecognisedUsername() - { - setUpGroupAccessControl(); - Subject.doAs(TestPrincipalUtils.createTestSubject("unknown", "unkgroup1", "unkgroup2"), - new PrivilegedAction<Object>() - { - @Override - public Object run() - { - assertEquals("Expecting zero messages before test", - 0, - _messageLogger.getLogMessages().size()); - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.DENIED, result); - - assertEquals("Expecting one message before test", 1, _messageLogger.getLogMessages().size()); - assertTrue("Logged message does not contain expected string", - _messageLogger.messageContains(0, "ACL-1002")); - return null; - } - }); - - } - - /** - * Tests that a grant access method rule allows any access operation to be performed on any component - */ - public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user4 access right on any method in any component - rs.grant(1, "user4", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, new ObjectProperties(ObjectProperties.WILD_CARD)); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user4"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties actionProperties = new ObjectProperties("getName"); - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - - } - - /** - * Tests that a grant access method rule allows any access operation to be performed on a specified component - */ - public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user5 access right on any methods in "Test" component - ObjectProperties ruleProperties = new ObjectProperties(ObjectProperties.WILD_CARD); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - rs.grant(1, "user5", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user5"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties actionProperties = new ObjectProperties("getName"); - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.ALLOWED, result); - - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test2"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.DEFER, result); - return null; - } - }); - - - } - - public void testAccess() throws Exception - { - final Subject subject = TestPrincipalUtils.createTestSubject("user1"); - final String testVirtualHost = getName(); - final InetAddress inetAddress = InetAddress.getLocalHost(); - final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1); - - AMQConnectionModel connectionModel = mock(AMQConnectionModel.class); - when(connectionModel.getRemoteAddress()).thenReturn(inetSocketAddress); - - subject.getPrincipals().add(new ConnectionPrincipal(connectionModel)); - - Subject.doAs(subject, new PrivilegedExceptionAction<Object>() - { - @Override - public Object run() throws Exception - { - RuleSet mockRuleSet = mock(RuleSet.class); - - DefaultAccessControl accessControl = new DefaultAccessControl(mockRuleSet); - - ObjectProperties properties = new ObjectProperties(testVirtualHost); - accessControl.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, properties); - - verify(mockRuleSet).check(subject, Operation.ACCESS, ObjectType.VIRTUALHOST, properties, inetAddress); - return null; - } - }); - - } - - public void testAccessIsDeniedIfRuleThrowsException() throws Exception - { - final Subject subject = TestPrincipalUtils.createTestSubject("user1"); - final InetAddress inetAddress = InetAddress.getLocalHost(); - final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1); - - AMQConnectionModel connectionModel = mock(AMQConnectionModel.class); - when(connectionModel.getRemoteAddress()).thenReturn(inetSocketAddress); - - subject.getPrincipals().add(new ConnectionPrincipal(connectionModel)); - - Subject.doAs(subject, new PrivilegedExceptionAction<Object>() - { - @Override - public Object run() throws Exception - { - - - RuleSet mockRuleSet = mock(RuleSet.class); - when(mockRuleSet.check( - subject, - Operation.ACCESS, - ObjectType.VIRTUALHOST, - ObjectProperties.EMPTY, - inetAddress)).thenThrow(new RuntimeException()); - - DefaultAccessControl accessControl = new DefaultAccessControl(mockRuleSet); - Result result = accessControl.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(Result.DENIED, result); - return null; - } - }); - - } - - - /** - * Tests that a grant access method rule allows any access operation to be performed on a specified component - */ - public void testAuthoriseAccessMethodWhenSpecifiedAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user6 access right on "getAttribute" method in "Test" component - ObjectProperties ruleProperties = new ObjectProperties("getAttribute"); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - rs.grant(1, "user6", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user6"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties.put(ObjectProperties.Property.COMPONENT, "Test2"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - properties = new ObjectProperties("getAttribute2"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - return null; - } - }); - - } - - /** - * Tests that granting of all method rights on a method allows a specified operation to be performed on any component - */ - public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnSpecifiedMethodForAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user8 all rights on method queryNames in all component - rs.grant(1, "user8", Permission.ALLOW, Operation.ALL, ObjectType.METHOD, new ObjectProperties("queryNames")); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user8"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties(); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - properties.put(ObjectProperties.Property.NAME, "queryNames"); - - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - return null; - } - }); - - - } - - /** - * Tests that granting of all method rights allows any operation to be performed on any component - */ - public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnAllMethodsInAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user9 all rights on any method in all component - rs.grant(1, "user9", Permission.ALLOW, Operation.ALL, ObjectType.METHOD, new ObjectProperties()); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user9"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("queryNames"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - - - } - - /** - * Tests that granting of access method rights with mask allows matching operations to be performed on the specified component - */ - public void testAuthoriseAccessMethodWhenMatchingAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user9 all rights on "getAttribute*" methods in Test component - ObjectProperties ruleProperties = new ObjectProperties(); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - ruleProperties.put(ObjectProperties.Property.NAME, "getAttribute*"); - - rs.grant(1, "user9", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user9"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("getAttributes"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribut"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - return null; - } - }); - } - - private void authoriseAndAssertResult(final Result expectedResult, String userName, String... groups) - { - - Subject.doAs(TestPrincipalUtils.createTestSubject(userName, groups), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(expectedResult, result); - return null; - } - }); - - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java deleted file mode 100644 index 5301d2e49d..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * - * 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.qpid.server.security.access.plugins; - -import static org.mockito.Mockito.mock; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.Permission; -import org.apache.qpid.server.security.access.ObjectProperties.Property; -import org.apache.qpid.server.security.access.config.Rule; -import org.apache.qpid.server.security.access.config.RuleSet; -import org.apache.qpid.server.security.auth.TestPrincipalUtils; -import org.apache.qpid.test.utils.QpidTestCase; - -/** - * This test checks that the {@link RuleSet} object which forms the core of the access control plugin performs correctly. - * - * The ruleset is configured directly rather than using an external file by adding rules individually, calling the - * {@link RuleSet#grant(Integer, String, Permission, Operation, ObjectType, ObjectProperties)} method. Then, the - * access control mechanism is validated by checking whether operations would be authorised by calling the - * {@link RuleSet#check(Subject, Operation, ObjectType, ObjectProperties)} method. - * - * It ensure that permissions can be granted correctly on users directly and on groups. - */ -public class RuleSetTest extends QpidTestCase -{ - private static final String DENIED_VH = "deniedVH"; - private static final String ALLOWED_VH = "allowedVH"; - - private RuleSet _ruleSet; // Object under test - - private static final String TEST_USER = "user"; - - // Common things that are passed to frame constructors - private String _queueName = this.getClass().getName() + "queue"; - private String _exchangeName = "amq.direct"; - private String _exchangeType = "direct"; - private Subject _testSubject = TestPrincipalUtils.createTestSubject(TEST_USER); - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _ruleSet = new RuleSet(mock(EventLoggerProvider.class)); - } - - @Override - public void tearDown() throws Exception - { - _ruleSet.clear(); - super.tearDown(); - } - - public void assertDenyGrantAllow(Subject subject, Operation operation, ObjectType objectType) - { - assertDenyGrantAllow(subject, operation, objectType, ObjectProperties.EMPTY); - } - - public void assertDenyGrantAllow(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties) - { - assertEquals(Result.DENIED, _ruleSet.check(subject, operation, objectType, properties)); - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, operation, objectType, properties); - assertEquals(1, _ruleSet.getRuleCount()); - assertEquals(Result.ALLOWED, _ruleSet.check(subject, operation, objectType, properties)); - } - - public void testEmptyRuleSet() - { - assertNotNull(_ruleSet); - assertEquals(_ruleSet.getRuleCount(), 0); - assertEquals(_ruleSet.getDefault(), _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testVirtualHostNodeCreateAllowPermissionWithVirtualHostName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.DELETE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY)); - } - - public void testVirtualHostAccessAllowPermissionWithVirtualHostName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithNameSetToWildCard() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ObjectProperties.WILD_CARD)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithNoName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessDenyPermissionWithNoName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessDenyPermissionWithNameSetToWildCard() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ObjectProperties.WILD_CARD)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowDenyPermissions() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH)); - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithVirtualHostNameOtherPredicate() throws Exception - { - ObjectProperties properties = new ObjectProperties(); - properties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, properties); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, properties)); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - - public void testQueueCreateNamed() throws Exception - { - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(_queueName)); - } - - public void testQueueCreateNamedVirtualHost() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(Property.VIRTUALHOST_NAME, ALLOWED_VH)); - - ObjectProperties allowedQueueObjectProperties = new ObjectProperties(_queueName); - allowedQueueObjectProperties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(allowedQueueObjectProperties))); - - ObjectProperties deniedQueueObjectProperties = new ObjectProperties(_queueName); - deniedQueueObjectProperties.put(Property.VIRTUALHOST_NAME, DENIED_VH); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, deniedQueueObjectProperties)); - } - - public void testQueueCreateNamedNullRoutingKey() - { - ObjectProperties properties = new ObjectProperties(_queueName); - properties.put(ObjectProperties.Property.ROUTING_KEY, (String) null); - - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.QUEUE, properties); - } - - public void testExchangeCreateNamedVirtualHost() - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.EXCHANGE, new ObjectProperties(Property.VIRTUALHOST_NAME, ALLOWED_VH)); - - ObjectProperties allowedExchangeProperties = new ObjectProperties(_exchangeName); - allowedExchangeProperties.put(Property.TYPE, _exchangeType); - allowedExchangeProperties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, allowedExchangeProperties)); - - ObjectProperties deniedExchangeProperties = new ObjectProperties(_exchangeName); - deniedExchangeProperties.put(Property.TYPE, _exchangeType); - deniedExchangeProperties.put(Property.VIRTUALHOST_NAME, DENIED_VH); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, deniedExchangeProperties)); - } - - public void testExchangeCreate() - { - ObjectProperties properties = new ObjectProperties(_exchangeName); - properties.put(ObjectProperties.Property.TYPE, _exchangeType); - - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, properties); - } - - public void testConsume() - { - assertDenyGrantAllow(_testSubject, Operation.CONSUME, ObjectType.QUEUE); - } - - public void testPublish() - { - assertDenyGrantAllow(_testSubject, Operation.PUBLISH, ObjectType.EXCHANGE); - } - - /** - * If the consume permission for temporary queues is for an unnamed queue then it should - * be global for any temporary queue but not for any non-temporary queue - */ - public void testTemporaryUnnamedQueueConsume() - { - ObjectProperties temporary = new ObjectProperties(); - temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - ObjectProperties normal = new ObjectProperties(); - normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - assertEquals(1, _ruleSet.getRuleCount()); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - - // defer to global if exists, otherwise default answer - this is handled by the security manager - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, normal)); - } - - /** - * Test that temporary queue permissions before queue perms in the ACL config work correctly - */ - public void testTemporaryQueueFirstConsume() - { - ObjectProperties temporary = new ObjectProperties(_queueName); - temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - ObjectProperties normal = new ObjectProperties(_queueName); - normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - - // should not matter if the temporary permission is processed first or last - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, normal); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, normal)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - } - - /** - * Test that temporary queue permissions after queue perms in the ACL config work correctly - */ - public void testTemporaryQueueLastConsume() - { - ObjectProperties temporary = new ObjectProperties(_queueName); - temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - ObjectProperties normal = new ObjectProperties(_queueName); - normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - - // should not matter if the temporary permission is processed first or last - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, normal); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, normal)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - } - - /* - * Test different rules for temporary queues. - */ - - /** - * The more generic rule first is used, so both requests are allowed. - */ - public void testFirstNamedSecondTemporaryQueueDenied() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - /** - * The more specific rule is first, so those requests are denied. - */ - public void testFirstTemporarySecondNamedQueueDenied() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - /** - * The more specific rules are first, so those requests are denied. - */ - public void testFirstTemporarySecondDurableThirdNamedQueueDenied() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - ObjectProperties namedDurable = new ObjectProperties(_queueName); - namedDurable.put(ObjectProperties.Property.DURABLE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedDurable)); - - _ruleSet.grant(1, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedDurable); - _ruleSet.grant(3, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(3, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedDurable)); - } - - public void testNamedTemporaryQueueAllowed() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - public void testNamedTemporaryQueueDeniedAllowed() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - /** - * Tests support for the {@link Rule#ALL} keyword. - */ - public void testAllowToAll() - { - _ruleSet.grant(1, Rule.ALL, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(1, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("usera"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("userb"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testGroupsSupported() - { - String allowGroup = "allowGroup"; - String deniedGroup = "deniedGroup"; - - _ruleSet.grant(1, allowGroup, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, deniedGroup, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("usera", allowGroup),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.DENIED, _ruleSet.check(TestPrincipalUtils.createTestSubject("userb", deniedGroup),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.DEFER, _ruleSet.check(TestPrincipalUtils.createTestSubject("user", "group not mentioned in acl"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - /** - * Rule order in the ACL determines the outcome of the check. This test ensures that a user who is - * granted explicit permission on an object, is granted that access even though a group - * to which the user belongs is later denied the permission. - */ - public void testAllowDeterminedByRuleOrder() - { - String group = "group"; - String user = "user"; - - _ruleSet.grant(1, user, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, group, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject(user, group),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - /** - * Rule order in the ACL determines the outcome of the check. This tests ensures that a user who is denied - * access by group, is denied access, despite there being a later rule granting permission to that user. - */ - public void testDenyDeterminedByRuleOrder() - { - String group = "aclgroup"; - String user = "usera"; - - _ruleSet.grant(1, group, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, user, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.DENIED, _ruleSet.check(TestPrincipalUtils.createTestSubject(user, group),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testUserInMultipleGroups() - { - String allowedGroup = "group1"; - String deniedGroup = "group2"; - - _ruleSet.grant(1, allowedGroup, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, deniedGroup, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - Subject subjectInBothGroups = TestPrincipalUtils.createTestSubject("user", allowedGroup, deniedGroup); - Subject subjectInDeniedGroupAndOneOther = TestPrincipalUtils.createTestSubject("user", deniedGroup, "some other group"); - Subject subjectInAllowedGroupAndOneOther = TestPrincipalUtils.createTestSubject("user", allowedGroup, "some other group"); - - assertEquals(Result.ALLOWED, _ruleSet.check(subjectInBothGroups,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - - assertEquals(Result.DENIED, _ruleSet.check(subjectInDeniedGroupAndOneOther,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - - assertEquals(Result.ALLOWED, _ruleSet.check(subjectInAllowedGroupAndOneOther,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } -} |
