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