]> source.dussan.org Git - archiva.git/blob
37f4b93bd80555dc84920498b24f213fadedcd3a
[archiva.git] /
1 package org.apache.archiva.webdav;
2
3 /*
4  * Licensed to the Apache Software Foundation (ASF) under one
5  * or more contributor license agreements.  See the NOTICE file
6  * distributed with this work for additional information
7  * regarding copyright ownership.  The ASF licenses this file
8  * to you under the Apache License, Version 2.0 (the
9  * "License"); you may not use this file except in compliance
10  * with the License.  You may obtain a copy of the License at
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17  * KIND, either express or implied.  See the License for the
18  * specific language governing permissions and limitations
19  * under the License.
20  */
21
22
23 import com.gargoylesoftware.htmlunit.WebRequest;
24 import com.gargoylesoftware.htmlunit.WebResponse;
25 import junit.framework.TestCase;
26 import net.sf.ehcache.CacheManager;
27 import org.apache.archiva.configuration.ArchivaConfiguration;
28 import org.apache.archiva.configuration.Configuration;
29 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
30 import org.apache.archiva.redback.authentication.AuthenticationException;
31 import org.apache.archiva.redback.authentication.AuthenticationResult;
32 import org.apache.archiva.redback.authorization.UnauthorizedException;
33 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
34 import org.apache.archiva.redback.system.DefaultSecuritySession;
35 import org.apache.archiva.redback.system.SecuritySession;
36 import org.apache.archiva.redback.users.User;
37 import org.apache.archiva.redback.users.memory.SimpleUser;
38 import org.apache.archiva.repository.audit.TestAuditListener;
39 import org.apache.archiva.security.ServletAuthenticator;
40 import org.apache.archiva.security.common.ArchivaRoleConstants;
41 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
42 import org.apache.archiva.webdav.util.MavenIndexerCleaner;
43 import org.apache.catalina.Container;
44 import org.apache.catalina.core.StandardContext;
45 import org.apache.catalina.deploy.ApplicationParameter;
46 import org.apache.catalina.startup.Tomcat;
47 import org.apache.commons.io.FileUtils;
48 import org.apache.commons.io.IOUtils;
49 import org.apache.commons.lang.StringUtils;
50 import org.apache.jackrabbit.webdav.DavSessionProvider;
51 import org.easymock.EasyMock;
52 import org.easymock.IMocksControl;
53 import org.junit.After;
54 import org.junit.Before;
55 import org.junit.Ignore;
56 import org.junit.Test;
57 import org.junit.runner.RunWith;
58 import org.springframework.context.ApplicationContext;
59 import org.springframework.mock.web.MockHttpServletRequest;
60 import org.springframework.mock.web.MockHttpServletResponse;
61 import org.springframework.test.context.ContextConfiguration;
62 import org.springframework.web.context.ContextLoaderListener;
63
64 import javax.inject.Inject;
65 import javax.servlet.Servlet;
66 import javax.servlet.http.HttpServletRequest;
67 import javax.servlet.http.HttpServletResponse;
68 import javax.servlet.http.HttpSession;
69 import java.io.File;
70 import java.io.IOException;
71 import java.io.InputStream;
72 import java.nio.charset.Charset;
73
74 import static org.easymock.EasyMock.anyObject;
75 import static org.easymock.EasyMock.eq;
76
77 /**
78  * RepositoryServletSecurityTest Test the flow of the authentication and authorization checks. This does not necessarily
79  * perform redback security checking.
80  */
81 @RunWith( ArchivaSpringJUnit4ClassRunner.class )
82 @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" } )
83 public class RepositoryServletSecurityTest
84     extends TestCase
85 {
86     protected static final String REPOID_INTERNAL = "internal";
87
88
89     protected File repoRootInternal;
90
91     protected ArchivaConfiguration archivaConfiguration;
92
93     private DavSessionProvider davSessionProvider;
94
95     private IMocksControl servletAuthControl;
96
97     private ServletAuthenticator servletAuth;
98
99     private IMocksControl httpAuthControl;
100
101     private HttpAuthenticator httpAuth;
102
103     private RepositoryServlet servlet;
104
105     protected Tomcat tomcat;
106
107     protected static int port;
108
109     StandardContext context;
110
111     @Inject
112     ApplicationContext applicationContext;
113
114     @Before
115     public void setUp()
116         throws Exception
117     {
118         super.setUp();
119
120         String appserverBase =
121             System.getProperty( "appserver.base", new File( "target/appserver-base" ).getAbsolutePath() );
122
123         File testConf = new File( "src/test/resources/repository-archiva.xml" );
124         File testConfDest = new File( appserverBase, "conf/archiva.xml" );
125         FileUtils.copyFile( testConf, testConfDest );
126
127         repoRootInternal = new File( appserverBase, "data/repositories/internal" );
128
129         archivaConfiguration = applicationContext.getBean( ArchivaConfiguration.class );
130         Configuration config = archivaConfiguration.getConfiguration();
131
132         if ( !config.getManagedRepositoriesAsMap().containsKey( REPOID_INTERNAL ) )
133         {
134             config.addManagedRepository(
135                 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal ) );
136         }
137         saveConfiguration( archivaConfiguration );
138
139         CacheManager.getInstance().clearAll();
140
141         tomcat = new Tomcat();
142         tomcat.setBaseDir( System.getProperty( "java.io.tmpdir" ) );
143         tomcat.setPort( 0 );
144
145         context = StandardContext.class.cast( tomcat.addContext( "", System.getProperty( "java.io.tmpdir" ) ) );
146
147         ApplicationParameter applicationParameter = new ApplicationParameter();
148         applicationParameter.setName( "contextConfigLocation" );
149         applicationParameter.setValue( getSpringConfigLocation() );
150         context.addApplicationParameter( applicationParameter );
151
152         context.addApplicationListener( ContextLoaderListener.class.getName() );
153
154         context.addApplicationListener( MavenIndexerCleaner.class.getName() );
155
156         Tomcat.addServlet( context, "repository", new UnauthenticatedRepositoryServlet() );
157         context.addServletMapping( "/repository/*", "repository" );
158
159         tomcat.start();
160
161         this.port = tomcat.getConnector().getLocalPort();
162
163         servletAuthControl = EasyMock.createControl();
164
165         servletAuth = servletAuthControl.createMock( ServletAuthenticator.class );
166
167         httpAuthControl = EasyMock.createControl();
168
169         httpAuth = httpAuthControl.createMock( HttpAuthenticator.class );
170
171         davSessionProvider = new ArchivaDavSessionProvider( servletAuth, httpAuth );
172
173         // FIXME use mock to avoid starting Tomcat
174         //RepositoryServlet repositoryServlet = new RepositoryServlet();
175         //MockServletConfig mockServletConfig = new MockServletConfig();
176
177         //MockServletContext mockServletContext = new MockServletContext(  );
178         //mockServletContext
179
180         //repositoryServlet.init( mockServletConfig );
181
182         servlet = RepositoryServlet.class.cast( findServlet( "repository" ) );
183     }
184
185     protected String getSpringConfigLocation()
186     {
187         return "classpath*:/META-INF/spring-context.xml,classpath*:/spring-context-servlet-security-test.xml";
188     }
189
190     protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location )
191     {
192         ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
193         repo.setId( id );
194         repo.setName( name );
195         repo.setLocation( location.getAbsolutePath() );
196         return repo;
197     }
198
199     protected void saveConfiguration()
200         throws Exception
201     {
202         saveConfiguration( archivaConfiguration );
203     }
204
205     protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
206         throws Exception
207     {
208         archivaConfiguration.save( archivaConfiguration.getConfiguration() );
209     }
210
211     protected void setupCleanRepo( File repoRootDir )
212         throws IOException
213     {
214         FileUtils.deleteDirectory( repoRootDir );
215         if ( !repoRootDir.exists() )
216         {
217             repoRootDir.mkdirs();
218         }
219     }
220
221     @Override
222     @After
223     public void tearDown()
224         throws Exception
225     {
226
227         if ( repoRootInternal.exists() )
228         {
229             FileUtils.deleteDirectory( repoRootInternal );
230         }
231
232         servlet = null;
233
234         if ( this.tomcat != null )
235         {
236             this.tomcat.stop();
237         }
238
239         super.tearDown();
240     }
241
242     protected Servlet findServlet( String name )
243         throws Exception
244     {
245         Container[] childs = context.findChildren();
246         for ( Container container : childs )
247         {
248             if ( StringUtils.equals( container.getName(), name ) )
249             {
250                 Tomcat.ExistingStandardWrapper esw = Tomcat.ExistingStandardWrapper.class.cast( container );
251                 Servlet servlet = esw.loadServlet();
252
253                 return servlet;
254             }
255         }
256         return null;
257     }
258
259     // test deploy with invalid user, and guest has no write access to repo
260     // 401 must be returned
261     @Test
262     public void testPutWithInvalidUserAndGuestHasNoWriteAccess()
263         throws Exception
264     {
265         setupCleanRepo( repoRootInternal );
266
267         InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
268         assertNotNull( "artifact.jar inputstream", is );
269
270         servlet.setDavSessionProvider( davSessionProvider );
271
272         AuthenticationResult result = new AuthenticationResult();
273
274         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
275                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
276             result );
277
278         servletAuth.isAuthenticated( EasyMock.anyObject( HttpServletRequest.class ),
279                                      EasyMock.anyObject( AuthenticationResult.class ) );
280         EasyMock.expectLastCall().andThrow( new AuthenticationException( "Authentication error" ) );
281
282         servletAuth.isAuthorized( "guest", "internal", ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD );
283
284         EasyMock.expectLastCall().andThrow( new UnauthorizedException( "'guest' has no write access to repository" ) );
285
286         httpAuthControl.replay();
287         servletAuthControl.replay();
288         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
289         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
290         mockHttpServletRequest.setMethod( "PUT" );
291         mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
292         mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
293         mockHttpServletRequest.setContentType( "application/octet-stream" );
294
295         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
296
297         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
298
299         httpAuthControl.verify();
300         servletAuthControl.verify();
301
302         assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
303     }
304
305     // test deploy with invalid user, but guest has write access to repo
306     @Test
307     public void testPutWithInvalidUserAndGuestHasWriteAccess()
308         throws Exception
309     {
310         setupCleanRepo( repoRootInternal );
311
312         servlet.setDavSessionProvider( davSessionProvider );
313
314         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
315         archivaDavResourceFactory.setHttpAuth( httpAuth );
316         archivaDavResourceFactory.setServletAuth( servletAuth );
317
318         servlet.setResourceFactory( archivaDavResourceFactory );
319
320         AuthenticationResult result = new AuthenticationResult();
321
322         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
323                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
324             result );
325
326         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
327                                                       anyObject( AuthenticationResult.class ) ) ).andThrow(
328             new AuthenticationException( "Authentication error" ) );
329
330         EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
331                                                    ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ).andReturn(
332             true );
333
334         // ArchivaDavResourceFactory#isAuthorized()
335         SecuritySession session = new DefaultSecuritySession();
336
337         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
338                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
339             result );
340
341         EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );
342
343         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andThrow(
344             new AuthenticationException( "Authentication error" ) );
345
346         EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( null );
347
348         // check if guest has write access
349         EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
350                                                    ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ).andReturn(
351             true );
352
353         httpAuthControl.replay();
354         servletAuthControl.replay();
355
356         InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
357         assertNotNull( "artifact.jar inputstream", is );
358
359         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
360         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
361         mockHttpServletRequest.setMethod( "PUT" );
362         mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
363         mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
364         mockHttpServletRequest.setContentType( "application/octet-stream" );
365
366         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
367
368         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
369
370         httpAuthControl.verify();
371         servletAuthControl.verify();
372
373         assertEquals( HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus() );
374     }
375
376     // test deploy with a valid user with no write access
377     @Test
378     public void testPutWithValidUserWithNoWriteAccess()
379         throws Exception
380     {
381         setupCleanRepo( repoRootInternal );
382
383         servlet.setDavSessionProvider( davSessionProvider );
384
385         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
386         archivaDavResourceFactory.setHttpAuth( httpAuth );
387         archivaDavResourceFactory.setServletAuth( servletAuth );
388         servlet.setResourceFactory( archivaDavResourceFactory );
389
390         AuthenticationResult result = new AuthenticationResult();
391
392         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
393                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
394             result );
395
396         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
397                                                       anyObject( AuthenticationResult.class ) ) ).andReturn( true );
398
399         // ArchivaDavResourceFactory#isAuthorized()
400         SecuritySession session = new DefaultSecuritySession();
401
402         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
403                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
404             result );
405
406         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
407
408         EasyMock.expect( httpAuth.getSecuritySession( mockHttpServletRequest.getSession( true ) ) ).andReturn(
409             session );
410
411         EasyMock.expect( httpAuth.getSessionUser( mockHttpServletRequest.getSession() ) ).andReturn( new SimpleUser() );
412
413         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
414             true );
415
416         EasyMock.expect(
417             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
418                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ) ).andThrow(
419             new UnauthorizedException( "User not authorized" ) );
420         httpAuthControl.replay();
421         servletAuthControl.replay();
422
423         InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
424         assertNotNull( "artifact.jar inputstream", is );
425
426         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
427         mockHttpServletRequest.setMethod( "PUT" );
428         mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
429         mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
430         mockHttpServletRequest.setContentType( "application/octet-stream" );
431
432         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
433
434         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
435
436         httpAuthControl.verify();
437         servletAuthControl.verify();
438
439         assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
440     }
441
442     // test deploy with a valid user with write access
443     @Test
444     public void testPutWithValidUserWithWriteAccess()
445         throws Exception
446     {
447         setupCleanRepo( repoRootInternal );
448         assertTrue( repoRootInternal.exists() );
449
450         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
451         String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
452         InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
453         assertNotNull( "artifact.jar inputstream", is );
454
455         servlet.setDavSessionProvider( davSessionProvider );
456
457         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
458         archivaDavResourceFactory.setHttpAuth( httpAuth );
459         archivaDavResourceFactory.setServletAuth( servletAuth );
460
461         TestAuditListener listener = new TestAuditListener();
462         archivaDavResourceFactory.addAuditListener( listener );
463         servlet.setResourceFactory( archivaDavResourceFactory );
464
465         AuthenticationResult result = new AuthenticationResult();
466
467         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
468                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
469             result );
470
471         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
472                                                       anyObject( AuthenticationResult.class ) ) ).andReturn( true );
473
474         User user = new SimpleUser();
475         user.setUsername( "admin" );
476
477         // ArchivaDavResourceFactory#isAuthorized()
478         SecuritySession session = new DefaultSecuritySession();
479
480         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
481                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
482             result );
483
484         EasyMock.expect( httpAuth.getSecuritySession( mockHttpServletRequest.getSession() ) ).andReturn( session );
485
486         EasyMock.expect( httpAuth.getSessionUser( mockHttpServletRequest.getSession() ) ).andReturn( user );
487
488         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
489             true );
490
491         EasyMock.expect(
492             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
493                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ) ).andReturn( true );
494
495         httpAuthControl.replay();
496         servletAuthControl.replay();
497
498         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
499         mockHttpServletRequest.setMethod( "PUT" );
500         mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
501         mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
502         mockHttpServletRequest.setContentType( "application/octet-stream" );
503
504         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
505
506         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
507
508         httpAuthControl.verify();
509         servletAuthControl.verify();
510
511         assertEquals( HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus() );
512
513         assertEquals( "admin", listener.getEvents().get( 0 ).getUserId() );
514     }
515
516     // test get with invalid user, and guest has read access to repo
517     @Test
518     public void testGetWithInvalidUserAndGuestHasReadAccess()
519         throws Exception
520     {
521         String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
522         String expectedArtifactContents = "dummy-commons-lang-artifact";
523
524         File artifactFile = new File( repoRootInternal, commonsLangJar );
525         artifactFile.getParentFile().mkdirs();
526
527         FileUtils.writeStringToFile( artifactFile, expectedArtifactContents, Charset.defaultCharset() );
528
529         servlet.setDavSessionProvider( davSessionProvider );
530
531         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
532         archivaDavResourceFactory.setHttpAuth( httpAuth );
533         archivaDavResourceFactory.setServletAuth( servletAuth );
534
535         servlet.setResourceFactory( archivaDavResourceFactory );
536
537         AuthenticationResult result = new AuthenticationResult();
538
539         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
540                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
541             result );
542
543         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
544                                                       anyObject( AuthenticationResult.class ) ) ).andThrow(
545             new AuthenticationException( "Authentication error" ) );
546
547         EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
548                                                    ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ).andReturn(
549             true );
550
551         // ArchivaDavResourceFactory#isAuthorized()
552         SecuritySession session = new DefaultSecuritySession();
553
554         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
555                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
556             result );
557
558         EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );
559
560         EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( null );
561
562         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
563             true );
564
565         EasyMock.expect(
566             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
567                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ) ).andReturn( true );
568         httpAuthControl.replay();
569         servletAuthControl.replay();
570
571         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
572         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
573         mockHttpServletRequest.setMethod( "GET" );
574         mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
575
576
577         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
578
579         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
580
581         httpAuthControl.verify();
582         servletAuthControl.verify();
583
584         assertEquals( HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus() );
585
586         assertEquals( "Expected file contents", expectedArtifactContents, mockHttpServletResponse.getContentAsString() );
587     }
588
589     // test get with invalid user, and guest has no read access to repo
590     @Test
591     public void testGetWithInvalidUserAndGuestHasNoReadAccess()
592         throws Exception
593     {
594         String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
595         String expectedArtifactContents = "dummy-commons-lang-artifact";
596
597         File artifactFile = new File( repoRootInternal, commonsLangJar );
598         artifactFile.getParentFile().mkdirs();
599
600         FileUtils.writeStringToFile( artifactFile, expectedArtifactContents, Charset.defaultCharset() );
601
602         servlet.setDavSessionProvider( davSessionProvider );
603
604         AuthenticationResult result = new AuthenticationResult();
605
606         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
607                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
608             result );
609
610         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
611                                                       anyObject( AuthenticationResult.class ) ) ).andThrow(
612             new AuthenticationException( "Authentication error" ) );
613
614         EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
615                                                    ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ).andReturn(
616             false );
617         httpAuthControl.replay();
618         servletAuthControl.replay();
619
620         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
621         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
622         mockHttpServletRequest.setMethod( "GET" );
623         mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
624
625
626         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
627
628         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
629
630         httpAuthControl.verify();
631         servletAuthControl.verify();
632
633         assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
634     }
635
636     // test get with valid user with read access to repo
637     @Test
638     public void testGetWithAValidUserWithReadAccess()
639         throws Exception
640     {
641         String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
642         String expectedArtifactContents = "dummy-commons-lang-artifact";
643
644         File artifactFile = new File( repoRootInternal, commonsLangJar );
645         artifactFile.getParentFile().mkdirs();
646
647         FileUtils.writeStringToFile( artifactFile, expectedArtifactContents, Charset.defaultCharset() );
648
649         servlet.setDavSessionProvider( davSessionProvider );
650
651         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
652         archivaDavResourceFactory.setHttpAuth( httpAuth );
653         archivaDavResourceFactory.setServletAuth( servletAuth );
654
655         servlet.setResourceFactory( archivaDavResourceFactory );
656
657         AuthenticationResult result = new AuthenticationResult();
658
659         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
660                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
661             result );
662
663         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
664                                                       anyObject( AuthenticationResult.class ) ) ).andReturn( true );
665         // ArchivaDavResourceFactory#isAuthorized()
666         SecuritySession session = new DefaultSecuritySession();
667
668         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
669                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
670             result );
671
672         EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );
673
674         EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( new SimpleUser() );
675
676         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
677             true );
678
679         EasyMock.expect(
680             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
681                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ) ).andReturn( true );
682
683         httpAuthControl.replay();
684         servletAuthControl.replay();
685
686         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
687         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
688         mockHttpServletRequest.setMethod( "GET" );
689         mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
690
691
692         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
693
694         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
695
696         httpAuthControl.verify();
697         servletAuthControl.verify();
698
699         assertEquals( HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus() );
700         assertEquals( "Expected file contents", expectedArtifactContents, mockHttpServletResponse.getContentAsString() );
701     }
702
703     // test get with valid user with no read access to repo
704     @Test
705     public void testGetWithAValidUserWithNoReadAccess()
706         throws Exception
707     {
708         String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
709         String expectedArtifactContents = "dummy-commons-lang-artifact";
710
711         File artifactFile = new File( repoRootInternal, commonsLangJar );
712         artifactFile.getParentFile().mkdirs();
713
714         FileUtils.writeStringToFile( artifactFile, expectedArtifactContents, Charset.defaultCharset() );
715
716         servlet.setDavSessionProvider( davSessionProvider );
717
718         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
719         archivaDavResourceFactory.setHttpAuth( httpAuth );
720         archivaDavResourceFactory.setServletAuth( servletAuth );
721
722         servlet.setResourceFactory( archivaDavResourceFactory );
723
724         AuthenticationResult result = new AuthenticationResult();
725
726         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
727                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
728             result );
729
730         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
731                                                       anyObject( AuthenticationResult.class ) ) ).andReturn( true );
732
733         // ArchivaDavResourceFactory#isAuthorized()
734         SecuritySession session = new DefaultSecuritySession();
735
736         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
737                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
738             result );
739
740         EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );
741
742         EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( new SimpleUser() );
743
744         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
745             true );
746
747         EasyMock.expect(
748             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
749                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ) ).andThrow(
750             new UnauthorizedException( "User not authorized to read repository." ) );
751         httpAuthControl.replay();
752         servletAuthControl.replay();
753
754         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
755         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
756         mockHttpServletRequest.setMethod( "GET" );
757         mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
758
759
760         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
761
762         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
763
764         httpAuthControl.verify();
765         servletAuthControl.verify();
766
767         assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
768     }
769 }