]> source.dussan.org Git - archiva.git/blob
0385c25e7e52d3eed74a9e3a79b7aca4c80aca6e
[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 junit.framework.TestCase;
24 import net.sf.ehcache.CacheManager;
25 import org.apache.archiva.configuration.ArchivaConfiguration;
26 import org.apache.archiva.configuration.Configuration;
27 import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
28 import org.apache.archiva.redback.authentication.AuthenticationException;
29 import org.apache.archiva.redback.authentication.AuthenticationResult;
30 import org.apache.archiva.redback.authorization.UnauthorizedException;
31 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
32 import org.apache.archiva.redback.system.DefaultSecuritySession;
33 import org.apache.archiva.redback.system.SecuritySession;
34 import org.apache.archiva.redback.users.User;
35 import org.apache.archiva.redback.users.memory.SimpleUser;
36 import org.apache.archiva.repository.RepositoryRegistry;
37 import org.apache.archiva.metadata.audit.TestAuditListener;
38 import org.apache.archiva.security.ServletAuthenticator;
39 import org.apache.archiva.security.common.ArchivaRoleConstants;
40 import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
41 import org.apache.commons.io.FileUtils;
42 import org.apache.commons.io.IOUtils;
43 import org.apache.commons.lang3.StringUtils;
44 import org.apache.jackrabbit.webdav.DavSessionProvider;
45 import org.easymock.EasyMock;
46 import org.easymock.IMocksControl;
47 import org.junit.After;
48 import org.junit.Before;
49 import org.junit.Rule;
50 import org.junit.Test;
51 import org.junit.runner.RunWith;
52 import org.springframework.context.ApplicationContext;
53 import org.springframework.mock.web.MockHttpServletRequest;
54 import org.springframework.mock.web.MockHttpServletResponse;
55 import org.springframework.mock.web.MockServletConfig;
56 import org.springframework.mock.web.MockServletContext;
57 import org.springframework.test.context.ContextConfiguration;
58 import org.springframework.web.context.WebApplicationContext;
59
60 import javax.inject.Inject;
61 import javax.servlet.ServletContext;
62 import javax.servlet.http.HttpServletRequest;
63 import javax.servlet.http.HttpServletResponse;
64 import javax.servlet.http.HttpSession;
65 import java.io.InputStream;
66 import java.nio.charset.Charset;
67 import java.nio.file.Files;
68 import java.nio.file.Path;
69 import java.nio.file.Paths;
70 import java.util.ArrayList;
71 import java.util.List;
72 import java.util.concurrent.atomic.AtomicReference;
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-servlet-security-test.xml" } )
83 public class RepositoryServletSecurityTest
84     extends TestCase
85 {
86     protected static final String REPOID_INTERNAL = "internal";
87
88     @Inject
89     protected ArchivaConfiguration archivaConfiguration;
90
91     @Inject
92     protected RepositoryRegistry repositoryRegistry;
93
94     private DavSessionProvider davSessionProvider;
95
96     private IMocksControl servletAuthControl;
97
98     private ServletAuthenticator servletAuth;
99
100     private IMocksControl httpAuthControl;
101
102     private HttpAuthenticator httpAuth;
103
104     private RepositoryServlet servlet;
105
106     @Inject
107     ApplicationContext applicationContext;
108    
109
110     @Rule
111     public ArchivaTemporaryFolderRule repoRootInternal = new ArchivaTemporaryFolderRule();
112
113     private AtomicReference<Path> projectBase = new AtomicReference<>( );
114
115     public Path getProjectBase() {
116         if (this.projectBase.get()==null) {
117             String pathVal = System.getProperty("mvn.project.base.dir");
118             Path baseDir;
119             if ( StringUtils.isEmpty(pathVal)) {
120                 baseDir= Paths.get("").toAbsolutePath();
121             } else {
122                 baseDir = Paths.get(pathVal).toAbsolutePath();
123             }
124             this.projectBase.compareAndSet(null, baseDir);
125         }
126         return this.projectBase.get();
127     }
128
129     @Before
130     @Override
131     public void setUp()
132         throws Exception
133     {
134         
135         super.setUp();
136
137         String appserverBase =
138             System.getProperty( "appserver.base", getProjectBase().resolve( "target/appserver-base" ).toAbsolutePath().toString() );
139
140         Path testConf = getProjectBase().resolve( "src/test/resources/repository-archiva.xml" );
141         Path testConfDest = Paths.get(appserverBase, "conf/archiva.xml" );
142         FileUtils.copyFile( testConf.toFile(), testConfDest.toFile() );
143         
144         
145  
146         Configuration config = archivaConfiguration.getConfiguration();
147         // clear managed repository
148         List<ManagedRepositoryConfiguration> f1 = new ArrayList<>(config.getManagedRepositories());
149         for (ManagedRepositoryConfiguration f: f1 ) {
150             config.removeManagedRepository(f);
151         }
152         assertEquals(0,config.getManagedRepositories().size());
153         // add internal repo
154         config.addManagedRepository(
155                 createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal.getRoot() ) );
156         
157         saveConfiguration( archivaConfiguration );
158
159         CacheManager.getInstance().clearAll();
160
161
162         servletAuthControl = EasyMock.createControl();
163
164         servletAuth = servletAuthControl.createMock( ServletAuthenticator.class );
165
166         httpAuthControl = EasyMock.createControl();
167
168         httpAuth = httpAuthControl.createMock( HttpAuthenticator.class );
169
170         davSessionProvider = new ArchivaDavSessionProvider( servletAuth, httpAuth );
171
172         final MockServletContext mockServletContext = new MockServletContext();
173
174         WebApplicationContext webApplicationContext =
175             new AbstractRepositoryServletTestCase.TestWebapplicationContext( applicationContext, mockServletContext );
176
177         mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
178                                          webApplicationContext );
179
180         MockServletConfig mockServletConfig = new MockServletConfig()
181         {
182             @Override
183             public ServletContext getServletContext()
184             {
185                 return mockServletContext;
186             }
187         };
188
189         servlet = new RepositoryServlet();
190
191         servlet.init( mockServletConfig );
192     }
193
194     protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location )
195     {
196         ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
197         repo.setId( id );
198         repo.setName( name );
199         repo.setLocation( location.toAbsolutePath().toString() );
200         return repo;
201     }
202
203     /*protected void saveConfiguration()
204         throws Exception
205     {
206         saveConfiguration( archivaConfiguration );
207     }*/
208
209     protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
210         throws Exception
211     {
212         repositoryRegistry.reload();
213         archivaConfiguration.save( archivaConfiguration.getConfiguration() );        
214     }
215
216     /*protected void setupCleanRepo( File repoRootDir )
217         throws IOException
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         super.tearDown();
233         String appBaseProp = System.getProperty( "appserver.base" );
234         if (StringUtils.isNotEmpty( appBaseProp )) {
235             org.apache.archiva.common.utils.FileUtils.deleteDirectory( Paths.get(appBaseProp) );
236         }
237     }
238
239
240
241     // test deploy with invalid user, and guest has no write access to repo
242     // 401 must be returned
243     @Test
244     public void testPutWithInvalidUserAndGuestHasNoWriteAccess()
245         throws Exception
246     {
247         
248         InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
249         assertNotNull( "artifact.jar inputstream", is );
250
251         servlet.setDavSessionProvider( davSessionProvider );
252
253         AuthenticationResult result = new AuthenticationResult();
254
255         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
256                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
257             result );
258
259         servletAuth.isAuthenticated( EasyMock.anyObject( HttpServletRequest.class ),
260                                      EasyMock.anyObject( AuthenticationResult.class ) );
261         EasyMock.expectLastCall().andThrow( new AuthenticationException( "Authentication error" ) );
262
263         servletAuth.isAuthorized( "guest", "internal", ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD );
264
265         EasyMock.expectLastCall().andThrow( new UnauthorizedException( "'guest' has no write access to repository" ) );
266
267         httpAuthControl.replay();
268         servletAuthControl.replay();
269         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
270         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
271         mockHttpServletRequest.setMethod( "PUT" );
272         mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
273         mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
274         mockHttpServletRequest.setContentType( "application/octet-stream" );
275
276         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
277
278         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
279
280         httpAuthControl.verify();
281         servletAuthControl.verify();
282
283         assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
284     }
285
286     // test deploy with invalid user, but guest has write access to repo
287     @Test
288     public void testPutWithInvalidUserAndGuestHasWriteAccess()
289         throws Exception
290     {
291         
292         servlet.setDavSessionProvider( davSessionProvider );
293
294         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
295         archivaDavResourceFactory.setHttpAuth( httpAuth );
296         archivaDavResourceFactory.setServletAuth( servletAuth );
297
298         servlet.setResourceFactory( archivaDavResourceFactory );
299
300         AuthenticationResult result = new AuthenticationResult();
301
302         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
303                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
304             result );
305
306         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
307                                                       anyObject( AuthenticationResult.class ) ) ).andThrow(
308             new AuthenticationException( "Authentication error" ) );
309
310         EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
311                                                    ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ).andReturn(
312             true );
313
314         // ArchivaDavResourceFactory#isAuthorized()
315         SecuritySession session = new DefaultSecuritySession();
316
317         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
318                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
319             result );
320
321         EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );
322
323         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andThrow(
324             new AuthenticationException( "Authentication error" ) );
325
326         EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( null );
327
328         // check if guest has write access
329         EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
330                                                    ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ).andReturn(
331             true );
332
333         httpAuthControl.replay();
334         servletAuthControl.replay();
335
336         InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
337         assertNotNull( "artifact.jar inputstream", is );
338
339         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
340         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
341         mockHttpServletRequest.setMethod( "PUT" );
342         mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
343         mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
344         mockHttpServletRequest.setContentType( "application/octet-stream" );
345
346         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
347
348         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
349
350         httpAuthControl.verify();
351         servletAuthControl.verify();
352
353         assertEquals( HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus() );
354     }
355
356     // test deploy with a valid user with no write access
357     @Test
358     public void testPutWithValidUserWithNoWriteAccess()
359         throws Exception
360     {
361         
362         servlet.setDavSessionProvider( davSessionProvider );
363
364         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
365         archivaDavResourceFactory.setHttpAuth( httpAuth );
366         archivaDavResourceFactory.setServletAuth( servletAuth );
367         servlet.setResourceFactory( archivaDavResourceFactory );
368
369         AuthenticationResult result = new AuthenticationResult();
370
371         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
372                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
373             result );
374
375         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
376                                                       anyObject( AuthenticationResult.class ) ) ).andReturn( true );
377
378         // ArchivaDavResourceFactory#isAuthorized()
379         SecuritySession session = new DefaultSecuritySession();
380
381         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
382                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
383             result );
384
385         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
386
387         EasyMock.expect( httpAuth.getSecuritySession( mockHttpServletRequest.getSession( true ) ) ).andReturn(
388             session );
389
390         EasyMock.expect( httpAuth.getSessionUser( mockHttpServletRequest.getSession() ) ).andReturn( new SimpleUser() );
391
392         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
393             true );
394
395         EasyMock.expect(
396             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
397                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ) ).andThrow(
398             new UnauthorizedException( "User not authorized" ) );
399         httpAuthControl.replay();
400         servletAuthControl.replay();
401
402         InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
403         assertNotNull( "artifact.jar inputstream", is );
404
405         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
406         mockHttpServletRequest.setMethod( "PUT" );
407         mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
408         mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
409         mockHttpServletRequest.setContentType( "application/octet-stream" );
410
411         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
412
413         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
414
415         httpAuthControl.verify();
416         servletAuthControl.verify();
417
418         assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
419     }
420
421     // test deploy with a valid user with write access
422     @Test
423     public void testPutWithValidUserWithWriteAccess()
424         throws Exception
425     {
426         assertTrue( Files.exists(repoRootInternal.getRoot()) );
427
428         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
429         String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
430         InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
431         assertNotNull( "artifact.jar inputstream", is );
432
433         servlet.setDavSessionProvider( davSessionProvider );
434
435         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
436         archivaDavResourceFactory.setHttpAuth( httpAuth );
437         archivaDavResourceFactory.setServletAuth( servletAuth );
438
439         TestAuditListener listener = new TestAuditListener();
440         archivaDavResourceFactory.addAuditListener( listener );
441         servlet.setResourceFactory( archivaDavResourceFactory );
442
443         AuthenticationResult result = new AuthenticationResult();
444
445         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
446                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
447             result );
448
449         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
450                                                       anyObject( AuthenticationResult.class ) ) ).andReturn( true );
451
452         User user = new SimpleUser();
453         user.setUsername( "admin" );
454
455         // ArchivaDavResourceFactory#isAuthorized()
456         SecuritySession session = new DefaultSecuritySession();
457
458         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
459                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
460             result );
461
462         EasyMock.expect( httpAuth.getSecuritySession( mockHttpServletRequest.getSession() ) ).andReturn( session );
463
464         EasyMock.expect( httpAuth.getSessionUser( mockHttpServletRequest.getSession() ) ).andReturn( user );
465
466         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
467             true );
468
469         EasyMock.expect(
470             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
471                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ) ).andReturn( true );
472
473         httpAuthControl.replay();
474         servletAuthControl.replay();
475
476         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
477         mockHttpServletRequest.setMethod( "PUT" );
478         mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
479         mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
480         mockHttpServletRequest.setContentType( "application/octet-stream" );
481
482         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
483
484         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
485
486         httpAuthControl.verify();
487         servletAuthControl.verify();
488
489         assertEquals( HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus() );
490
491         assertEquals( "admin", listener.getEvents().get( 0 ).getUserId() );
492     }
493
494     // test get with invalid user, and guest has read access to repo
495     @Test
496     public void testGetWithInvalidUserAndGuestHasReadAccess()
497         throws Exception
498     {
499         String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
500         String expectedArtifactContents = "dummy-commons-lang-artifact";
501
502         Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
503         Files.createDirectories(artifactFile.getParent());
504
505         org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);
506
507         servlet.setDavSessionProvider( davSessionProvider );
508
509         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
510         archivaDavResourceFactory.setHttpAuth( httpAuth );
511         archivaDavResourceFactory.setServletAuth( servletAuth );
512
513         servlet.setResourceFactory( archivaDavResourceFactory );
514
515         AuthenticationResult result = new AuthenticationResult();
516
517         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
518                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
519             result );
520
521         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
522                                                       anyObject( AuthenticationResult.class ) ) ).andThrow(
523             new AuthenticationException( "Authentication error" ) );
524
525         EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
526                                                    ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ).andReturn(
527             true );
528
529         // ArchivaDavResourceFactory#isAuthorized()
530         SecuritySession session = new DefaultSecuritySession();
531
532         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
533                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
534             result );
535
536         EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );
537
538         EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( null );
539
540         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
541             true );
542
543         EasyMock.expect(
544             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
545                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ) ).andReturn( true );
546         httpAuthControl.replay();
547         servletAuthControl.replay();
548
549         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
550         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
551         mockHttpServletRequest.setMethod( "GET" );
552         mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
553
554         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
555
556         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
557
558         httpAuthControl.verify();
559         servletAuthControl.verify();
560
561         assertEquals( HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus() );
562
563         assertEquals( "Expected file contents", expectedArtifactContents, mockHttpServletResponse.getContentAsString() );
564     }
565
566     // test get with invalid user, and guest has no read access to repo
567     @Test
568     public void testGetWithInvalidUserAndGuestHasNoReadAccess()
569         throws Exception
570     {
571         String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
572         String expectedArtifactContents = "dummy-commons-lang-artifact";
573
574         Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
575         Files.createDirectories(artifactFile.getParent());
576
577         org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);
578
579         servlet.setDavSessionProvider( davSessionProvider );
580
581         AuthenticationResult result = new AuthenticationResult();
582
583         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
584                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
585             result );
586
587         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
588                                                       anyObject( AuthenticationResult.class ) ) ).andThrow(
589             new AuthenticationException( "Authentication error" ) );
590
591         EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
592                                                    ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ).andReturn(
593             false );
594         httpAuthControl.replay();
595         servletAuthControl.replay();
596
597         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
598         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
599         mockHttpServletRequest.setMethod( "GET" );
600         mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
601
602         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
603
604         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
605
606         httpAuthControl.verify();
607         servletAuthControl.verify();
608
609         assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
610     }
611
612     // test get with valid user with read access to repo
613     @Test
614     public void testGetWithAValidUserWithReadAccess()
615         throws Exception
616     {
617         String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
618         String expectedArtifactContents = "dummy-commons-lang-artifact";
619
620         Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
621         Files.createDirectories(artifactFile.getParent());
622
623         org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);
624
625         servlet.setDavSessionProvider( davSessionProvider );
626
627         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
628         archivaDavResourceFactory.setHttpAuth( httpAuth );
629         archivaDavResourceFactory.setServletAuth( servletAuth );
630
631         servlet.setResourceFactory( archivaDavResourceFactory );
632
633         AuthenticationResult result = new AuthenticationResult();
634
635         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
636                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
637             result );
638
639         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
640                                                       anyObject( AuthenticationResult.class ) ) ).andReturn( true );
641         // ArchivaDavResourceFactory#isAuthorized()
642         SecuritySession session = new DefaultSecuritySession();
643
644         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
645                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
646             result );
647
648         EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );
649
650         EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( new SimpleUser() );
651
652         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
653             true );
654
655         EasyMock.expect(
656             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
657                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ) ).andReturn( true );
658
659         httpAuthControl.replay();
660         servletAuthControl.replay();
661
662         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
663         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
664         mockHttpServletRequest.setMethod( "GET" );
665         mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
666
667         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
668
669         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
670
671         httpAuthControl.verify();
672         servletAuthControl.verify();
673
674         assertEquals( HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus() );
675         assertEquals( "Expected file contents", expectedArtifactContents, mockHttpServletResponse.getContentAsString() );
676     }
677
678     // test get with valid user with no read access to repo
679     @Test
680     public void testGetWithAValidUserWithNoReadAccess()
681         throws Exception
682     {
683         String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
684         String expectedArtifactContents = "dummy-commons-lang-artifact";
685
686         Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
687         Files.createDirectories(artifactFile.getParent());
688
689         org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);
690
691         servlet.setDavSessionProvider( davSessionProvider );
692
693         ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
694         archivaDavResourceFactory.setHttpAuth( httpAuth );
695         archivaDavResourceFactory.setServletAuth( servletAuth );
696
697         servlet.setResourceFactory( archivaDavResourceFactory );
698
699         AuthenticationResult result = new AuthenticationResult();
700
701         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
702                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
703             result );
704
705         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
706                                                       anyObject( AuthenticationResult.class ) ) ).andReturn( true );
707
708         // ArchivaDavResourceFactory#isAuthorized()
709         SecuritySession session = new DefaultSecuritySession();
710
711         EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
712                                                            anyObject( HttpServletResponse.class ) ) ).andReturn(
713             result );
714
715         EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );
716
717         EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( new SimpleUser() );
718
719         EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
720             true );
721
722         EasyMock.expect(
723             servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
724                                       eq( ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) ) ).andThrow(
725             new UnauthorizedException( "User not authorized to read repository." ) );
726         httpAuthControl.replay();
727         servletAuthControl.replay();
728
729         MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
730         mockHttpServletRequest.addHeader( "User-Agent", "foo" );
731         mockHttpServletRequest.setMethod( "GET" );
732         mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
733
734
735         MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
736
737         servlet.service( mockHttpServletRequest, mockHttpServletResponse );
738
739         httpAuthControl.verify();
740         servletAuthControl.verify();
741
742         assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
743     }
744
745 }