1
0
mirror of synced 2026-08-03 16:56:56 +00:00

SEC-1743: Separate remoting from core into separate module.

This commit is contained in:
Luke Taylor
2011-05-14 11:57:30 +01:00
parent 1c1ffe2f0f
commit 295ea27526
22 changed files with 65 additions and 5 deletions
@@ -1,39 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.dns;
/**
* This will be thrown if no entry matches the specified DNS query.
*
* @author Mike Wiesner
* @since 3.0
*/
public class DnsEntryNotFoundException extends DnsLookupException {
private static final long serialVersionUID = -947232730426775162L;
public DnsEntryNotFoundException(String msg) {
super(msg);
}
public DnsEntryNotFoundException(String msg, Throwable cause) {
super(msg, cause);
}
}
@@ -1,35 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.dns;
/**
* This will be thrown for unknown DNS errors.
*
* @author Mike Wiesner
* @since 3.0
*/
public class DnsLookupException extends RuntimeException {
public DnsLookupException(String msg, Throwable cause) {
super(msg, cause);
}
public DnsLookupException(String msg) {
super(msg);
}
}
@@ -1,73 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.dns;
/**
* Helper class for DNS operations.
*
* @author Mike Wiesner
* @since 3.0
*/
public interface DnsResolver {
/**
* Resolves the IP Address (A record) to the specified host name.
* Throws DnsEntryNotFoundException if there is no record.
*
* @param hostname The hostname for which you need the IP Address
* @return IP Address as a String
* @throws DnsEntryNotFoundException No record found
* @throws DnsLookupException Unknown DNS error
*/
public String resolveIpAddress(String hostname) throws DnsEntryNotFoundException, DnsLookupException;
/**
* <p>Resolves the host name for the specified service in the specified domain</p>
* <p>For example, if you need the host name for an LDAP server running in the
* domain springsource.com, you would call <b>resolveServiceEntry("ldap", "springsource.com")</b>.</p>
*
* <p>The DNS server needs to provide the service records for this, in the example above, it
* would look like this:
*
* <pre>_ldap._tcp.springsource.com IN SRV 10 0 88 ldap.springsource.com.</pre>
*
* The method will return the record with highest priority (which means the lowest number in the DNS record)
* and if there are more than one records with the same priority, it will return the one with the highest weight.
* You will find more informatione about DNS service records at <a href="http://en.wikipedia.org/wiki/SRV_record">Wikipedia</a>.</p>
*
* @param serviceType The service type you are searching for, e.g. ldap, kerberos, ...
* @param domain The domain, in which you are searching for the service
* @return The hostname of the service
* @throws DnsEntryNotFoundException No record found
* @throws DnsLookupException Unknown DNS error
*/
public String resolveServiceEntry(String serviceType, String domain) throws DnsEntryNotFoundException, DnsLookupException;
/**
* Resolves the host name for the specified service and then the IP Address for this host in one call.
*
* @param serviceType The service type you are searching for, e.g. ldap, kerberos, ...
* @param domain The domain, in which you are searching for the service
* @return IP Address of the service
* @throws DnsEntryNotFoundException No record found
* @throws DnsLookupException Unknown DNS error
* @see #resolveServiceEntry(String, String)
* @see #resolveIpAddress(String)
*/
public String resolveServiceIpAddress(String serviceType, String domain) throws DnsEntryNotFoundException, DnsLookupException;
}
@@ -1,41 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.dns;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
* This is used in JndiDnsResolver to get an InitialDirContext for DNS queries.
*
* @author Mike Wiesner
* @since 3.0
* @see InitialDirContext
* @see DirContext
* @see JndiDnsResolver
*/
public interface InitialContextFactory {
/**
* Must return a DirContext which can be used for DNS queries
* @return JNDI DirContext
*/
public DirContext getCtx();
}
@@ -1,168 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.dns;
import java.util.*;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
* Implementation of DnsResolver which uses JNDI for the DNS queries.
*
* Uses an <b>InitialContextFactory</b> to get the JNDI DirContext. The default implementation
* will just create a new Context with the context factory <b>com.sun.jndi.dns.DnsContextFactory</b>
*
* @author Mike Wiesner
* @since 3.0
* @see DnsResolver
* @see InitialContextFactory
*/
public class JndiDnsResolver implements DnsResolver {
private InitialContextFactory ctxFactory = new DefaultInitialContextFactory();
/**
* Allows to inject an own JNDI context factory.
*
* @param ctxFactory factory to use, when a DirContext is needed
* @see InitialDirContext
* @see DirContext
*/
public void setCtxFactory(InitialContextFactory ctxFactory) {
this.ctxFactory = ctxFactory;
}
/* (non-Javadoc)
* @see org.springframework.security.remoting.dns.DnsResolver#resolveIpAddress(java.lang.String)
*/
public String resolveIpAddress(String hostname) {
return resolveIpAddress(hostname, ctxFactory.getCtx());
}
/* (non-Javadoc)
* @see org.springframework.security.remoting.dns.DnsResolver#resolveServiceEntry(java.lang.String, java.lang.String)
*/
public String resolveServiceEntry(String serviceType, String domain) {
return resolveServiceEntry(serviceType, domain, ctxFactory.getCtx());
}
/* (non-Javadoc)
* @see org.springframework.security.remoting.dns.DnsResolver#resolveServiceIpAddress(java.lang.String, java.lang.String)
*/
public String resolveServiceIpAddress(String serviceType, String domain) {
DirContext ctx = ctxFactory.getCtx();
String hostname = resolveServiceEntry(serviceType, domain, ctx);
return resolveIpAddress(hostname, ctx);
}
// This method is needed, so that we can use only one DirContext for
// resolveServiceIpAddress().
private String resolveIpAddress(String hostname, DirContext ctx) {
try {
Attribute dnsRecord = lookup(hostname, ctx, "A");
// There should be only one A record, therefore it is save to return
// only the first.
return dnsRecord.get().toString();
} catch (NamingException e) {
throw new DnsLookupException("DNS lookup failed for: "+ hostname, e);
}
}
// This method is needed, so that we can use only one DirContext for
// resolveServiceIpAddress().
private String resolveServiceEntry(String serviceType, String domain, DirContext ctx) {
String result = null;
try {
String query = new StringBuilder("_").append(serviceType).append("._tcp.").append(domain).toString();
Attribute dnsRecord = lookup(query, ctx, "SRV");
// There are maybe more records defined, we will return the one
// with the highest priority (lowest number) and the highest weight
// (highest number)
int highestPriority = -1;
int highestWeight = -1;
for (NamingEnumeration<?> recordEnum = dnsRecord.getAll(); recordEnum.hasMoreElements();) {
String[] record = recordEnum.next().toString().split(" ");
if (record.length != 4) {
throw new DnsLookupException("Wrong service record for query " + query + ": [" + Arrays.toString(record) + "]");
}
int priority = Integer.parseInt(record[0]);
int weight = Integer.parseInt(record[1]);
// we have a new highest Priority, so forget also the highest weight
if (priority < highestPriority || highestPriority == -1) {
highestPriority = priority;
highestWeight = weight;
result = record[3].trim();
}
// same priority, but higher weight
if (priority == highestPriority && weight > highestWeight) {
highestWeight = weight;
result = record[3].trim();
}
}
} catch (NamingException e) {
throw new DnsLookupException("DNS lookup failed for service " + serviceType + " at " + domain, e);
}
// remove the "." at the end
if (result.endsWith(".")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
private Attribute lookup(String query, DirContext ictx, String recordType) {
try {
Attributes dnsResult = ictx.getAttributes(query, new String[] { recordType });
return dnsResult.get(recordType);
} catch (NamingException e) {
if (e instanceof NameNotFoundException) {
throw new DnsEntryNotFoundException("DNS entry not found for:" + query, e);
}
throw new DnsLookupException("DNS lookup failed for: " + query, e);
}
}
private static class DefaultInitialContextFactory implements InitialContextFactory {
public DirContext getCtx() {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
env.put(Context.PROVIDER_URL, "dns:"); // This is needed for IBM JDK/JRE
InitialDirContext ictx;
try {
ictx = new InitialDirContext(env);
} catch (NamingException e) {
throw new DnsLookupException("Cannot create InitialDirContext for DNS lookup", e);
}
return ictx;
}
}
}
@@ -1,4 +0,0 @@
/**
* DNS resolution.
*/
package org.springframework.security.remoting.dns;
@@ -1,85 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.httpinvoker;
import java.io.IOException;
import java.net.HttpURLConnection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Adds BASIC authentication support to <code>SimpleHttpInvokerRequestExecutor</code>.
*
* @author Ben Alex
*/
public class AuthenticationSimpleHttpInvokerRequestExecutor extends SimpleHttpInvokerRequestExecutor {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(AuthenticationSimpleHttpInvokerRequestExecutor.class);
//~ Methods ========================================================================================================
/**
* Provided so subclasses can perform additional configuration if required (eg set additional request
* headers for non-security related information etc).
*
* @param con the HTTP connection to prepare
* @param contentLength the length of the content to send
*
* @throws IOException if thrown by HttpURLConnection methods
*/
protected void doPrepareConnection(HttpURLConnection con, int contentLength)
throws IOException {}
/**
* Called every time a HTTP invocation is made.<p>Simply allows the parent to setup the connection, and
* then adds an <code>Authorization</code> HTTP header property that will be used for BASIC authentication.</p>
* <p>The <code>SecurityContextHolder</code> is used to obtain the relevant principal and credentials.</p>
*
* @param con the HTTP connection to prepare
* @param contentLength the length of the content to send
*
* @throws IOException if thrown by HttpURLConnection methods
*/
protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException {
super.prepareConnection(con, contentLength);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null)) {
String base64 = auth.getName() + ":" + auth.getCredentials().toString();
con.setRequestProperty("Authorization", "Basic " + new String(Base64.encode(base64.getBytes())));
if (logger.isDebugEnabled()) {
logger.debug("HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived: "
+ auth.toString());
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Unable to set BASIC authentication header as SecurityContext did not provide "
+ "valid Authentication: " + auth);
}
}
doPrepareConnection(con, contentLength);
}
}
@@ -1,19 +0,0 @@
/**
* Enables use of Spring's <code>HttpInvoker</code> extension points to
* present the <code>principal</code> and <code>credentials</code> located
* in the <code>ContextHolder</code> via BASIC authentication.
* <p>
* The beans are wired as follows:
*
* <pre>
* &lt;bean id="test" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"&gt;
* &lt;property name="serviceUrl"&gt;&lt;value&gt;http://localhost/Test&lt;/value&gt;&lt;/property&gt;
* &lt;property name="serviceInterface"&gt;&lt;value&gt;test.TargetInterface&lt;/value&gt;&lt;/property&gt;
* &lt;property name="httpInvokerRequestExecutor"&gt;&lt;ref bean="httpInvokerRequestExecutor"/&gt;&lt;/property&gt;
* &lt;/bean&gt;
*
* &lt;bean id="httpInvokerRequestExecutor"
* class="org.springframework.security.core.context.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor"/&gt;
* </pre>
*/
package org.springframework.security.remoting.httpinvoker;
@@ -1,4 +0,0 @@
/**
* Remote client related functionality.
*/
package org.springframework.security.remoting;
@@ -1,114 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.rmi;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.remoting.support.RemoteInvocation;
import java.lang.reflect.InvocationTargetException;
/**
* The actual <code>RemoteInvocation</code> that is passed from the client to the server, which contains the
* contents of {@link SecurityContextHolder}, being a {@link SecurityContext} object.
* <p>
* When constructed on the client via {@link ContextPropagatingRemoteInvocationFactory}, the contents of the
* <code>SecurityContext</code> are stored inside the object. The object is then passed to the server that is
* processing the remote invocation. Upon the server invoking the remote invocation, it will retrieve the passed
* contents of the <code>SecurityContextHolder</code> and set them on the server-side
* <code>SecurityContextHolder</code> while the target object is invoked. When the target invocation has been
* completed, the security context will be cleared using a call to {@link SecurityContextHolder#clearContext()}.
*
* @author James Monaghan
* @author Ben Alex
*/
public class ContextPropagatingRemoteInvocation extends RemoteInvocation {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private static final Log logger = LogFactory.getLog(ContextPropagatingRemoteInvocation.class);
//~ Instance fields ================================================================================================
private final SecurityContext securityContext;
//~ Constructors ===================================================================================================
/**
* Constructs the object, storing the value of the client-side
* <code>SecurityContextHolder</code> inside the object.
*
* @param methodInvocation the method to invoke
*/
public ContextPropagatingRemoteInvocation(MethodInvocation methodInvocation) {
super(methodInvocation);
securityContext = SecurityContextHolder.getContext();
if (logger.isDebugEnabled()) {
logger.debug("RemoteInvocation now has SecurityContext: " + securityContext);
}
}
//~ Methods ========================================================================================================
/**
* Invoked on the server-side as described in the class JavaDocs.
* <p>
* Invocations will always have their {@link org.springframework.security.core.Authentication#setAuthenticated(boolean)}
* set to <code>false</code>, which is guaranteed to always be accepted by <code>Authentication</code>
* implementations. This ensures that even remotely authenticated <code>Authentication</code>s will be untrusted by
* the server-side, which is an appropriate security measure.
*
* @param targetObject the target object to apply the invocation to
*
* @return the invocation result
*
* @throws NoSuchMethodException if the method name could not be resolved
* @throws IllegalAccessException if the method could not be accessed
* @throws InvocationTargetException if the method invocation resulted in an exception
*/
public Object invoke(Object targetObject)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
SecurityContextHolder.setContext(securityContext);
if ((SecurityContextHolder.getContext() != null)
&& (SecurityContextHolder.getContext().getAuthentication() != null)) {
SecurityContextHolder.getContext().getAuthentication().setAuthenticated(false);
}
if (logger.isDebugEnabled()) {
logger.debug("Set SecurityContextHolder to contain: " + securityContext);
}
try {
return super.invoke(targetObject);
} finally {
SecurityContextHolder.clearContext();
if (logger.isDebugEnabled()) {
logger.debug("Cleared SecurityContextHolder.");
}
}
}
}
@@ -1,38 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.rmi;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.remoting.support.RemoteInvocation;
import org.springframework.remoting.support.RemoteInvocationFactory;
/**
* Called by a client-side instance of <code>org.springframework.remoting.rmi.RmiProxyFactoryBean</code> when it
* wishes to create a remote invocation.<P>Set an instance of this bean against the above class'
* <code>remoteInvocationFactory</code> property.</p>
*
* @author James Monaghan
* @author Ben Alex
*/
public class ContextPropagatingRemoteInvocationFactory implements RemoteInvocationFactory {
//~ Methods ========================================================================================================
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
return new ContextPropagatingRemoteInvocation(methodInvocation);
}
}
@@ -1,18 +0,0 @@
/**
* Enables use of Spring's RMI remoting extension points to propagate the <code>SecurityContextHolder</code> (which
* should contain an <code>Authentication</code> request token) from one JVM to the remote JVM.
* <p>
* The beans are wired as follows:
* <pre>
* &lt;bean id="test" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"&gt;
* &lt;property name="serviceUrl"&gt;&lt;value&gt;rmi://localhost/Test&lt;/value&gt;&lt;/property&gt;
* &lt;property name="serviceInterface"&gt;&lt;value&gt;test.TargetInterface&lt;/value&gt;&lt;/property&gt;
* &lt;property name="refreshStubOnConnectFailure"&gt;&lt;value&gt;true&lt;/value&gt;&lt;/property&gt;
* &lt;property name="remoteInvocationFactory"&gt;&lt;ref bean="remoteInvocationFactory"/&gt;&lt;/property&gt;
* &lt;/bean&gt;
*
* &lt;bean id="remoteInvocationFactory"
* class="org.springframework.security.remoting.rmi.ContextPropagatingRemoteInvocationFactory"/&gt;
* </pre>
*/
package org.springframework.security.remoting.rmi;
@@ -1,119 +0,0 @@
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.dns;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Mike Wiesner
* @since 3.0
*/
public class JndiDnsResolverTest {
private JndiDnsResolver dnsResolver;
private InitialContextFactory contextFactory;
private DirContext context;
@Before
public void setup() {
contextFactory = mock(InitialContextFactory.class);
context = mock(DirContext.class);
dnsResolver = new JndiDnsResolver();
dnsResolver.setCtxFactory(contextFactory);
when(contextFactory.getCtx()).thenReturn(context);
}
@Test
public void testResolveIpAddress() throws Exception {
Attributes records = new BasicAttributes("A","63.246.7.80");
when(context.getAttributes("www.springsource.com", new String[] {"A"})).thenReturn(records);
String ipAddress = dnsResolver.resolveIpAddress("www.springsource.com");
assertEquals("63.246.7.80", ipAddress);
}
@Test(expected=DnsEntryNotFoundException.class)
public void testResolveIpAddressNotExisting() throws Exception {
when(context.getAttributes(any(String.class), any(String[].class))).thenThrow(new NameNotFoundException("not found"));
dnsResolver.resolveIpAddress("notexisting.ansdansdugiuzgguzgioansdiandwq.foo");
}
@Test
public void testResolveServiceEntry() throws Exception {
BasicAttributes records = createSrvRecords();
when(context.getAttributes("_ldap._tcp.springsource.com", new String[] {"SRV"})).thenReturn(records);
String hostname = dnsResolver.resolveServiceEntry("ldap", "springsource.com");
assertEquals("kdc.springsource.com", hostname);
}
@Test(expected=DnsEntryNotFoundException.class)
public void testResolveServiceEntryNotExisting() throws Exception {
when(context.getAttributes(any(String.class), any(String[].class))).thenThrow(new NameNotFoundException("not found"));
dnsResolver.resolveServiceEntry("wrong", "secpod.de");
}
@Test
public void testResolveServiceIpAddress() throws Exception {
BasicAttributes srvRecords = createSrvRecords();
BasicAttributes aRecords = new BasicAttributes("A", "63.246.7.80");
when(context.getAttributes("_ldap._tcp.springsource.com", new String[] {"SRV"})).thenReturn(srvRecords);
when(context.getAttributes("kdc.springsource.com", new String[] {"A"})).thenReturn(aRecords);
String ipAddress = dnsResolver.resolveServiceIpAddress("ldap", "springsource.com");
assertEquals("63.246.7.80", ipAddress);
}
@Test(expected=DnsLookupException.class)
public void testUnknowError() throws Exception {
when(context.getAttributes(any(String.class), any(String[].class))).thenThrow(new NamingException("error"));
dnsResolver.resolveIpAddress("");
}
private BasicAttributes createSrvRecords() {
BasicAttributes records = new BasicAttributes();
BasicAttribute record = new BasicAttribute("SRV");
// the structure of the service records is:
// priority weight port hostname
// for more information: http://en.wikipedia.org/wiki/SRV_record
record.add("20 80 389 kdc3.springsource.com.");
record.add("10 70 389 kdc.springsource.com.");
record.add("20 20 389 kdc4.springsource.com.");
record.add("10 30 389 kdc2.springsource.com");
records.put(record);
return records;
}
}
@@ -1,109 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.httpinvoker;
import junit.framework.TestCase;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.remoting.httpinvoker.AuthenticationSimpleHttpInvokerRequestExecutor;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Tests {@link AuthenticationSimpleHttpInvokerRequestExecutor}.
*
* @author Ben Alex
*/
public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCase {
//~ Methods ========================================================================================================
protected void tearDown() throws Exception {
super.tearDown();
SecurityContextHolder.clearContext();
}
public void testNormalOperation() throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("Aladdin", "open sesame");
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
// Create a connection and ensure our executor sets its
// properties correctly
AuthenticationSimpleHttpInvokerRequestExecutor executor = new AuthenticationSimpleHttpInvokerRequestExecutor();
HttpURLConnection conn = new MockHttpURLConnection(new URL("http://localhost/"));
executor.prepareConnection(conn, 10);
// Check connection properties
// See http://www.faqs.org/rfcs/rfc1945.html section 11.1 for example
// we are comparing against
assertEquals("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", conn.getRequestProperty("Authorization"));
}
public void testNullContextHolderIsNull() throws Exception {
SecurityContextHolder.getContext().setAuthentication(null);
// Create a connection and ensure our executor sets its
// properties correctly
AuthenticationSimpleHttpInvokerRequestExecutor executor = new AuthenticationSimpleHttpInvokerRequestExecutor();
HttpURLConnection conn = new MockHttpURLConnection(new URL("http://localhost/"));
executor.prepareConnection(conn, 10);
// Check connection properties (shouldn't be an Authorization header)
assertNull(conn.getRequestProperty("Authorization"));
}
//~ Inner Classes ==================================================================================================
private class MockHttpURLConnection extends HttpURLConnection {
private Map<String,String> requestProperties = new HashMap<String,String>();
public MockHttpURLConnection(URL u) {
super(u);
}
public void connect() throws IOException {
throw new UnsupportedOperationException("mock not implemented");
}
public void disconnect() {
throw new UnsupportedOperationException("mock not implemented");
}
public String getRequestProperty(String key) {
return requestProperties.get(key);
}
public void setRequestProperty(String key, String value) {
requestProperties.put(key, value);
}
public boolean usingProxy() {
throw new UnsupportedOperationException("mock not implemented");
}
}
}
@@ -1,106 +0,0 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.remoting.rmi;
import junit.framework.TestCase;
import org.springframework.security.TargetObject;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.remoting.rmi.ContextPropagatingRemoteInvocation;
import org.springframework.security.remoting.rmi.ContextPropagatingRemoteInvocationFactory;
import org.springframework.security.util.SimpleMethodInvocation;
import org.aopalliance.intercept.MethodInvocation;
import java.lang.reflect.Method;
/**
* Tests {@link ContextPropagatingRemoteInvocation} and {@link ContextPropagatingRemoteInvocationFactory}.
*
* @author Ben Alex
*/
public class ContextPropagatingRemoteInvocationTests extends TestCase {
//~ Methods ========================================================================================================
protected void tearDown() throws Exception {
super.tearDown();
SecurityContextHolder.clearContext();
}
private ContextPropagatingRemoteInvocation getRemoteInvocation() throws Exception {
Class<TargetObject> clazz = TargetObject.class;
Method method = clazz.getMethod("makeLowerCase", new Class[] {String.class});
MethodInvocation mi = new SimpleMethodInvocation(new TargetObject(), method, "SOME_STRING");
ContextPropagatingRemoteInvocationFactory factory = new ContextPropagatingRemoteInvocationFactory();
return (ContextPropagatingRemoteInvocation) factory.createRemoteInvocation(mi);
}
public void testContextIsResetEvenIfExceptionOccurs()
throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", "koala");
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
try {
// Set up the wrong arguments.
remoteInvocation.setArguments(new Object[] {});
remoteInvocation.invoke(TargetObject.class.newInstance());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
assertNull("Authentication must be null ", SecurityContextHolder.getContext().getAuthentication());
}
public void testNormalOperation() throws Exception {
// Setup client-side context
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", "koala");
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
// Set to null, as ContextPropagatingRemoteInvocation already obtained
// a copy and nulling is necessary to ensure the Context delivered by
// ContextPropagatingRemoteInvocation is used on server-side
SecurityContextHolder.clearContext();
// The result from invoking the TargetObject should contain the
// Authentication class delivered via the SecurityContextHolder
assertEquals("some_string org.springframework.security.authentication.UsernamePasswordAuthenticationToken false",
remoteInvocation.invoke(new TargetObject()));
}
public void testNullContextHolderDoesNotCauseInvocationProblems() throws Exception {
SecurityContextHolder.getContext().setAuthentication(null); // just to be explicit
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
SecurityContextHolder.getContext().setAuthentication(null); // unnecessary, but for explicitness
assertEquals("some_string Authentication empty", remoteInvocation.invoke(new TargetObject()));
}
}