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