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