Debian Codegraph @

src/test/java/org/astrogrid/samp/web/WebClientTest.java

raw
1 package org.astrogrid.samp.web;
2
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.net.ServerSocket;
9 import java.net.URL;
10 import java.util.ArrayList;
11 import java.util.Collections;
12 import java.util.HashMap;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Random;
16 import java.util.logging.Level;
17 import java.util.logging.Logger;
18 import junit.framework.TestCase;
19 import org.astrogrid.samp.Message;
20 import org.astrogrid.samp.RegInfo;
21 import org.astrogrid.samp.Response;
22 import org.astrogrid.samp.SampUtils;
23 import org.astrogrid.samp.Subscriptions;
24 import org.astrogrid.samp.TestProfile;
25 import org.astrogrid.samp.client.CallableClient;
26 import org.astrogrid.samp.client.HubConnection;
27 import org.astrogrid.samp.client.SampException;
28 import org.astrogrid.samp.httpd.HttpServer;
29 import org.astrogrid.samp.hub.MessageRestriction;
30 import org.astrogrid.samp.xmlrpc.XmlRpcHubConnection;
31 import org.astrogrid.samp.xmlrpc.internal.InternalServer;
32
33 public class WebClientTest extends TestCase {
34
35 public void setUp() {
36 Logger.getLogger( "org.astrogrid.samp" ).setLevel( Level.WARNING );
37 Logger.getLogger( InternalServer.class.getName() )
38 .setLevel( Level.SEVERE );
39 Logger.getLogger( WebHubConnection.class.getName() )
40 .setLevel( Level.SEVERE );
41 Logger.getLogger( UrlTracker.class.getName() )
42 .setLevel( Level.SEVERE );
43 Logger.getLogger( HttpServer.class.getName() )
44 .setLevel( Level.SEVERE );
45 }
46
47 // Test withdrawn, multiple cycles of allowReverseCallbacks are not
48 // recommended. Code may come in useful for something else another
49 // day though.
50 public void doNottestCallbacks() throws IOException, InterruptedException {
51 WebTestProfile profile =
52 new WebTestProfile( new Random( 23L ), true, null );
53 profile.startHub();
54 XmlRpcHubConnection tconn = (XmlRpcHubConnection) profile.register();
55 XmlRpcHubConnection rconn = (XmlRpcHubConnection) profile.register();
56 String tid = tconn.getRegInfo().getSelfId();
57 String rid = rconn.getRegInfo().getSelfId();
58 Subscriptions subs = new Subscriptions();
59 String pMtype = "test.ping";
60 subs.addMType( pMtype );
61 Message pmsg = new Message( pMtype );
62 Receiver rcvr = new Receiver();
63 rconn.setCallable( rcvr );
64 rconn.declareSubscriptions( subs );
65
66 tconn.notify( rid, pmsg );
67 assertTrue( rcvr.waitForMessage( 1000 ) != null );
68 rconn.exec( "allowReverseCallbacks", new String[] { "0" } );
69 tconn.notify( rid, pmsg );
70 assertTrue( rcvr.waitForMessage( 1000 ) == null );
71 rconn.exec( "allowReverseCallbacks", new String[] { "1" } );
72 assertTrue( rcvr.waitForMessage( 1000 ) != null );
73 assertTrue( rcvr.waitForMessage( 1000 ) == null );
74 tconn.unregister();
75 rconn.unregister();
76 }
77
78 public void testRegistration() throws IOException {
79 WebTestProfile profile =
80 new WebTestProfile( new Random( 23L ), true, null );
81 profile.startHub();
82 assertTrue( profile.isHubRunning() );
83 HubConnection conn = profile.register();
84 assertEquals( "samp.url-translator", WebClientProfile.URLTRANS_KEY );
85 RegInfo regInfo = conn.getRegInfo();
86 assertTrue( ((String) regInfo.get( "samp.private-key" )).length() > 0 );
87 profile.setClientAuthorizer( ClientAuthorizers
88 .createFixedClientAuthorizer( false ) );
89 try {
90 profile.register();
91 fail();
92 }
93 catch ( SampException e ) {
94 assertTrue( e.getMessage().indexOf( "denied" ) > 0 );
95 }
96 profile.stopHub();
97 }
98
99 public void testControlledUrlTranslator()
100 throws IOException, InterruptedException {
101 WebTestProfile profile =
102 new WebTestProfile( new Random( 23L ), true, null );
103 profile.startHub();
104 Subscriptions subs = new Subscriptions();
105 String mtype = "test.url";
106 subs.addMType( mtype );
107 String ftxt = "some\ntext\nin\na\nfile\n";
108
109 HubConnection webConn = profile.register();
110 Receiver webReceiver = new Receiver();
111 webConn.setCallable( webReceiver );
112 webConn.declareSubscriptions( subs );
113 RegInfo webReg = webConn.getRegInfo();
114 String turl = (String) webReg.get( WebClientProfile.URLTRANS_KEY );
115
116 HubConnection dirConn = profile.registerDirect();
117 Receiver dirReceiver = new Receiver();
118 dirConn.setCallable( dirReceiver );
119 dirConn.declareSubscriptions( subs );
120 RegInfo dirReg = dirConn.getRegInfo();
121
122 File file1 = File.createTempFile( "txtfile", ".tmp" );
123 file1.deleteOnExit();
124 OutputStream fout1 = new FileOutputStream( file1 );
125 fout1.write( ftxt.getBytes( "utf-8" ) );
126 fout1.close();
127 URL furl1 = SampUtils.fileToUrl( file1 );
128 URL tfurl1 = new URL( turl + furl1.toString() );
129 Message url1Msg = new Message( mtype )
130 .addParam( "url", furl1.toString() );
131
132 // First try - blocked because it's a local URL, and no incoming
133 // reference has been seen (UrlTracker).
134 try {
135 readUrl( tfurl1 );
136 fail( "Should have blocked access to " + tfurl1 );
137 }
138 catch ( IOException e ) {
139 }
140
141 // Second try: send message out mentioning it. This will still
142 // fail, because we're not trusted, and it will permanently block
143 // access (if we're the first one to mention it, it's probalbly
144 // not legitimante and it might provoke an echo somewhere).
145 webConn.notify( dirReg.getSelfId(), url1Msg );
146 dirReceiver.waitForMessage( 1000 );
147 try {
148 readUrl( tfurl1 );
149 fail( "Should have blocked access to " + tfurl1 );
150 }
151 catch ( IOException e ) {
152 }
153
154 // Third try: get some trusted client to mention the URL,
155 // but since it's been permanently blocked, we still can't access it.
156 dirConn.notify( webReg.getSelfId(), url1Msg );
157 webReceiver.waitForMessage( 1000 );
158 try {
159 readUrl( tfurl1 );
160 fail( "Should have blocked access to " + tfurl1 );
161 }
162 catch ( IOException e ) {
163 }
164
165 // Now try with a different file.
166 File file2 = File.createTempFile( "txtfile", ".tmp" );
167 file2.deleteOnExit();
168 OutputStream fout2 = new FileOutputStream( file2 );
169 fout2.write( ftxt.getBytes( "utf-8" ) );
170 fout2.close();
171 URL furl2 = SampUtils.fileToUrl( file2 );
172 URL tfurl2 = new URL( turl + furl2.toString() );
173 Message url2msg = new Message( mtype )
174 .addParam( "url", furl2.toString() );
175
176 // Get a trusted client to mention it.
177 dirConn.notify( webReg.getSelfId(), url2msg );
178 webReceiver.waitForMessage( 1000 );
179
180 // Read it. Should be OK.
181 assertEquals( ftxt, readUrl( tfurl2 ) );
182
183 // Tidy up.
184 file1.delete();
185 file2.delete();
186 profile.stopHub();
187 }
188
189 public void testUncontrolledUrlTranslator() throws IOException {
190 WebTestProfile profile =
191 new WebTestProfile( new Random( 29L ), false, null );
192 profile.startHub();
193 HubConnection webConn = profile.register();
194 RegInfo webReg = webConn.getRegInfo();
195 String turl = (String) webReg.get( WebClientProfile.URLTRANS_KEY );
196 File file = File.createTempFile( "txtfile", ".tmp" );
197 file.deleteOnExit();
198 OutputStream fout = new FileOutputStream( file );
199 String ftxt = "some\ntext\nin\na\nfile\n";
200 fout.write( ftxt.getBytes( "utf-8" ) );
201 fout.close();
202 URL furl = SampUtils.fileToUrl( file );
203 URL tfurl = new URL( turl + furl.toString() );
204 assertEquals( ftxt, readUrl( tfurl ) );
205 file.delete();
206 profile.stopHub();
207 }
208
209 public void testRestrictMTypes() throws IOException, InterruptedException {
210 assertTrue( passMessage( ListMessageRestriction.ALLOW_ALL,
211 "test.hello" ) );
212 assertTrue( ! passMessage( ListMessageRestriction.DENY_ALL,
213 "test.hello" ) );
214 assertTrue( passMessage( singleMessageRestriction( true, "test.hello" ),
215 "test.hello" ) );
216 assertTrue( ! passMessage( singleMessageRestriction( true,
217 "test.goodbye" ),
218 "test.hello" ) );
219 assertTrue( passMessage( singleMessageRestriction( false,
220 "test.goodbye" ),
221 "test.hello" ) );
222 assertTrue( ! passMessage( singleMessageRestriction( false,
223 "test.goodbye" ),
224 "test.goodbye" ) );
225 assertTrue( passMessage( singleMessageRestriction( true, "test.*" ),
226 "test.hello" ) );
227 assertTrue( ! passMessage( singleMessageRestriction( true, "test.*" ),
228 "hello" ) );
229 }
230
231 private MessageRestriction singleMessageRestriction( final boolean allow,
232 String mtype ) {
233 return new ListMessageRestriction( allow, new String[] { mtype },
234 true );
235 }
236
237 private boolean passMessage( MessageRestriction mrestrict, String mtype )
238 throws IOException, InterruptedException {
239 Message msg0 = new Message( mtype );
240 WebTestProfile profile =
241 new WebTestProfile( new Random( 1019L ), false, mrestrict );
242 profile.startHub();
243 HubConnection tconn = profile.register();
244 HubConnection rconn = profile.register();
245 String tid = tconn.getRegInfo().getSelfId();
246 String rid = rconn.getRegInfo().getSelfId();
247 Subscriptions subs = new Subscriptions();
248 subs.addMType( mtype );
249 Receiver rcvr = new Receiver();
250 rconn.setCallable( rcvr );
251 rconn.declareSubscriptions( subs );
252 boolean sent;
253 try {
254 tconn.notify( rid, msg0 );
255 sent = true;
256 }
257 catch ( SampException e ) {
258 sent = false;
259 }
260 if ( sent ) {
261 Message msg1 = rcvr.waitForMessage( 1000 );
262 assertEquals( msg0, msg1 );
263 }
264 tconn.unregister();
265 rconn.unregister();
266 return sent;
267 }
268
269 public void testServer() throws IOException {
270 ServerSocket sock = new ServerSocket( 0 );
271 String path = "/";
272 WebHubProfile.ServerFactory sxfact =
273 new WebHubProfile.ServerFactory();
274 sxfact.setLogType( null );
275 sxfact.setPort( 0 );
276 sxfact.setXmlrpcPath( "/" );
277 sxfact.setOriginAuthorizer( OriginAuthorizers.TRUE );
278 sxfact.setAllowFlash( true );
279 sxfact.setAllowSilverlight( true );
280 InternalServer xServer = sxfact.createSampXmlRpcServer();
281 HttpServer hServer = xServer.getHttpServer();
282 URL surl =
283 new URL( "http://localhost:" + hServer.getSocket().getLocalPort() );
284 hServer.start();
285 String xdomain = readUrl( new URL( surl, "/crossdomain.xml" ) );
286 assertTrue( xdomain.indexOf( "<cross-domain-policy>" ) > 0 );
287 String accpol = readUrl( new URL( surl, "/clientaccesspolicy.xml" ) );
288 assertTrue( accpol.indexOf( "<access-policy>" ) > 0 );
289 hServer.stop();
290 }
291
292 public void testMessageRestriction() {
293 MessageRestriction allMr = ListMessageRestriction.ALLOW_ALL;
294 MessageRestriction noneMr = ListMessageRestriction.DENY_ALL;
295 MessageRestriction dfltMr = ListMessageRestriction.DEFAULT;
296 MessageRestriction testMr =
297 new ListMessageRestriction( true, new String[] { "test.*" }, true );
298 MessageRestriction notestMr =
299 new ListMessageRestriction( false, new String[] { "test.*" },
300 true );
301 assertTrue( allMr.permitSend( "system.exec", new HashMap() ) );
302 assertTrue( ! noneMr.permitSend( "system.exec", new HashMap() ) );
303 assertTrue( ! dfltMr.permitSend( "system.exec", new HashMap() ) );
304 assertTrue( ! testMr.permitSend( "system.exec", new HashMap() ) );
305 assertTrue( notestMr.permitSend( "system.exec", new HashMap() ) );
306 assertTrue( dfltMr.permitSend( "table.load.votable", new HashMap() ) );
307 assertTrue( new ListMessageRestriction( true,
308 new String[] { "do.what" },
309 true )
310 .permitSend( "do.what", new HashMap() ) );
311 }
312
313 private static String readUrl( URL url ) throws IOException {
314 StringBuffer ubuf = new StringBuffer();
315 InputStream in = url.openStream();
316 for ( int b; ( b = in.read() ) >= 0; ) {
317 ubuf.append( (char) b );
318 }
319 in.close();
320 return ubuf.toString();
321 }
322
323 private static class Receiver implements CallableClient {
324 private final List msgList_ = new ArrayList();
325 private final List responseList_ = new ArrayList();
326 public synchronized void receiveCall( String senderId, String msgId,
327 Message msg ) {
328 msgList_.add( msg );
329 notifyAll();
330 }
331 public synchronized void receiveNotification( String senderId,
332 Message msg ) {
333 msgList_.add( msg );
334 notifyAll();
335 }
336 public synchronized void receiveResponse( String responsderId,
337 String msgTag,
338 Response response ) {
339 msgList_.add( response );
340 notifyAll();
341 }
342 public synchronized Message waitForMessage( long millis )
343 throws InterruptedException {
344 long end = System.currentTimeMillis() + millis;
345 while ( System.currentTimeMillis() < end && msgList_.isEmpty() ) {
346 wait( end - System.currentTimeMillis() );
347 }
348 return msgList_.isEmpty() ? null
349 : (Message) msgList_.get( 0 );
350 }
351 public synchronized Response waitForResponse( long millis )
352 throws InterruptedException {
353 long end = System.currentTimeMillis() + millis;
354 while ( System.currentTimeMillis() < end &&
355 responseList_.isEmpty() ) {
356 wait( end - System.currentTimeMillis() );
357 }
358 return responseList_.isEmpty() ? null
359 : (Response) responseList_.get( 0 );
360 }
361 }
362 }