You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RepositoryServletSecurityTest.java 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. package org.apache.archiva.webdav;
  2. /*
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. */
  20. import junit.framework.TestCase;
  21. import net.sf.ehcache.CacheManager;
  22. import org.apache.archiva.configuration.ArchivaConfiguration;
  23. import org.apache.archiva.configuration.Configuration;
  24. import org.apache.archiva.configuration.ManagedRepositoryConfiguration;
  25. import org.apache.archiva.redback.authentication.AuthenticationException;
  26. import org.apache.archiva.redback.authentication.AuthenticationResult;
  27. import org.apache.archiva.redback.authorization.UnauthorizedException;
  28. import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
  29. import org.apache.archiva.redback.system.DefaultSecuritySession;
  30. import org.apache.archiva.redback.system.SecuritySession;
  31. import org.apache.archiva.redback.users.User;
  32. import org.apache.archiva.redback.users.memory.SimpleUser;
  33. import org.apache.archiva.repository.RepositoryRegistry;
  34. import org.apache.archiva.webdav.mock.metadata.audit.TestAuditListener;
  35. import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
  36. import org.apache.archiva.security.ServletAuthenticator;
  37. import org.apache.archiva.security.common.ArchivaRoleConstants;
  38. import org.apache.archiva.test.utils.ArchivaSpringJUnit4ClassRunner;
  39. import org.apache.commons.io.FileUtils;
  40. import org.apache.commons.io.IOUtils;
  41. import org.apache.commons.lang3.StringUtils;
  42. import org.apache.jackrabbit.webdav.DavSessionProvider;
  43. import org.junit.After;
  44. import org.junit.Before;
  45. import org.junit.Rule;
  46. import org.junit.Test;
  47. import org.junit.runner.RunWith;
  48. import org.mockito.Mockito;
  49. import org.springframework.context.ApplicationContext;
  50. import org.springframework.mock.web.MockHttpServletRequest;
  51. import org.springframework.mock.web.MockHttpServletResponse;
  52. import org.springframework.mock.web.MockServletConfig;
  53. import org.springframework.mock.web.MockServletContext;
  54. import org.springframework.test.context.ContextConfiguration;
  55. import org.springframework.web.context.WebApplicationContext;
  56. import javax.inject.Inject;
  57. import javax.servlet.ServletContext;
  58. import javax.servlet.http.HttpServletRequest;
  59. import javax.servlet.http.HttpServletResponse;
  60. import javax.servlet.http.HttpSession;
  61. import java.io.InputStream;
  62. import java.nio.charset.Charset;
  63. import java.nio.file.Files;
  64. import java.nio.file.Path;
  65. import java.nio.file.Paths;
  66. import java.util.ArrayList;
  67. import java.util.List;
  68. import java.util.concurrent.atomic.AtomicReference;
  69. import static org.mockito.AdditionalMatchers.not;
  70. import static org.mockito.ArgumentMatchers.any;
  71. import static org.mockito.ArgumentMatchers.eq;
  72. import static org.mockito.Mockito.*;
  73. /**
  74. * RepositoryServletSecurityTest Test the flow of the authentication and authorization checks. This does not necessarily
  75. * perform redback security checking.
  76. */
  77. @RunWith( ArchivaSpringJUnit4ClassRunner.class )
  78. @ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context-servlet-security-test.xml" } )
  79. public class RepositoryServletSecurityTest
  80. extends TestCase
  81. {
  82. protected static final String REPOID_INTERNAL = "internal";
  83. @Inject
  84. protected ArchivaConfiguration archivaConfiguration;
  85. @Inject
  86. protected RepositoryRegistry repositoryRegistry;
  87. @SuppressWarnings( "unused" )
  88. @Inject
  89. RepositoryGroupHandler repositoryGroupHandler;
  90. private DavSessionProvider davSessionProvider;
  91. private ServletAuthenticator servletAuth;
  92. private HttpAuthenticator httpAuth;
  93. private RepositoryServlet servlet;
  94. @Inject
  95. ApplicationContext applicationContext;
  96. @Rule
  97. public ArchivaTemporaryFolderRule repoRootInternal = new ArchivaTemporaryFolderRule();
  98. private AtomicReference<Path> projectBase = new AtomicReference<>( );
  99. public Path getProjectBase() {
  100. if (this.projectBase.get()==null) {
  101. String pathVal = System.getProperty("mvn.project.base.dir");
  102. Path baseDir;
  103. if ( StringUtils.isEmpty(pathVal)) {
  104. baseDir= Paths.get("").toAbsolutePath();
  105. } else {
  106. baseDir = Paths.get(pathVal).toAbsolutePath();
  107. }
  108. this.projectBase.compareAndSet(null, baseDir);
  109. }
  110. return this.projectBase.get();
  111. }
  112. @Before
  113. @Override
  114. public void setUp()
  115. throws Exception
  116. {
  117. super.setUp();
  118. String appserverBase =
  119. System.getProperty( "appserver.base", getProjectBase().resolve( "target/appserver-base" ).toAbsolutePath().toString() );
  120. Path testConf = getProjectBase().resolve( "src/test/resources/repository-archiva.xml" );
  121. Path testConfDest = Paths.get(appserverBase, "conf/archiva.xml" );
  122. FileUtils.copyFile( testConf.toFile(), testConfDest.toFile() );
  123. Configuration config = archivaConfiguration.getConfiguration();
  124. // clear managed repository
  125. List<ManagedRepositoryConfiguration> f1 = new ArrayList<>(config.getManagedRepositories());
  126. for (ManagedRepositoryConfiguration f: f1 ) {
  127. config.removeManagedRepository(f);
  128. }
  129. assertEquals(0,config.getManagedRepositories().size());
  130. // add internal repo
  131. config.addManagedRepository(
  132. createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal.getRoot() ) );
  133. saveConfiguration( archivaConfiguration );
  134. CacheManager.getInstance().clearAll();
  135. servletAuth = mock( ServletAuthenticator.class );
  136. httpAuth = mock( HttpAuthenticator.class );
  137. davSessionProvider = new ArchivaDavSessionProvider( servletAuth, httpAuth );
  138. final MockServletContext mockServletContext = new MockServletContext();
  139. WebApplicationContext webApplicationContext =
  140. new AbstractRepositoryServletTestCase.TestWebapplicationContext( applicationContext, mockServletContext );
  141. mockServletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
  142. webApplicationContext );
  143. MockServletConfig mockServletConfig = new MockServletConfig()
  144. {
  145. @Override
  146. public ServletContext getServletContext()
  147. {
  148. return mockServletContext;
  149. }
  150. };
  151. servlet = new RepositoryServlet();
  152. servlet.init( mockServletConfig );
  153. }
  154. protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, Path location )
  155. {
  156. ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
  157. repo.setId( id );
  158. repo.setName( name );
  159. repo.setLocation( location.toAbsolutePath().toString() );
  160. return repo;
  161. }
  162. /*protected void saveConfiguration()
  163. throws Exception
  164. {
  165. saveConfiguration( archivaConfiguration );
  166. }*/
  167. protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
  168. throws Exception
  169. {
  170. repositoryRegistry.reload();
  171. archivaConfiguration.save( archivaConfiguration.getConfiguration() );
  172. }
  173. /*protected void setupCleanRepo( File repoRootDir )
  174. throws IOException
  175. {
  176. }*/
  177. @Override
  178. @After
  179. public void tearDown()
  180. throws Exception
  181. {
  182. /* if ( repoRootInternal.exists() )
  183. {
  184. FileUtils.deleteDirectory( repoRootInternal );
  185. }*/
  186. super.tearDown();
  187. String appBaseProp = System.getProperty( "appserver.base" );
  188. if (StringUtils.isNotEmpty( appBaseProp )) {
  189. org.apache.archiva.common.utils.FileUtils.deleteDirectory( Paths.get(appBaseProp) );
  190. }
  191. }
  192. // test deploy with invalid user, and guest has no write access to repo
  193. // 401 must be returned
  194. @Test
  195. public void testPutWithInvalidUserAndGuestHasNoWriteAccess()
  196. throws Exception
  197. {
  198. InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
  199. assertNotNull( "artifact.jar inputstream", is );
  200. servlet.setDavSessionProvider( davSessionProvider );
  201. AuthenticationResult result = new AuthenticationResult();
  202. when( httpAuth.getAuthenticationResult( any( ),
  203. any( ) ) ).thenReturn(
  204. result );
  205. when(servletAuth.isAuthenticated( any( ),
  206. any( ) )).thenThrow( new AuthenticationException( "Authentication error" ) );
  207. when(servletAuth.isAuthorized( "guest", "internal", ArchivaRoleConstants.OPERATION_ADD_ARTIFACT ))
  208. .thenThrow( new UnauthorizedException( "'guest' has no write access to repository" ) );
  209. MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  210. mockHttpServletRequest.addHeader( "User-Agent", "foo" );
  211. mockHttpServletRequest.setMethod( "PUT" );
  212. mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
  213. mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
  214. mockHttpServletRequest.setContentType( "application/octet-stream" );
  215. MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
  216. servlet.service( mockHttpServletRequest, mockHttpServletResponse );
  217. assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
  218. }
  219. // test deploy with invalid user, but guest has write access to repo
  220. @Test
  221. public void testPutWithInvalidUserAndGuestHasWriteAccess()
  222. throws Exception
  223. {
  224. servlet.setDavSessionProvider( davSessionProvider );
  225. ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
  226. archivaDavResourceFactory.setHttpAuth( httpAuth );
  227. archivaDavResourceFactory.setServletAuth( servletAuth );
  228. servlet.setResourceFactory( archivaDavResourceFactory );
  229. AuthenticationResult result = new AuthenticationResult();
  230. when( httpAuth.getAuthenticationResult( any( ),
  231. any( ) ) ).thenReturn(
  232. result );
  233. when( servletAuth.isAuthorized( "guest", "internal",
  234. ArchivaRoleConstants.OPERATION_ADD_ARTIFACT ) ).thenReturn(
  235. true );
  236. // ArchivaDavResourceFactory#isAuthorized()
  237. SecuritySession session = new DefaultSecuritySession();
  238. when( httpAuth.getAuthenticationResult( any( ),
  239. any( ) ) ).thenReturn(
  240. result );
  241. when( httpAuth.getSecuritySession( any( ) ) ).thenReturn( session );
  242. when( servletAuth.isAuthenticated( any( ),
  243. any( ) ) ).thenThrow(
  244. new AuthenticationException( "Authentication error" ) );
  245. when( httpAuth.getSessionUser( any( ) ) ).thenReturn( null );
  246. // check if guest has write access
  247. when( servletAuth.isAuthorized( "guest", "internal",
  248. ArchivaRoleConstants.OPERATION_ADD_ARTIFACT ) ).thenReturn(
  249. true );
  250. InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
  251. assertNotNull( "artifact.jar inputstream", is );
  252. MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  253. mockHttpServletRequest.addHeader( "User-Agent", "foo" );
  254. mockHttpServletRequest.setMethod( "PUT" );
  255. mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
  256. mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
  257. mockHttpServletRequest.setContentType( "application/octet-stream" );
  258. MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
  259. servlet.service( mockHttpServletRequest, mockHttpServletResponse );
  260. assertEquals( HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus() );
  261. }
  262. // test deploy with a valid user with no write access
  263. @Test
  264. public void testPutWithValidUserWithNoWriteAccess()
  265. throws Exception
  266. {
  267. servlet.setDavSessionProvider( davSessionProvider );
  268. ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
  269. archivaDavResourceFactory.setHttpAuth( httpAuth );
  270. archivaDavResourceFactory.setServletAuth( servletAuth );
  271. servlet.setResourceFactory( archivaDavResourceFactory );
  272. AuthenticationResult result = new AuthenticationResult();
  273. when( httpAuth.getAuthenticationResult( any( ),
  274. any( ) ) ).thenReturn(
  275. result );
  276. when( servletAuth.isAuthenticated( any( ),
  277. any( ) ) ).thenReturn( true );
  278. // ArchivaDavResourceFactory#isAuthorized()
  279. SecuritySession session = new DefaultSecuritySession();
  280. when( httpAuth.getAuthenticationResult( any( ),
  281. any( ) ) ).thenReturn(
  282. result );
  283. MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  284. when( httpAuth.getSecuritySession( mockHttpServletRequest.getSession( true ) ) ).thenReturn(
  285. session );
  286. when( httpAuth.getSessionUser( mockHttpServletRequest.getSession() ) ).thenReturn( new SimpleUser() );
  287. when( servletAuth.isAuthenticated( any( ), eq( result ) ) ).thenReturn(
  288. true );
  289. when(
  290. servletAuth.isAuthorized( any( ), eq( session ), eq( "internal" ),
  291. eq( ArchivaRoleConstants.OPERATION_ADD_ARTIFACT ) ) ).thenThrow(
  292. new UnauthorizedException( "User not authorized" ) );
  293. InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
  294. assertNotNull( "artifact.jar inputstream", is );
  295. mockHttpServletRequest.addHeader( "User-Agent", "foo" );
  296. mockHttpServletRequest.setMethod( "PUT" );
  297. mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
  298. mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
  299. mockHttpServletRequest.setContentType( "application/octet-stream" );
  300. MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
  301. servlet.service( mockHttpServletRequest, mockHttpServletResponse );
  302. assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
  303. }
  304. // test deploy with a valid user with write access
  305. @Test
  306. public void testPutWithValidUserWithWriteAccess()
  307. throws Exception
  308. {
  309. assertTrue( Files.exists(repoRootInternal.getRoot()) );
  310. MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  311. String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
  312. InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
  313. assertNotNull( "artifact.jar inputstream", is );
  314. servlet.setDavSessionProvider( davSessionProvider );
  315. ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
  316. archivaDavResourceFactory.setHttpAuth( httpAuth );
  317. archivaDavResourceFactory.setServletAuth( servletAuth );
  318. TestAuditListener listener = new TestAuditListener();
  319. archivaDavResourceFactory.addAuditListener( listener );
  320. servlet.setResourceFactory( archivaDavResourceFactory );
  321. AuthenticationResult result = new AuthenticationResult();
  322. when( httpAuth.getAuthenticationResult( any( ),
  323. any( ) ) ).thenReturn(
  324. result );
  325. when( servletAuth.isAuthenticated( any( ),
  326. any( ) ) ).thenReturn( true );
  327. User user = new SimpleUser();
  328. user.setUsername( "admin" );
  329. // ArchivaDavResourceFactory#isAuthorized()
  330. SecuritySession session = new DefaultSecuritySession();
  331. when( httpAuth.getAuthenticationResult( any( ),
  332. any( ) ) ).thenReturn(
  333. result );
  334. when( httpAuth.getSecuritySession( mockHttpServletRequest.getSession() ) ).thenReturn( session );
  335. when( httpAuth.getSessionUser( mockHttpServletRequest.getSession() ) ).thenReturn( user );
  336. when( servletAuth.isAuthenticated( any( ), eq( result ) ) ).thenReturn(
  337. true );
  338. when(
  339. servletAuth.isAuthorized( any( ), eq( session ), eq( "internal" ),
  340. eq( ArchivaRoleConstants.OPERATION_ADD_ARTIFACT ) ) ).thenReturn( true );
  341. mockHttpServletRequest.addHeader( "User-Agent", "foo" );
  342. mockHttpServletRequest.setMethod( "PUT" );
  343. mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
  344. mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
  345. mockHttpServletRequest.setContentType( "application/octet-stream" );
  346. MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
  347. servlet.service( mockHttpServletRequest, mockHttpServletResponse );
  348. assertEquals( HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus() );
  349. assertEquals( "admin", listener.getEvents().get( 0 ).getUserId() );
  350. }
  351. // test get with invalid user, and guest has read access to repo
  352. @Test
  353. public void testGetWithInvalidUserAndGuestHasReadAccess()
  354. throws Exception
  355. {
  356. String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
  357. String expectedArtifactContents = "dummy-commons-lang-artifact";
  358. Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
  359. Files.createDirectories(artifactFile.getParent());
  360. org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);
  361. servlet.setDavSessionProvider( davSessionProvider );
  362. ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
  363. archivaDavResourceFactory.setHttpAuth( httpAuth );
  364. archivaDavResourceFactory.setServletAuth( servletAuth );
  365. servlet.setResourceFactory( archivaDavResourceFactory );
  366. AuthenticationResult result = new AuthenticationResult();
  367. when( httpAuth.getAuthenticationResult( any( ),
  368. any( ) ) ).thenReturn(
  369. result );
  370. when( servletAuth.isAuthorized( "guest", "internal",
  371. ArchivaRoleConstants.OPERATION_READ_REPOSITORY ) ).thenReturn(
  372. true );
  373. // ArchivaDavResourceFactory#isAuthorized()
  374. SecuritySession session = new DefaultSecuritySession();
  375. when( httpAuth.getSecuritySession( any( ) ) ).thenReturn( session );
  376. when( httpAuth.getSessionUser( any( ) ) ).thenReturn( null );
  377. when( servletAuth.isAuthenticated( any( ), eq( result ) ) ).thenReturn(
  378. true );
  379. when( servletAuth.isAuthenticated( any( ),
  380. not(eq(result)) ) ).thenThrow(
  381. new AuthenticationException( "Authentication error" ) );
  382. when(
  383. servletAuth.isAuthorized( any( ), eq( session ), eq( "internal" ),
  384. eq( ArchivaRoleConstants.OPERATION_READ_REPOSITORY ) ) ).thenReturn( true );
  385. MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  386. mockHttpServletRequest.addHeader( "User-Agent", "foo" );
  387. mockHttpServletRequest.setMethod( "GET" );
  388. mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
  389. MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
  390. servlet.service( mockHttpServletRequest, mockHttpServletResponse );
  391. assertEquals( HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus() );
  392. assertEquals( "Expected file contents", expectedArtifactContents, mockHttpServletResponse.getContentAsString() );
  393. }
  394. // test get with invalid user, and guest has no read access to repo
  395. @Test
  396. public void testGetWithInvalidUserAndGuestHasNoReadAccess()
  397. throws Exception
  398. {
  399. String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
  400. String expectedArtifactContents = "dummy-commons-lang-artifact";
  401. Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
  402. Files.createDirectories(artifactFile.getParent());
  403. org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);
  404. servlet.setDavSessionProvider( davSessionProvider );
  405. AuthenticationResult result = new AuthenticationResult();
  406. when( httpAuth.getAuthenticationResult( any( ),
  407. any( ) ) ).thenReturn(
  408. result );
  409. when( servletAuth.isAuthenticated( any( ),
  410. any( ) ) ).thenThrow(
  411. new AuthenticationException( "Authentication error" ) );
  412. when( servletAuth.isAuthorized( "guest", "internal",
  413. ArchivaRoleConstants.OPERATION_READ_REPOSITORY ) ).thenReturn(
  414. false );
  415. MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  416. mockHttpServletRequest.addHeader( "User-Agent", "foo" );
  417. mockHttpServletRequest.setMethod( "GET" );
  418. mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
  419. MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
  420. servlet.service( mockHttpServletRequest, mockHttpServletResponse );
  421. assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
  422. }
  423. // test get with valid user with read access to repo
  424. @Test
  425. public void testGetWithAValidUserWithReadAccess()
  426. throws Exception
  427. {
  428. String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
  429. String expectedArtifactContents = "dummy-commons-lang-artifact";
  430. Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
  431. Files.createDirectories(artifactFile.getParent());
  432. org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);
  433. servlet.setDavSessionProvider( davSessionProvider );
  434. ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
  435. archivaDavResourceFactory.setHttpAuth( httpAuth );
  436. archivaDavResourceFactory.setServletAuth( servletAuth );
  437. servlet.setResourceFactory( archivaDavResourceFactory );
  438. AuthenticationResult result = new AuthenticationResult();
  439. when( httpAuth.getAuthenticationResult( any( ),
  440. any( ) ) ).thenReturn(
  441. result );
  442. when( servletAuth.isAuthenticated( any( ),
  443. any( ) ) ).thenReturn( true );
  444. // ArchivaDavResourceFactory#isAuthorized()
  445. SecuritySession session = new DefaultSecuritySession();
  446. when( httpAuth.getAuthenticationResult( any( ),
  447. any( ) ) ).thenReturn(
  448. result );
  449. when( httpAuth.getSecuritySession( any( ) ) ).thenReturn( session );
  450. when( httpAuth.getSessionUser( any( ) ) ).thenReturn( new SimpleUser() );
  451. when( servletAuth.isAuthenticated( any( ), eq( result ) ) ).thenReturn(
  452. true );
  453. when(
  454. servletAuth.isAuthorized( any( ), eq( session ), eq( "internal" ),
  455. eq( ArchivaRoleConstants.OPERATION_READ_REPOSITORY ) ) ).thenReturn( true );
  456. MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  457. mockHttpServletRequest.addHeader( "User-Agent", "foo" );
  458. mockHttpServletRequest.setMethod( "GET" );
  459. mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
  460. MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
  461. servlet.service( mockHttpServletRequest, mockHttpServletResponse );
  462. assertEquals( HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus() );
  463. assertEquals( "Expected file contents", expectedArtifactContents, mockHttpServletResponse.getContentAsString() );
  464. }
  465. // test get with valid user with no read access to repo
  466. @Test
  467. public void testGetWithAValidUserWithNoReadAccess()
  468. throws Exception
  469. {
  470. String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
  471. String expectedArtifactContents = "dummy-commons-lang-artifact";
  472. Path artifactFile = repoRootInternal.getRoot().resolve( commonsLangJar );
  473. Files.createDirectories(artifactFile.getParent());
  474. org.apache.archiva.common.utils.FileUtils.writeStringToFile( artifactFile, Charset.defaultCharset() , expectedArtifactContents);
  475. servlet.setDavSessionProvider( davSessionProvider );
  476. ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
  477. archivaDavResourceFactory.setHttpAuth( httpAuth );
  478. archivaDavResourceFactory.setServletAuth( servletAuth );
  479. servlet.setResourceFactory( archivaDavResourceFactory );
  480. AuthenticationResult result = new AuthenticationResult();
  481. when( httpAuth.getAuthenticationResult( any( ),
  482. any( ) ) ).thenReturn(
  483. result );
  484. when( servletAuth.isAuthenticated( any( ),
  485. any( ) ) ).thenReturn( true );
  486. // ArchivaDavResourceFactory#isAuthorized()
  487. SecuritySession session = new DefaultSecuritySession();
  488. when( httpAuth.getAuthenticationResult( any( ),
  489. any( ) ) ).thenReturn(
  490. result );
  491. when( httpAuth.getSecuritySession( any( ) ) ).thenReturn( session );
  492. when( httpAuth.getSessionUser( any( ) ) ).thenReturn( new SimpleUser() );
  493. when( servletAuth.isAuthenticated( any( ), eq( result ) ) ).thenReturn(
  494. true );
  495. when(
  496. servletAuth.isAuthorized( any( ), eq( session ), eq( "internal" ),
  497. eq( ArchivaRoleConstants.OPERATION_READ_REPOSITORY ) ) ).thenThrow(
  498. new UnauthorizedException( "User not authorized to read repository." ) );
  499. MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
  500. mockHttpServletRequest.addHeader( "User-Agent", "foo" );
  501. mockHttpServletRequest.setMethod( "GET" );
  502. mockHttpServletRequest.setRequestURI( "/repository/internal/" + commonsLangJar );
  503. MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
  504. servlet.service( mockHttpServletRequest, mockHttpServletResponse );
  505. assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
  506. }
  507. }