diff options
author | 2016-05-24 17:13:17 +0200 | |
---|---|---|
committer | 2016-05-24 17:13:17 +0200 | |
commit | e63b03f3d7e4851e008e4bb4d184982c2c0bd229 (patch) | |
tree | 8364e8a9c56e214ac0fe248409d21f324b1e0f18 /odl-aaa-moon/aaa-shiro | |
parent | 3c1264562ec7949d008e2335b9eecc400436a70d (diff) |
odl/aaa clone
Change-Id: I2b72c16aa3245e02d985a2c6189aacee7caad36e
Signed-off-by: WuKong <rebirthmonkey@gmail.com>
Diffstat (limited to 'odl-aaa-moon/aaa-shiro')
19 files changed, 1901 insertions, 0 deletions
diff --git a/odl-aaa-moon/aaa-shiro/pom.xml b/odl-aaa-moon/aaa-shiro/pom.xml new file mode 100644 index 00000000..2f848215 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/pom.xml @@ -0,0 +1,156 @@ +<!-- Copyright (c) 2015 Brocade Communications Systems, Inc. and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 which accompanies + this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html --> +<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/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.opendaylight.aaa</groupId> + <artifactId>aaa-parent</artifactId> + <version>0.3.1-Beryllium-SR1</version> + <relativePath>../parent</relativePath> + </parent> + + <artifactId>aaa-shiro</artifactId> + <packaging>bundle</packaging> + + <dependencies> + <!-- moon add --> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-client</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.json</groupId> + <artifactId>json</artifactId> + <version>20140107</version> + </dependency> + <!-- OAuth2 dependencies for moon --> + <dependency> + <groupId>org.apache.oltu.oauth2</groupId> + <artifactId>org.apache.oltu.oauth2.authzserver</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.apache.oltu.oauth2</groupId> + <artifactId>org.apache.oltu.oauth2.common</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.apache.oltu.oauth2</groupId> + <artifactId>org.apache.oltu.oauth2.resourceserver</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.apache.felix</groupId> + <artifactId>org.apache.felix.dependencymanager</artifactId> + </dependency> + <dependency> + <groupId>org.opendaylight.aaa</groupId> + <artifactId>aaa-authn-sts</artifactId> + </dependency> + <dependency> + <groupId>org.opendaylight.aaa</groupId> + <artifactId>aaa-authn-basic</artifactId> + </dependency> + <dependency> + <groupId>org.apache.shiro</groupId> + <artifactId>shiro-core</artifactId> + </dependency> + <dependency> + <groupId>org.apache.shiro</groupId> + <artifactId>shiro-web</artifactId> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </dependency> + <dependency> + <groupId>commons-beanutils</groupId> + <artifactId>commons-beanutils</artifactId> + <version>1.8.3</version> + </dependency> + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>javax.servlet-api</artifactId> + </dependency> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + </dependency> + + <!-- Testing Dependencies --> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> + <pluginManagement> + <plugins> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-bundle-plugin</artifactId> + <version>${bundle.plugin.version}</version> + <extensions>true</extensions> + <configuration> + <instructions> + <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name> + </instructions> + <manifestLocation>${project.basedir}/META-INF</manifestLocation> + </configuration> + </plugin> + </plugins> + </pluginManagement> + <plugins> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-bundle-plugin</artifactId> + <extensions>true</extensions> + <configuration> + <instructions> + <Import-Package> + * + </Import-Package> + <Web-ContextPath>/moon</Web-ContextPath> + <Bundle-Activator>org.opendaylight.aaa.shiro.Activator</Bundle-Activator> + </instructions> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jar-plugin</artifactId> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <executions> + <execution> + <id>attach-artifacts</id> + <phase>package</phase> + <goals> + <goal>attach-artifact</goal> + </goals> + <configuration> + <artifacts> + <artifact> + <file>${project.build.directory}/classes/shiro.ini</file> + <type>cfg</type> + <classifier>configuration</classifier> + </artifact> + </artifacts> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/Activator.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/Activator.java new file mode 100644 index 00000000..2f1c98f7 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/Activator.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro; + +import org.apache.felix.dm.DependencyActivatorBase; +import org.apache.felix.dm.DependencyManager; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This scaffolding allows the use of AAA Filters without AuthN or AuthZ + * enabled. This is done to support workflows such as those included in the + * <code>odl-restconf-noauth</code> feature. + * + * This class is also responsible for offering contextual <code>DEBUG</code> + * level clues concerning the activation of the <code>aaa-shiro</code> bundle. + * To enable these debug messages, issue the following command in the karaf + * shell: <code>log:set debug org.opendaylight.aaa.shiro.Activator</code> + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + */ +public class Activator extends DependencyActivatorBase { + + private static final Logger LOG = LoggerFactory.getLogger(Activator.class); + + @Override + public void destroy(BundleContext bc, DependencyManager dm) throws Exception { + final String DEBUG_MESSAGE = "Destroying the aaa-shiro bundle"; + LOG.debug(DEBUG_MESSAGE); + } + + @Override + public void init(BundleContext bc, DependencyManager dm) throws Exception { + final String DEBUG_MESSAGE = "Initializing the aaa-shiro bundle"; + LOG.debug(DEBUG_MESSAGE); + } + +} diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/ServiceProxy.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/ServiceProxy.java new file mode 100644 index 00000000..e4485d73 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/ServiceProxy.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro; + +import org.opendaylight.aaa.shiro.filters.AAAFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Responsible for enabling and disabling the AAA service. By default, the + * service is disabled; the AAAFilter will not require AuthN or AuthZ. The + * service is enabled through calling + * <code>ServiceProxy.getInstance().setEnabled(true)</code>. AuthN and AuthZ are + * disabled by default in order to support workflows such as the feature + * <code>odl-restconf-noauth</code>. + * + * The AAA service is enabled through installing the <code>odl-aaa-shiro</code> + * feature. The <code>org.opendaylight.aaa.shiroact.Activator()</code> + * constructor calls enables AAA through the ServiceProxy, which in turn enables + * the AAAFilter. + * + * ServiceProxy is a singleton; access to the ServiceProxy is granted through + * the <code>getInstance()</code> function. + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + * @see <a + * href="https://github.com/opendaylight/netconf/blob/master/opendaylight/restconf/sal-rest-connector/src/main/resources/WEB-INF/web.xml">resconf + * web,xml</a> + * @see <code>org.opendaylight.aaa.shiro.Activator</code> + * @see <code>org.opendaylight.aaa.shiro.filters.AAAFilter</code> + */ +public class ServiceProxy { + private static final Logger LOG = LoggerFactory.getLogger(ServiceProxy.class); + + /** + * AuthN and AuthZ are disabled by default to support workflows included in + * features such as <code>odl-restconf-noauth</code> + */ + public static final boolean DEFAULT_AA_ENABLE_STATUS = false; + + private static ServiceProxy instance = new ServiceProxy(); + private volatile boolean enabled = false; + private AAAFilter filter; + + /** + * private for singleton pattern + */ + private ServiceProxy() { + final String INFO_MESSAGE = "Creating the ServiceProxy"; + LOG.info(INFO_MESSAGE); + } + + /** + * @return ServiceProxy, a feature level singleton + */ + public static ServiceProxy getInstance() { + return instance; + } + + /** + * Enables/disables the feature, cascading the state information to the + * AAAFilter. + * + * @param enabled A flag indicating whether to enable the Service. + */ + public synchronized void setEnabled(final boolean enabled) { + this.enabled = enabled; + final String SERVICE_ENABLED_INFO_MESSAGE = "Setting ServiceProxy enabled to " + enabled; + LOG.info(SERVICE_ENABLED_INFO_MESSAGE); + // check for null because of non-determinism in bundle load + if (filter != null) { + filter.setEnabled(enabled); + } + } + + /** + * Extract whether the service is enabled. + * + * @param filter + * register an optional Filter for callback if enable state + * changes + * @return Whether the service is enabled + */ + public synchronized boolean getEnabled(final AAAFilter filter) { + this.filter = filter; + return enabled; + } +} diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/accounting/Accounter.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/accounting/Accounter.java new file mode 100644 index 00000000..e768ea59 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/accounting/Accounter.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.aaa.shiro.accounting; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Accounter is a common place to output AAA messages. Use this class through + * invoking <code>Logger.output("message")</code>. + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + */ +public class Accounter { + + private static final Logger LOG = LoggerFactory.getLogger(Accounter.class); + + /* + * Essentially makes Accounter a singleton, avoiding the verbosity of + * <code>Accounter.getInstance().output("message")</code>. + */ + private Accounter() { + } + + /** + * Account for a particular <code>message</code> + * + * @param message A message for the aggregated AAA log. + */ + public static void output(final String message) { + LOG.debug(message); + } +} diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/authorization/DefaultRBACRules.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/authorization/DefaultRBACRules.java new file mode 100644 index 00000000..9e84c988 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/authorization/DefaultRBACRules.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.aaa.shiro.authorization; + +import com.google.common.collect.Sets; +import java.util.Collection; +import java.util.HashSet; + +/** + * A singleton container of default authorization rules that are installed as + * part of Shiro initialization. This class defines an immutable set of rules + * that are needed to provide system-wide security. These include protecting + * certain MD-SAL leaf nodes that contain AAA data from random access. This is + * not a place to define your custom rule set; additional RBAC rules are + * configured through the shiro initialization file: + * <code>$KARAF_HOME/shiro.ini</code> + * + * An important distinction to consider is that Shiro URL rules work to protect + * the system at the Web layer, and <code>AuthzDomDataBroker</code> works to + * protect the system down further at the DOM layer. + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + * + */ +public class DefaultRBACRules { + + private static DefaultRBACRules instance; + + /** + * a collection of the default security rules + */ + private Collection<RBACRule> rbacRules = new HashSet<RBACRule>(); + + /** + * protects the AAA MD-SAL store by preventing access to the leaf nodes to + * non-admin users. + */ + private static final RBACRule PROTECT_AAA_MDSAL = RBACRule.createAuthorizationRule( + "*/authorization/*", Sets.newHashSet("admin")); + + /* + * private for singleton pattern + */ + private DefaultRBACRules() { + // rbacRules.add(PROTECT_AAA_MDSAL); + } + + /** + * + * @return the container instance for the default RBAC Rules + */ + public static final DefaultRBACRules getInstance() { + if (null == instance) { + instance = new DefaultRBACRules(); + } + return instance; + } + + /** + * + * @return a copy of the default rules, so any modifications to the returned + * reference do not affect the <code>DefaultRBACRules</code>. + */ + public final Collection<RBACRule> getRBACRules() { + // Returns a copy of the rbacRules set such that the original set keeps + // its contract of remaining immutable. Calls to rbacRules.add() are + // encapsulated solely in <code>DefaultRBACRules</code>. + // + // Since this method is only called at shiro initialiation time, + // memory consumption of creating a new set is a non-issue. + return Sets.newHashSet(rbacRules); + } +} diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/authorization/RBACRule.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/authorization/RBACRule.java new file mode 100644 index 00000000..0da95eb4 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/authorization/RBACRule.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.aaa.shiro.authorization; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A container for RBAC Rules. An RBAC Rule is composed of a url pattern which + * may contain asterisk characters (*), and a collection of roles. These are + * represented in shiro.ini in the following format: + * <code>urlPattern=roles[atLeastOneCommaSeperatedRole]</code> + * + * RBACRules are immutable; that is, you cannot change the url pattern or the + * roles after creation. This is done for security purposes. RBACRules are + * created through utilizing a static factory method: + * <code>RBACRule.createRBACRule()</code> + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + * + */ +public class RBACRule { + + private static final Logger LOG = LoggerFactory.getLogger(RBACRule.class); + + /** + * a url pattern that can optional contain asterisk characters (*) + */ + private String urlPattern; + + /** + * a collection of role names, such as "admin" and "user" + */ + private Collection<String> roles = new HashSet<String>(); + + /** + * Creates an RBAC Rule. Made private for static factory method. + * + * @param urlPattern + * Cannot be null or the empty string. + * @param roles + * Must contain at least one role. + * @throws NullPointerException + * if <code>urlPattern</code> or <code>roles</code> is null + * @throws IllegalArgumentException + * if <code>urlPattern</code> is an empty string or + * <code>roles</code> is an empty collection. + */ + private RBACRule(final String urlPattern, final Collection<String> roles) + throws NullPointerException, IllegalArgumentException { + + this.setUrlPattern(urlPattern); + this.setRoles(roles); + } + + /** + * The static factory method used to create RBACRules. + * + * @param urlPattern + * Cannot be null or the empty string. + * @param roles + * Cannot be null or an emtpy collection. + * @return An immutable RBACRule + */ + public static RBACRule createAuthorizationRule(final String urlPattern, + final Collection<String> roles) { + + RBACRule authorizationRule = null; + try { + authorizationRule = new RBACRule(urlPattern, roles); + } catch (Exception e) { + LOG.error("Cannot instantiate the AuthorizationRule", e); + } + return authorizationRule; + } + + /** + * + * @return the urlPattern for the RBACRule + */ + public String getUrlPattern() { + return urlPattern; + } + + /* + * helper to ensure the url pattern is not the empty string + */ + private static void checkUrlPatternLength(final String urlPattern) + throws IllegalArgumentException { + + final String EXCEPTION_MESSAGE = "Empty String is not allowed for urlPattern"; + if (urlPattern.isEmpty()) { + throw new IllegalArgumentException(EXCEPTION_MESSAGE); + } + } + + private void setUrlPattern(final String urlPattern) throws NullPointerException, + IllegalArgumentException { + + Preconditions.checkNotNull(urlPattern); + checkUrlPatternLength(urlPattern); + this.urlPattern = urlPattern; + } + + /** + * + * @return a copy of the rule, so any modifications to the returned + * reference do not affect the immutable <code>RBACRule</code>. + */ + public Collection<String> getRoles() { + // Returns a copy of the roles collection such that the original set + // keeps + // its contract of remaining immutable. + // + // Since this method is only called at shiro initialiation time, + // memory consumption of creating a new set is a non-issue. + return Sets.newHashSet(roles); + } + + /* + * check to ensure the roles collection is not empty + */ + private static void checkRolesCollectionSize(final Collection<String> roles) + throws IllegalArgumentException { + + final String EXCEPTION_MESSAGE = "roles must contain at least 1 role"; + if (roles.isEmpty()) { + throw new IllegalArgumentException(EXCEPTION_MESSAGE); + } + } + + private void setRoles(final Collection<String> roles) throws NullPointerException, + IllegalArgumentException { + + Preconditions.checkNotNull(roles); + checkRolesCollectionSize(roles); + this.roles = roles; + } + + /** + * Generates a string representation of the <code>RBACRule</code> roles in + * shiro form. + * + * @return roles string representation in the form + * <code>roles[roleOne,roleTwo]</code> + */ + public String getRolesInShiroFormat() { + final String ROLES_STRING = "roles"; + return ROLES_STRING + Arrays.toString(roles.toArray()); + } + + /** + * Generates the string representation of the <code>RBACRule</code> in shiro + * form. For example: <code>urlPattern=roles[admin,user]</code> + */ + @Override + public String toString() { + return String.format("%s=%s", urlPattern, getRolesInShiroFormat()); + } +} diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/AAAFilter.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/AAAFilter.java new file mode 100644 index 00000000..b53588d8 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/AAAFilter.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro.filters; + +import org.apache.shiro.web.servlet.ShiroFilter; +import org.opendaylight.aaa.shiro.ServiceProxy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The default AAA JAX-RS 1.X Web Filter. This class is also responsible for + * delivering debug information; to enable these debug statements, please issue + * the following in the karaf shell: + * + * <code>log:set debug org.opendaylight.aaa.shiro.filters.AAAFilter</code> + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + * @see <code>javax.servlet.Filter</code> + * @see <code>org.apache.shiro.web.servlet.ShiroFilter</code> + */ +public class AAAFilter extends ShiroFilter { + + private static final Logger LOG = LoggerFactory.getLogger(AAAFilter.class); + + public AAAFilter() { + super(); + final String DEBUG_MESSAGE = "Creating the AAAFilter"; + LOG.debug(DEBUG_MESSAGE); + } + + /* + * (non-Javadoc) + * + * Adds context clues that aid in debugging. Also initializes the enable + * status to correspond with + * <code>ServiceProxy.getInstance.getEnabled()</code>. + * + * @see org.apache.shiro.web.servlet.ShiroFilter#init() + */ + @Override + public void init() throws Exception { + super.init(); + final String DEBUG_MESSAGE = "Initializing the AAAFilter"; + LOG.debug(DEBUG_MESSAGE); + // sets the filter to the startup value. Because of non-determinism in + // bundle loading, this passes an instance of itself along so that if + // the + // enable status changes, then AAAFilter enable status is changed. + setEnabled(ServiceProxy.getInstance().getEnabled(this)); + } + + /* + * (non-Javadoc) + * + * Adds context clues to aid in debugging whether the filter is enabled. + * + * @see + * org.apache.shiro.web.servlet.OncePerRequestFilter#setEnabled(boolean) + */ + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + final String DEBUG_MESSAGE = "Setting AAAFilter enabled to " + enabled; + LOG.debug(DEBUG_MESSAGE); + } +} diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/MoonOAuthFilter.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/MoonOAuthFilter.java new file mode 100644 index 00000000..06038c54 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/MoonOAuthFilter.java @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2014, 2015 Hewlett-Packard Development Company, L.P. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.aaa.shiro.filters; + + +import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; +import static javax.servlet.http.HttpServletResponse.SC_CREATED; +import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; +import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.oltu.oauth2.as.response.OAuthASResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.OAuthResponse; +import org.apache.oltu.oauth2.common.message.types.TokenType; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.web.filter.authc.AuthenticatingFilter; +import org.opendaylight.aaa.AuthenticationBuilder; +import org.opendaylight.aaa.ClaimBuilder; +import org.opendaylight.aaa.api.Authentication; +import org.opendaylight.aaa.api.Claim; +import org.opendaylight.aaa.shiro.moon.MoonPrincipal; +import org.opendaylight.aaa.sts.OAuthRequest; +import org.opendaylight.aaa.sts.ServiceLocator; + + +public class MoonOAuthFilter extends AuthenticatingFilter{ + + private static final String DOMAIN_SCOPE_REQUIRED = "Domain scope required"; + private static final String NOT_IMPLEMENTED = "not_implemented"; + private static final String UNAUTHORIZED = "unauthorized"; + private static final String UNAUTHORIZED_CREDENTIALS = "Unauthorized: Login/Password incorrect"; + + static final String TOKEN_GRANT_ENDPOINT = "/token"; + static final String TOKEN_REVOKE_ENDPOINT = "/revoke"; + static final String TOKEN_VALIDATE_ENDPOINT = "/validate"; + + @Override + protected UsernamePasswordToken createToken(ServletRequest request, ServletResponse response) throws Exception { + // TODO Auto-generated method stub + HttpServletRequest httpRequest = (HttpServletRequest) request; + OAuthRequest oauthRequest = new OAuthRequest(httpRequest); + return new UsernamePasswordToken(oauthRequest.getUsername(),oauthRequest.getPassword()); + } + + @Override + protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { + // TODO Auto-generated method stub + Subject currentUser = SecurityUtils.getSubject(); + return executeLogin(request, response); + } + + protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, + ServletRequest request, ServletResponse response) throws Exception { + HttpServletResponse httpResponse= (HttpServletResponse) response; + MoonPrincipal principal = (MoonPrincipal) subject.getPrincipals().getPrimaryPrincipal(); + Claim claim = principal.principalToClaim(); + oauthAccessTokenResponse(httpResponse,claim,"",principal.getToken()); + return true; + } + + protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, + ServletRequest request, ServletResponse response) { + HttpServletResponse resp = (HttpServletResponse) response; + error(resp, SC_BAD_REQUEST, UNAUTHORIZED_CREDENTIALS); + return false; + } + + protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { + /** + * Here, we will call three functions depending on whether user wants to: + * create Token + * refresh token + * delete token + */ + HttpServletRequest req= (HttpServletRequest) request; + HttpServletResponse resp = (HttpServletResponse) response; + try { + if (req.getServletPath().equals(TOKEN_GRANT_ENDPOINT)) { + UsernamePasswordToken token = createToken(request, response); + if (token == null) { + String msg = "A valid non-null AuthenticationToken " + + "must be created in order to execute a login attempt."; + throw new IllegalStateException(msg); + } + try { + Subject subject = getSubject(request, response); + subject.login(token); + return onLoginSuccess(token, subject, request, response); + } catch (AuthenticationException e) { + return onLoginFailure(token, e, request, response); + } + } else if (req.getServletPath().equals(TOKEN_REVOKE_ENDPOINT)) { + //deleteAccessToken(req, resp); + } else if (req.getServletPath().equals(TOKEN_VALIDATE_ENDPOINT)) { + //validateToken(req, resp); + } + } catch (AuthenticationException e) { + error(resp, SC_UNAUTHORIZED, e.getMessage()); + } catch (OAuthProblemException oe) { + error(resp, oe); + } catch (Exception e) { + error(resp, e); + } + return false; + } + + private void oauthAccessTokenResponse(HttpServletResponse resp, Claim claim, String clientId, String token) + throws OAuthSystemException, IOException { + if (claim == null) { + throw new AuthenticationException(UNAUTHORIZED); + } + + // Cache this token... + Authentication auth = new AuthenticationBuilder(new ClaimBuilder(claim).setClientId( + clientId).build()).setExpiration(tokenExpiration()).build(); + ServiceLocator.getInstance().getTokenStore().put(token, auth); + + OAuthResponse r = OAuthASResponse.tokenResponse(SC_CREATED).setAccessToken(token) + .setTokenType(TokenType.BEARER.toString()) + .setExpiresIn(Long.toString(auth.expiration())) + .buildJSONMessage(); + write(resp, r); + } + + private void write(HttpServletResponse resp, OAuthResponse r) throws IOException { + resp.setStatus(r.getResponseStatus()); + PrintWriter pw = resp.getWriter(); + pw.print(r.getBody()); + pw.flush(); + pw.close(); + } + + private long tokenExpiration() { + return ServiceLocator.getInstance().getTokenStore().tokenExpiration(); + } + + // Emit an error OAuthResponse with the given HTTP code + private void error(HttpServletResponse resp, int httpCode, String error) { + try { + OAuthResponse r = OAuthResponse.errorResponse(httpCode).setError(error) + .buildJSONMessage(); + write(resp, r); + } catch (Exception e1) { + // Nothing to do here + } + } + + private void error(HttpServletResponse resp, OAuthProblemException e) { + try { + OAuthResponse r = OAuthResponse.errorResponse(SC_BAD_REQUEST).error(e) + .buildJSONMessage(); + write(resp, r); + } catch (Exception e1) { + // Nothing to do here + } + } + + private void error(HttpServletResponse resp, Exception e) { + try { + OAuthResponse r = OAuthResponse.errorResponse(SC_INTERNAL_SERVER_ERROR) + .setError(e.getClass().getName()) + .setErrorDescription(e.getMessage()).buildJSONMessage(); + write(resp, r); + } catch (Exception e1) { + // Nothing to do here + } + } + +}
\ No newline at end of file diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/ODLHttpAuthenticationFilter.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/ODLHttpAuthenticationFilter.java new file mode 100644 index 00000000..90b0101e --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/filters/ODLHttpAuthenticationFilter.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro.filters; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.apache.shiro.codec.Base64; +import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter; +import org.apache.shiro.web.util.WebUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Extends <code>BasicHttpAuthenticationFilter</code> to include ability to + * authenticate OAuth2 tokens, which is needed for backwards compatibility with + * <code>TokenAuthFilter</code>. + * + * This behavior is enabled by default for backwards compatibility. To disable + * OAuth2 functionality, just comment out the following line from the + * <code>etc/shiro.ini</code> file: + * <code>authcBasic = org.opendaylight.aaa.shiro.filters.ODLHttpAuthenticationFilter</code> + * then restart the karaf container. + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + * + */ +public class ODLHttpAuthenticationFilter extends BasicHttpAuthenticationFilter { + + private static final Logger LOG = LoggerFactory.getLogger(ODLHttpAuthenticationFilter.class); + + // defined in lower-case for more efficient string comparison + protected static final String BEARER_SCHEME = "bearer"; + + protected static final String OPTIONS_HEADER = "OPTIONS"; + + public ODLHttpAuthenticationFilter() { + super(); + LOG.info("Creating the ODLHttpAuthenticationFilter"); + } + + @Override + protected String[] getPrincipalsAndCredentials(String scheme, String encoded) { + final String decoded = Base64.decodeToString(encoded); + // attempt to decode username/password; otherwise decode as token + if (decoded.contains(":")) { + return decoded.split(":"); + } + return new String[] { encoded }; + } + + @Override + protected boolean isLoginAttempt(String authzHeader) { + final String authzScheme = getAuthzScheme().toLowerCase(); + final String authzHeaderLowerCase = authzHeader.toLowerCase(); + return authzHeaderLowerCase.startsWith(authzScheme) + || authzHeaderLowerCase.startsWith(BEARER_SCHEME); + } + + @Override + protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, + Object mappedValue) { + final HttpServletRequest httpRequest = WebUtils.toHttp(request); + final String httpMethod = httpRequest.getMethod(); + if (OPTIONS_HEADER.equalsIgnoreCase(httpMethod)) { + return true; + } else { + return super.isAccessAllowed(httpRequest, response, mappedValue); + } + } +} diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/moon/MoonPrincipal.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/moon/MoonPrincipal.java new file mode 100644 index 00000000..a95b4e7f --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/moon/MoonPrincipal.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.aaa.shiro.moon; + +import com.google.common.collect.ImmutableSet; + +import java.io.Serializable; +import java.util.Set; + +import org.opendaylight.aaa.api.Claim; + +public class MoonPrincipal { + + private final String username; + private final String domain; + private final String userId; + private final Set<String> roles; + private final String token; + + + public MoonPrincipal(String username, String domain, String userId, Set<String> roles, String token) { + this.username = username; + this.domain = domain; + this.userId = userId; + this.roles = roles; + this.token = token; + } + + public MoonPrincipal createODLPrincipal(String username, String domain, + String userId, Set<String> roles, String token) { + + return new MoonPrincipal(username, domain, userId, roles,token); + } + + public Claim principalToClaim (){ + return new MoonClaim("", this.getUserId(), this.getUsername(), this.getDomain(), this.getRoles()); + } + + public String getUsername() { + return this.username; + } + + public String getDomain() { + return this.domain; + } + + public String getUserId() { + return this.userId; + } + + public Set<String> getRoles() { + return this.roles; + } + + public String getToken(){ + return this.token; + } + + public class MoonClaim implements Claim, Serializable { + private static final long serialVersionUID = -8115027645190209125L; + private int hashCode = 0; + private String clientId; + private String userId; + private String user; + private String domain; + private ImmutableSet<String> roles; + + public MoonClaim(String clientId, String userId, String user, String domain, Set<String> roles) { + this.clientId = clientId; + this.userId = userId; + this.user = user; + this.domain = domain; + this.roles = ImmutableSet.<String> builder().addAll(roles).build(); + + if (userId.isEmpty() || user.isEmpty() || roles.isEmpty() || roles.contains("")) { + throw new IllegalStateException("The Claim is missing one or more of the required fields."); + } + } + + @Override + public String clientId() { + return clientId; + } + + @Override + public String userId() { + return userId; + } + + @Override + public String user() { + return user; + } + + @Override + public String domain() { + return domain; + } + + @Override + public Set<String> roles() { + return roles; + } + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public ImmutableSet<String> getRoles() { + return roles; + } + + public void setRoles(ImmutableSet<String> roles) { + this.roles = roles; + } + + @Override + public String toString() { + return "clientId:" + clientId + "," + "userId:" + userId + "," + "userName:" + user + + "," + "domain:" + domain + "," + "roles:" + roles ; + } + } +}
\ No newline at end of file diff --git a/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/moon/MoonTokenEndpoint.java b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/moon/MoonTokenEndpoint.java new file mode 100644 index 00000000..a954a606 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/java/org/opendaylight/aaa/shiro/moon/MoonTokenEndpoint.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro.moon; + + +import java.io.IOException; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MoonTokenEndpoint extends HttpServlet{ + + private static final long serialVersionUID = 4980356362831585417L; + private static final Logger LOG = LoggerFactory.getLogger(MoonTokenEndpoint.class); + + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + LOG.debug("MoonTokenEndpoint Servlet doPost"); + } + +}
\ No newline at end of file diff --git a/odl-aaa-moon/aaa-shiro/src/main/resources/WEB-INF/web.xml b/odl-aaa-moon/aaa-shiro/src/main/resources/WEB-INF/web.xml new file mode 100644 index 00000000..63288c23 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/resources/WEB-INF/web.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="ISO-8859-1"?> +<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" + version="3.0"> + + <servlet> + <servlet-name>MOON</servlet-name> + <servlet-class>org.opendaylight.aaa.shiro.moon.MoonTokenEndpoint</servlet-class> + <load-on-startup>1</load-on-startup> + </servlet> + + <servlet-mapping> + <servlet-name>MOON</servlet-name> + <url-pattern>/token</url-pattern> + </servlet-mapping> + <servlet-mapping> + <servlet-name>MOON</servlet-name> + <url-pattern>/revoke</url-pattern> + </servlet-mapping> + <servlet-mapping> + <servlet-name>MOON</servlet-name> + <url-pattern>/validate</url-pattern> + </servlet-mapping> + <servlet-mapping> + <servlet-name>MOON</servlet-name> + <url-pattern>/*</url-pattern> + </servlet-mapping> + + <!-- Shiro Filter --> + <context-param> + <param-name>shiroEnvironmentClass</param-name> + <param-value>org.opendaylight.aaa.shiro.web.env.KarafIniWebEnvironment</param-value> + </context-param> + + <listener> + <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class> + </listener> + + <filter> + <filter-name>ShiroFilter</filter-name> + <filter-class>org.opendaylight.aaa.shiro.filters.AAAFilter</filter-class> + </filter> + + <filter-mapping> + <filter-name>ShiroFilter</filter-name> + <url-pattern>/*</url-pattern> + </filter-mapping> +</web-app>
\ No newline at end of file diff --git a/odl-aaa-moon/aaa-shiro/src/main/resources/shiro.ini b/odl-aaa-moon/aaa-shiro/src/main/resources/shiro.ini new file mode 100644 index 00000000..d84f9fa0 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/main/resources/shiro.ini @@ -0,0 +1,95 @@ +# +# Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. +# +# This program and the accompanying materials are made available under the +# terms of the Eclipse Public License v1.0 which accompanies this distribution, +# and is available at http://www.eclipse.org/legal/epl-v10.html +# + +############################################################################### +# shiro.ini # +# # +# Configuration of OpenDaylight's aaa-shiro feature. Provided Realm # +# implementations include: # +# - TokenAuthRealm (enabled by default) # +# - ODLJndiLdapRealm (disabled by default) # +# - ODLJndiLdapRealmAuthNOnly (disabled by default) # +# Basic user configuration through shiro.ini is disabled for security # +# purposes. # +############################################################################### + + + +[main] +############################################################################### +# realms # +# # +# This section is dedicated to setting up realms for OpenDaylight. Realms # +# are essentially different methods for providing AAA. ODL strives to provide# +# highly-configurable AAA by providing pluggable infrastructure. By deafult, # +# TokenAuthRealm is enabled out of the box (which bridges to the existing AAA # +# mechanisms). More than one realm can be enabled, and the realms are # +# tried Round-Robin until: # +# 1) a realm successfully authenticates the incoming request # +# 2) all realms are exhausted, and 401 is returned # +############################################################################### + +# ODL provides a few LDAP implementations, which are disabled out of the box. +# ODLJndiLdapRealm includes authorization functionality based on LDAP elements +# extracted through and LDAP search. This requires a bit of knowledge about +# how your LDAP system is setup. An example is provided below: +#ldapRealm = org.opendaylight.aaa.shiro.realm.ODLJndiLdapRealm +#ldapRealm.userDnTemplate = uid={0},ou=People,dc=DOMAIN,dc=TLD +#ldapRealm.contextFactory.url = ldap://<URL>:389 +#ldapRealm.searchBase = dc=DOMAIN,dc=TLD +#ldapRealm.ldapAttributeForComparison = objectClass + +# ODL also provides ODLJndiLdapRealmAuthNOnly. Essentially, this allows +# access through AAAFilter to any user that can authenticate against the +# provided LDAP server. +#ldapRealm = org.opendaylight.aaa.shiro.realm.ODLJndiLdapRealmAuthNOnly +#ldapRealm.userDnTemplate = uid={0},ou=People,dc=DOMAIN,dc=TLD +#ldapRealm.contextFactory.url = ldap://<URL>:389 + +# Bridge to existing h2/idmlight/mdsal authentication/authorization mechanisms. +# This realm is enabled by default, and utilizes h2-store by default. +tokenAuthRealm = org.opendaylight.aaa.shiro.realm.TokenAuthRealm +moonAuthRealm = org.opendaylight.aaa.shiro.realm.MoonRealm + +# The CSV list of enabled realms. In order to enable a realm, add it to the +# list below: +securityManager.realms = $moonAuthRealm + + +# adds a custom AuthenticationFilter to support OAuth2 for backwards +# compatibility. To disable OAuth2 access, just comment out the next line +# and authcBasic will default to BasicHttpAuthenticationFilter, a +# Shiro-provided class. +authcBasic = org.opendaylight.aaa.shiro.filters.ODLHttpAuthenticationFilter +# OAuth2 Filer for moon token AuthN +rest = org.opendaylight.aaa.shiro.filters.MoonOAuthFilter + + + +[urls] +############################################################################### +# url authorization section # +# # +# This section is dedicated to defining url-based authorization according to: # +# http://shiro.apache.org/web.html # +############################################################################### +#Filtering REST requests with AAAFilter +/v1/users** = authcBasic +/v1/domains** = authcBasic +/v1/roles** = authcBasic + +#Filter OAuth2 request$ +/token = rest + +# General access through AAAFilter requires valid credentials (AuthN only). +/** = authcBasic + +# Access to the credential store is limited to the valid users who have the +# admin role. The following line is only needed if the mdsal store is enabled +#(the mdsal store is disabled by default). +/config/aaa-authn-model** = authcBasic,roles[admin] diff --git a/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/ServiceProxyTest.java b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/ServiceProxyTest.java new file mode 100644 index 00000000..2d9c8976 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/ServiceProxyTest.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.opendaylight.aaa.shiro.filters.AAAFilter; + +/** + * @author Ryan Goulding (ryandgoulding@gmail.com) + */ +public class ServiceProxyTest { + + @Test + public void testGetInstance() { + // ensures that singleton pattern is working + assertNotNull(ServiceProxy.getInstance()); + } + + @Test + public void testGetSetEnabled() { + // combines set and get tests. These are important in this instance, + // because getEnabled allows an optional callback Filter. + ServiceProxy.getInstance().setEnabled(true); + assertTrue(ServiceProxy.getInstance().getEnabled(null)); + + AAAFilter testFilter = new AAAFilter(); + // register the filter + ServiceProxy.getInstance().getEnabled(testFilter); + assertTrue(testFilter.isEnabled()); + + ServiceProxy.getInstance().setEnabled(false); + assertFalse(ServiceProxy.getInstance().getEnabled(testFilter)); + assertFalse(testFilter.isEnabled()); + } +} diff --git a/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/authorization/DefaultRBACRulesTest.java b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/authorization/DefaultRBACRulesTest.java new file mode 100644 index 00000000..38658f0c --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/authorization/DefaultRBACRulesTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro.authorization; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import com.google.common.collect.Sets; +import java.util.Collection; +import org.junit.Test; + +/** + * A few basic test cases for the DefualtRBACRules singleton container. + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + * + */ +public class DefaultRBACRulesTest { + + @Test + public void testGetInstance() { + assertNotNull(DefaultRBACRules.getInstance()); + assertEquals(DefaultRBACRules.getInstance(), DefaultRBACRules.getInstance()); + } + + @Test + public void testGetRBACRules() { + Collection<RBACRule> rbacRules = DefaultRBACRules.getInstance().getRBACRules(); + assertNotNull(rbacRules); + + // check that a copy was returned + int originalSize = rbacRules.size(); + rbacRules.add(RBACRule.createAuthorizationRule("fakeurl/*", Sets.newHashSet("admin"))); + assertEquals(originalSize, DefaultRBACRules.getInstance().getRBACRules().size()); + } + +} diff --git a/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/authorization/RBACRuleTest.java b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/authorization/RBACRuleTest.java new file mode 100644 index 00000000..825fe626 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/authorization/RBACRuleTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro.authorization; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.Sets; +import java.util.Collection; +import java.util.HashSet; +import org.junit.Test; + +public class RBACRuleTest { + + private static final String BASIC_RBAC_RULE_URL_PATTERN = "/*"; + private static final Collection<String> BASIC_RBAC_RULE_ROLES = Sets.newHashSet("admin"); + private RBACRule basicRBACRule = RBACRule.createAuthorizationRule(BASIC_RBAC_RULE_URL_PATTERN, + BASIC_RBAC_RULE_ROLES); + + private static final String COMPLEX_RBAC_RULE_URL_PATTERN = "/auth/v1/"; + private static final Collection<String> COMPLEX_RBAC_RULE_ROLES = Sets.newHashSet("admin", + "user"); + private RBACRule complexRBACRule = RBACRule.createAuthorizationRule( + COMPLEX_RBAC_RULE_URL_PATTERN, COMPLEX_RBAC_RULE_ROLES); + + @Test + public void testCreateAuthorizationRule() { + // positive test cases + assertNotNull(RBACRule.createAuthorizationRule(BASIC_RBAC_RULE_URL_PATTERN, + BASIC_RBAC_RULE_ROLES)); + assertNotNull(RBACRule.createAuthorizationRule(COMPLEX_RBAC_RULE_URL_PATTERN, + COMPLEX_RBAC_RULE_ROLES)); + + // negative test cases + // both null + assertNull(RBACRule.createAuthorizationRule(null, null)); + + // url pattern is null + assertNull(RBACRule.createAuthorizationRule(null, BASIC_RBAC_RULE_ROLES)); + // url pattern is empty string + assertNull(RBACRule.createAuthorizationRule("", BASIC_RBAC_RULE_ROLES)); + + // roles is null + assertNull(RBACRule.createAuthorizationRule(BASIC_RBAC_RULE_URL_PATTERN, null)); + // roles is empty collection + assertNull(RBACRule.createAuthorizationRule(COMPLEX_RBAC_RULE_URL_PATTERN, + new HashSet<String>())); + } + + @Test + public void testGetUrlPattern() { + assertEquals(BASIC_RBAC_RULE_URL_PATTERN, basicRBACRule.getUrlPattern()); + assertEquals(COMPLEX_RBAC_RULE_URL_PATTERN, complexRBACRule.getUrlPattern()); + } + + @Test + public void testGetRoles() { + assertTrue(BASIC_RBAC_RULE_ROLES.containsAll(basicRBACRule.getRoles())); + basicRBACRule.getRoles().clear(); + // test that getRoles() produces a new object + assertFalse(basicRBACRule.getRoles().isEmpty()); + assertTrue(basicRBACRule.getRoles().containsAll(BASIC_RBAC_RULE_ROLES)); + + assertTrue(COMPLEX_RBAC_RULE_ROLES.containsAll(complexRBACRule.getRoles())); + complexRBACRule.getRoles().add("newRole"); + // test that getRoles() produces a new object + assertFalse(complexRBACRule.getRoles().contains("newRole")); + assertTrue(complexRBACRule.getRoles().containsAll(COMPLEX_RBAC_RULE_ROLES)); + } + + @Test + public void testGetRolesInShiroFormat() { + final String BASIC_RBAC_RULE_EXPECTED_SHIRO_FORMAT = "roles[admin]"; + assertEquals(BASIC_RBAC_RULE_EXPECTED_SHIRO_FORMAT, basicRBACRule.getRolesInShiroFormat()); + + // set ordering is not predictable, so both formats must be considered + final String COMPLEX_RBAC_RULE_EXPECTED_SHIRO_FORMAT_1 = "roles[admin, user]"; + final String COMPLEX_RBAC_RULE_EXPECTED_SHIRO_FORMAT_2 = "roles[user, admin]"; + assertTrue(COMPLEX_RBAC_RULE_EXPECTED_SHIRO_FORMAT_1.equals(complexRBACRule + .getRolesInShiroFormat()) + || COMPLEX_RBAC_RULE_EXPECTED_SHIRO_FORMAT_2.equals(complexRBACRule + .getRolesInShiroFormat())); + } + + @Test + public void testToString() { + final String BASIC_RBAC_RULE_EXPECTED_SHIRO_FORMAT = "/*=roles[admin]"; + assertEquals(BASIC_RBAC_RULE_EXPECTED_SHIRO_FORMAT, basicRBACRule.toString()); + + // set ordering is not predictable,s o both formats must be considered + final String COMPLEX_RBAC_RULE_EXPECTED_SHIRO_FORMAT_1 = "/auth/v1/=roles[admin, user]"; + final String COMPLEX_RBAC_RULE_EXPECTED_SHIRO_FORMAT_2 = "/auth/v1/=roles[user, admin]"; + assertTrue(COMPLEX_RBAC_RULE_EXPECTED_SHIRO_FORMAT_1.equals(complexRBACRule.toString()) + || COMPLEX_RBAC_RULE_EXPECTED_SHIRO_FORMAT_2.equals(complexRBACRule.toString())); + } + +} diff --git a/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/realm/ODLJndiLdapRealmTest.java b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/realm/ODLJndiLdapRealmTest.java new file mode 100644 index 00000000..22ce203f --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/realm/ODLJndiLdapRealmTest.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro.realm; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.Vector; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.BasicAttributes; +import javax.naming.directory.SearchControls; +import javax.naming.directory.SearchResult; +import javax.naming.ldap.LdapContext; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.realm.ldap.LdapContextFactory; +import org.apache.shiro.subject.PrincipalCollection; +import org.junit.Test; + +/** + * @author Ryan Goulding (ryandgoulding@gmail.com) + */ +public class ODLJndiLdapRealmTest { + + /** + * throw-away anonymous test class + */ + class TestNamingEnumeration implements NamingEnumeration<SearchResult> { + + /** + * state variable + */ + boolean first = true; + + /** + * returned the first time <code>next()</code> or + * <code>nextElement()</code> is called. + */ + SearchResult searchResult = new SearchResult("testuser", null, new BasicAttributes( + "objectClass", "engineering")); + + /** + * returns true the first time, then false for subsequent calls + */ + @Override + public boolean hasMoreElements() { + return first; + } + + /** + * returns <code>searchResult</code> then null for subsequent calls + */ + @Override + public SearchResult nextElement() { + if (first) { + first = false; + return searchResult; + } + return null; + } + + /** + * does nothing because close() doesn't require any special behavior + */ + @Override + public void close() throws NamingException { + } + + /** + * returns true the first time, then false for subsequent calls + */ + @Override + public boolean hasMore() throws NamingException { + return first; + } + + /** + * returns <code>searchResult</code> then null for subsequent calls + */ + @Override + public SearchResult next() throws NamingException { + if (first) { + first = false; + return searchResult; + } + return null; + } + }; + + /** + * throw away test class + * + * @author ryan + */ + class TestPrincipalCollection implements PrincipalCollection { + /** + * + */ + private static final long serialVersionUID = -1236759619455574475L; + + Vector<String> collection = new Vector<String>(); + + public TestPrincipalCollection(String element) { + collection.add(element); + } + + @Override + public Iterator<String> iterator() { + return collection.iterator(); + } + + @Override + public List<String> asList() { + return collection; + } + + @Override + public Set<String> asSet() { + HashSet<String> set = new HashSet<String>(); + set.addAll(collection); + return set; + } + + @Override + public <T> Collection<T> byType(Class<T> arg0) { + return null; + } + + @Override + public Collection<String> fromRealm(String arg0) { + return collection; + } + + @Override + public Object getPrimaryPrincipal() { + return collection.firstElement(); + } + + @Override + public Set<String> getRealmNames() { + return null; + } + + @Override + public boolean isEmpty() { + return collection.isEmpty(); + } + + @Override + public <T> T oneByType(Class<T> arg0) { + // TODO Auto-generated method stub + return null; + } + }; + + @Test + public void testGetUsernameAuthenticationToken() { + AuthenticationToken authenticationToken = null; + assertNull(ODLJndiLdapRealm.getUsername(authenticationToken)); + AuthenticationToken validAuthenticationToken = new UsernamePasswordToken("test", + "testpassword"); + assertEquals("test", ODLJndiLdapRealm.getUsername(validAuthenticationToken)); + } + + @Test + public void testGetUsernamePrincipalCollection() { + PrincipalCollection pc = null; + assertNull(new ODLJndiLdapRealm().getUsername(pc)); + TestPrincipalCollection tpc = new TestPrincipalCollection("testuser"); + String username = new ODLJndiLdapRealm().getUsername(tpc); + assertEquals("testuser", username); + } + + @Test + public void testQueryForAuthorizationInfoPrincipalCollectionLdapContextFactory() + throws NamingException { + LdapContext ldapContext = mock(LdapContext.class); + // emulates an ldap search and returns the mocked up test class + when( + ldapContext.search((String) any(), (String) any(), + (SearchControls) any())).thenReturn(new TestNamingEnumeration()); + LdapContextFactory ldapContextFactory = mock(LdapContextFactory.class); + when(ldapContextFactory.getSystemLdapContext()).thenReturn(ldapContext); + AuthorizationInfo authorizationInfo = new ODLJndiLdapRealm().queryForAuthorizationInfo( + new TestPrincipalCollection("testuser"), ldapContextFactory); + assertNotNull(authorizationInfo); + assertFalse(authorizationInfo.getRoles().isEmpty()); + assertTrue(authorizationInfo.getRoles().contains("engineering")); + } + + @Test + public void testBuildAuthorizationInfo() { + assertNull(ODLJndiLdapRealm.buildAuthorizationInfo(null)); + Set<String> roleNames = new HashSet<String>(); + roleNames.add("engineering"); + AuthorizationInfo authorizationInfo = ODLJndiLdapRealm.buildAuthorizationInfo(roleNames); + assertNotNull(authorizationInfo); + assertFalse(authorizationInfo.getRoles().isEmpty()); + assertTrue(authorizationInfo.getRoles().contains("engineering")); + } + + @Test + public void testGetRoleNamesForUser() throws NamingException { + ODLJndiLdapRealm ldapRealm = new ODLJndiLdapRealm(); + LdapContext ldapContext = mock(LdapContext.class); + + // emulates an ldap search and returns the mocked up test class + when( + ldapContext.search((String) any(), (String) any(), + (SearchControls) any())).thenReturn(new TestNamingEnumeration()); + + // extracts the roles for "testuser" and ensures engineering is returned + Set<String> roles = ldapRealm.getRoleNamesForUser("testuser", ldapContext); + assertFalse(roles.isEmpty()); + assertTrue(roles.iterator().next().equals("engineering")); + } + + @Test + public void testCreateSearchControls() { + SearchControls searchControls = ODLJndiLdapRealm.createSearchControls(); + assertNotNull(searchControls); + int expectedSearchScope = SearchControls.SUBTREE_SCOPE; + int actualSearchScope = searchControls.getSearchScope(); + assertEquals(expectedSearchScope, actualSearchScope); + } + +} diff --git a/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/realm/TokenAuthRealmTest.java b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/realm/TokenAuthRealmTest.java new file mode 100644 index 00000000..f2eb92b5 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/realm/TokenAuthRealmTest.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro.realm; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.common.collect.Lists; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.shiro.authc.AuthenticationToken; +import org.junit.Test; + +/** + * + * @author Ryan Goulding (ryandgoulding@gmail.com) + * + */ +public class TokenAuthRealmTest extends TokenAuthRealm { + + private TokenAuthRealm testRealm = new TokenAuthRealm(); + + @Test + public void testTokenAuthRealm() { + assertEquals("TokenAuthRealm", testRealm.getName()); + } + + @Test(expected = NullPointerException.class) + public void testDoGetAuthorizationInfoPrincipalCollectionNullCacheToken() { + testRealm.doGetAuthorizationInfo(null); + } + + @Test + public void testGetUsernamePasswordDomainString() { + final String username = "user"; + final String password = "password"; + final String domain = "domain"; + final String expectedUsernamePasswordString = "user:password:domain"; + assertEquals(expectedUsernamePasswordString, getUsernamePasswordDomainString(username, password, domain)); + } + + @Test + public void testGetEncodedToken() { + final String stringToEncode = "admin1:admin1"; + final byte[] bytesToEncode = stringToEncode.getBytes(); + final String expectedToken = org.apache.shiro.codec.Base64.encodeToString(bytesToEncode); + assertEquals(expectedToken, getEncodedToken(stringToEncode)); + } + + @Test + public void testGetTokenAuthHeader() { + final String encodedCredentials = getEncodedToken(getUsernamePasswordDomainString("user1", + "password", "sdn")); + final String expectedTokenAuthHeader = "Basic " + encodedCredentials; + assertEquals(expectedTokenAuthHeader, getTokenAuthHeader(encodedCredentials)); + } + + @Test + public void testFormHeadersWithToken() { + final String authHeader = getEncodedToken(getTokenAuthHeader(getUsernamePasswordDomainString( + "user1", "password", "sdn"))); + final Map<String, List<String>> expectedHeaders = new HashMap<String, List<String>>(); + expectedHeaders.put("Authorization", Lists.newArrayList(authHeader)); + final Map<String, List<String>> actualHeaders = formHeadersWithToken(authHeader); + List<String> value; + for (String key : expectedHeaders.keySet()) { + value = expectedHeaders.get(key); + assertTrue(actualHeaders.get(key).equals(value)); + } + } + + @Test + public void testFormHeaders() { + final String username = "basicUser"; + final String password = "basicPassword"; + final String domain = "basicDomain"; + final String authHeader = getTokenAuthHeader(getEncodedToken(getUsernamePasswordDomainString( + username, password, domain))); + final Map<String, List<String>> expectedHeaders = new HashMap<String, List<String>>(); + expectedHeaders.put("Authorization", Lists.newArrayList(authHeader)); + final Map<String, List<String>> actualHeaders = formHeaders(username, password, domain); + List<String> value; + for (String key : expectedHeaders.keySet()) { + value = expectedHeaders.get(key); + assertTrue(actualHeaders.get(key).equals(value)); + } + } + + @Test + public void testIsTokenAuthAvailable() { + assertFalse(testRealm.isTokenAuthAvailable()); + } + + @Test(expected = org.apache.shiro.authc.AuthenticationException.class) + public void testDoGetAuthenticationInfoAuthenticationToken() { + testRealm.doGetAuthenticationInfo(null); + } + + @Test + public void testExtractUsernameNullUsername() { + AuthenticationToken at = mock(AuthenticationToken.class); + when(at.getPrincipal()).thenReturn(null); + assertNull(extractUsername(at)); + } + + @Test(expected = ClassCastException.class) + public void testExtractPasswordNullPassword() { + AuthenticationToken at = mock(AuthenticationToken.class); + when(at.getPrincipal()).thenReturn("username"); + when(at.getCredentials()).thenReturn(null); + extractPassword(at); + } + + @Test(expected = ClassCastException.class) + public void testExtractUsernameBadUsernameClass() { + AuthenticationToken at = mock(AuthenticationToken.class); + when(at.getPrincipal()).thenReturn(new Integer(1)); + extractUsername(at); + } + + @Test(expected = ClassCastException.class) + public void testExtractPasswordBadPasswordClass() { + AuthenticationToken at = mock(AuthenticationToken.class); + when(at.getPrincipal()).thenReturn("username"); + when(at.getCredentials()).thenReturn(new Integer(1)); + extractPassword(at); + } +} diff --git a/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/web/env/KarafIniWebEnvironmentTest.java b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/web/env/KarafIniWebEnvironmentTest.java new file mode 100644 index 00000000..141d0ce5 --- /dev/null +++ b/odl-aaa-moon/aaa-shiro/src/test/java/org/opendaylight/aaa/shiro/web/env/KarafIniWebEnvironmentTest.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.aaa.shiro.web.env; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import org.apache.shiro.config.Ini; +import org.apache.shiro.config.Ini.Section; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * @author Ryan Goulding (ryandgoulding@gmail.com) + */ +public class KarafIniWebEnvironmentTest { + private static File iniFile; + + @BeforeClass + public static void setup() throws IOException { + iniFile = createShiroIniFile(); + assertTrue(iniFile.exists()); + } + + @AfterClass + public static void teardown() { + iniFile.delete(); + } + + private static String createFakeShiroIniContents() { + return "[users]\n" + "admin=admin, ROLE_ADMIN \n" + "[roles]\n" + "ROLE_ADMIN = *\n" + + "[urls]\n" + "/** = authcBasic"; + } + + private static File createShiroIniFile() throws IOException { + File shiroIni = File.createTempFile("shiro", "ini"); + FileWriter writer = new FileWriter(shiroIni); + writer.write(createFakeShiroIniContents()); + writer.flush(); + writer.close(); + return shiroIni; + } + + @Test + public void testCreateShiroIni() throws IOException { + Ini ini = KarafIniWebEnvironment.createShiroIni(iniFile.getAbsolutePath()); + assertNotNull(ini); + assertNotNull(ini.getSection("users")); + assertNotNull(ini.getSection("roles")); + assertNotNull(ini.getSection("urls")); + Section usersSection = ini.getSection("users"); + assertTrue(usersSection.containsKey("admin")); + assertTrue(usersSection.get("admin").contains("admin")); + assertTrue(usersSection.get("admin").contains("ROLE_ADMIN")); + } + + @Test + public void testCreateFileBasedIniPath() { + String testPath = "/shiro.ini"; + String expectedFileBasedIniPath = KarafIniWebEnvironment.SHIRO_FILE_PREFIX + testPath; + String actualFileBasedIniPath = KarafIniWebEnvironment.createFileBasedIniPath(testPath); + assertEquals(expectedFileBasedIniPath, actualFileBasedIniPath); + } + +} |