]> source.dussan.org Git - archiva.git/blob
f62fef2e0b8942f1add6968ed7b692d38fffe7d8
[archiva.git] /
1 package org.apache.archiva.rest.v2.svc.maven;
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  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19
20 import org.apache.archiva.admin.model.AuditInformation;
21 import org.apache.archiva.admin.model.RepositoryAdminException;
22 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
23 import org.apache.archiva.components.rest.model.PagedResult;
24 import org.apache.archiva.components.rest.util.QueryHelper;
25 import org.apache.archiva.configuration.model.ManagedRepositoryConfiguration;
26 import org.apache.archiva.redback.authentication.AuthenticationResult;
27 import org.apache.archiva.redback.authorization.AuthorizationException;
28 import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal;
29 import org.apache.archiva.redback.rest.services.RedbackRequestInformation;
30 import org.apache.archiva.redback.system.DefaultSecuritySession;
31 import org.apache.archiva.redback.system.SecuritySession;
32 import org.apache.archiva.redback.system.SecuritySystem;
33 import org.apache.archiva.redback.users.User;
34 import org.apache.archiva.redback.users.UserManagerException;
35 import org.apache.archiva.redback.users.UserNotFoundException;
36 import org.apache.archiva.repository.ManagedRepository;
37 import org.apache.archiva.repository.ReleaseScheme;
38 import org.apache.archiva.repository.Repository;
39 import org.apache.archiva.repository.RepositoryRegistry;
40 import org.apache.archiva.repository.RepositoryType;
41 import org.apache.archiva.repository.content.ContentItem;
42 import org.apache.archiva.repository.content.LayoutException;
43 import org.apache.archiva.repository.storage.fs.FsStorageUtil;
44 import org.apache.archiva.rest.api.v2.model.FileInfo;
45 import org.apache.archiva.rest.api.v2.model.MavenManagedRepository;
46 import org.apache.archiva.rest.api.v2.model.MavenManagedRepositoryUpdate;
47 import org.apache.archiva.rest.api.v2.svc.ArchivaRestServiceException;
48 import org.apache.archiva.rest.api.v2.svc.ErrorKeys;
49 import org.apache.archiva.rest.api.v2.svc.ErrorMessage;
50 import org.apache.archiva.rest.api.v2.svc.maven.MavenManagedRepositoryService;
51 import org.apache.archiva.security.common.ArchivaRoleConstants;
52 import org.apache.commons.lang3.StringUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.stereotype.Service;
56
57 import javax.servlet.http.HttpServletResponse;
58 import javax.ws.rs.core.Context;
59 import javax.ws.rs.core.Response;
60 import javax.ws.rs.core.UriInfo;
61 import java.io.IOException;
62 import java.util.Collection;
63 import java.util.Comparator;
64 import java.util.List;
65 import java.util.function.Predicate;
66 import java.util.stream.Collectors;
67
68 import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_READ_REPOSITORY;
69 import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_ADD_ARTIFACT;
70
71 /**
72  * @author Martin Stockhammer <martin_s@apache.org>
73  */
74 @Service("v2.managedMavenRepositoryService#rest")
75 public class DefaultMavenManagedRepositoryService implements MavenManagedRepositoryService
76 {
77     @Context
78     HttpServletResponse httpServletResponse;
79
80     @Context
81     UriInfo uriInfo;
82
83     private static final Logger log = LoggerFactory.getLogger( DefaultMavenManagedRepositoryService.class );
84     private static final QueryHelper<ManagedRepository> QUERY_HELPER = new QueryHelper<>( new String[]{"id", "name"} );
85     static
86     {
87         QUERY_HELPER.addStringFilter( "id", ManagedRepository::getId );
88         QUERY_HELPER.addStringFilter( "name", ManagedRepository::getName );
89         QUERY_HELPER.addStringFilter( "location", (r)  -> r.getLocation().toString() );
90         QUERY_HELPER.addBooleanFilter( "snapshot", (r) -> r.getActiveReleaseSchemes( ).contains( ReleaseScheme.SNAPSHOT ) );
91         QUERY_HELPER.addBooleanFilter( "release", (r) -> r.getActiveReleaseSchemes().contains( ReleaseScheme.RELEASE ));
92         QUERY_HELPER.addNullsafeFieldComparator( "id", ManagedRepository::getId );
93         QUERY_HELPER.addNullsafeFieldComparator( "name", ManagedRepository::getName );
94     }
95
96     private final ManagedRepositoryAdmin managedRepositoryAdmin;
97     private final RepositoryRegistry repositoryRegistry;
98     private final SecuritySystem securitySystem;
99
100     public DefaultMavenManagedRepositoryService( SecuritySystem securitySystem,
101                                                  RepositoryRegistry repositoryRegistry,
102                                                  ManagedRepositoryAdmin managedRepositoryAdmin )
103     {
104         this.securitySystem = securitySystem;
105         this.repositoryRegistry = repositoryRegistry;
106         this.managedRepositoryAdmin = managedRepositoryAdmin;
107     }
108
109     protected AuditInformation getAuditInformation( )
110     {
111         RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get( );
112         User user;
113         String remoteAddr;
114         if (redbackRequestInformation==null) {
115             user = null;
116             remoteAddr = null;
117         } else
118         {
119             user = redbackRequestInformation.getUser( );
120             remoteAddr = redbackRequestInformation.getRemoteAddr( );
121         }
122         return new AuditInformation( user, remoteAddr );
123     }
124
125     public static ManagedRepositoryConfiguration toConfig(MavenManagedRepository repo) {
126         ManagedRepositoryConfiguration cfg = new ManagedRepositoryConfiguration( );
127         return cfg;
128
129     }
130
131     @Override
132     public PagedResult<MavenManagedRepository> getManagedRepositories( final String searchTerm, final Integer offset,
133                                                                        final Integer limit, final List<String> orderBy,
134                                                                        final String order ) throws ArchivaRestServiceException
135     {
136         try
137         {
138             Collection<ManagedRepository> repos = repositoryRegistry.getManagedRepositories( );
139             final Predicate<ManagedRepository> queryFilter = QUERY_HELPER.getQueryFilter( searchTerm ).and( r -> r.getType() == RepositoryType.MAVEN );
140             final Comparator<ManagedRepository> comparator = QUERY_HELPER.getComparator( orderBy, order );
141             int totalCount = Math.toIntExact( repos.stream( ).filter( queryFilter ).count( ) );
142             return PagedResult.of( totalCount, offset, limit, repos.stream( ).filter( queryFilter ).sorted( comparator )
143                 .map( MavenManagedRepository::of ).skip( offset ).limit( limit ).collect( Collectors.toList( ) ) );
144         }
145         catch (ArithmeticException e) {
146             log.error( "Invalid number of repositories detected." );
147             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.INVALID_RESULT_SET_ERROR ) );
148         }
149     }
150
151     @Override
152     public MavenManagedRepository getManagedRepository( String repositoryId ) throws ArchivaRestServiceException
153     {
154         ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
155         if (repo==null) {
156             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
157         }
158         if (repo.getType()!=RepositoryType.MAVEN) {
159             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_WRONG_TYPE, repositoryId, repo.getType().name() ), 404 );
160         }
161         return MavenManagedRepository.of( repo );
162     }
163
164     @Override
165     public Response deleteManagedRepository( String repositoryId, Boolean deleteContent ) throws ArchivaRestServiceException
166     {
167         MavenManagedRepository repo = getManagedRepository( repositoryId );
168         if (repo != null)
169         {
170             try
171             {
172                 managedRepositoryAdmin.deleteManagedRepository( repositoryId, getAuditInformation( ), deleteContent );
173                 return Response.ok( ).build( );
174             }
175             catch ( RepositoryAdminException e )
176             {
177                 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_DELETE_FAILED, e.getMessage( ) ) );
178             }
179         } else {
180             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
181         }
182     }
183
184     private org.apache.archiva.admin.model.beans.ManagedRepository convert(MavenManagedRepository repository) {
185         org.apache.archiva.admin.model.beans.ManagedRepository repoBean = new org.apache.archiva.admin.model.beans.ManagedRepository( );
186         repoBean.setId( repository.getId( ) );
187         repoBean.setName( repository.getName() );
188         repoBean.setDescription( repository.getDescription() );
189         repoBean.setBlockRedeployments( repository.isBlocksRedeployments() );
190         repoBean.setCronExpression( repository.getSchedulingDefinition() );
191         repoBean.setLocation( repository.getLocation() );
192         repoBean.setReleases( repository.getReleaseSchemes().contains( ReleaseScheme.RELEASE.name() ) );
193         repoBean.setSnapshots( repository.getReleaseSchemes().contains( ReleaseScheme.SNAPSHOT.name() ) );
194         repoBean.setScanned( repository.isScanned() );
195         repoBean.setDeleteReleasedSnapshots( repository.isDeleteSnapshotsOfRelease() );
196         repoBean.setSkipPackedIndexCreation( repository.isSkipPackedIndexCreation() );
197         repoBean.setRetentionCount( repository.getRetentionCount() );
198         if (repository.getRetentionPeriod()!=null)
199         {
200             repoBean.setRetentionPeriod( repository.getRetentionPeriod( ).getDays( ) );
201         }
202         repoBean.setIndexDirectory( repository.getIndexPath() );
203         repoBean.setPackedIndexDirectory( repository.getPackedIndexPath() );
204         repoBean.setLayout( repository.getLayout() );
205         repoBean.setType( RepositoryType.MAVEN.name( ) );
206         return repoBean;
207     }
208
209     @Override
210     public MavenManagedRepository addManagedRepository( MavenManagedRepository managedRepository ) throws ArchivaRestServiceException
211     {
212         final String repoId = managedRepository.getId( );
213         if ( StringUtils.isEmpty( repoId ) ) {
214             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_INVALID_ID, repoId ), 422 );
215         }
216         Repository repo = repositoryRegistry.getRepository( repoId );
217         if (repo!=null) {
218             httpServletResponse.setHeader( "Location", uriInfo.getAbsolutePathBuilder( ).path( repoId ).build( ).toString( ) );
219             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ID_EXISTS, repoId ), 303 );
220         }
221         try
222         {
223             managedRepositoryAdmin.addManagedRepository( convert( managedRepository ), managedRepository.isHasStagingRepository(), getAuditInformation() );
224             httpServletResponse.setStatus( 201 );
225             return MavenManagedRepository.of( repositoryRegistry.getManagedRepository( repoId ) );
226         }
227         catch ( RepositoryAdminException e )
228         {
229             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) );
230         }
231     }
232
233     @Override
234     public MavenManagedRepository updateManagedRepository( final String repositoryId, final MavenManagedRepositoryUpdate managedRepository ) throws ArchivaRestServiceException
235     {
236         org.apache.archiva.admin.model.beans.ManagedRepository repo = convert( managedRepository );
237         try
238         {
239             managedRepositoryAdmin.updateManagedRepository( repo, managedRepository.isHasStagingRepository( ), getAuditInformation( ), managedRepository.isResetStats( ) );
240             ManagedRepository newRepo = repositoryRegistry.getManagedRepository( managedRepository.getId( ) );
241             if (newRepo==null) {
242                 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_UPDATE_FAILED, repositoryId ) );
243             }
244             return MavenManagedRepository.of( newRepo );
245         }
246         catch ( RepositoryAdminException e )
247         {
248             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) );
249         }
250     }
251
252     @Override
253     public FileInfo getFileStatus( String repositoryId, String fileLocation ) throws ArchivaRestServiceException
254     {
255         ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
256         if (repo==null) {
257             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
258         }
259         try
260         {
261             ContentItem contentItem = repo.getContent( ).toItem( fileLocation );
262             if (contentItem.getAsset( ).exists( ))  {
263                 return FileInfo.of( contentItem.getAsset( ) );
264             } else {
265                 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, repositoryId, fileLocation ), 404 );
266             }
267         }
268         catch ( LayoutException e )
269         {
270             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage( ) ) );
271         }
272     }
273
274     @Override
275     public Response copyArtifact( String srcRepositoryId, String dstRepositoryId,
276                                   String path ) throws ArchivaRestServiceException
277     {
278         final AuditInformation auditInformation = getAuditInformation( );
279         final String userName = auditInformation.getUser( ).getUsername( );
280         if ( StringUtils.isEmpty( userName ) )
281         {
282             httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" );
283             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.NOT_AUTHENTICATED ), 401 );
284         }
285         ManagedRepository srcRepo = repositoryRegistry.getManagedRepository( srcRepositoryId );
286         if (srcRepo==null) {
287             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, srcRepositoryId ), 404 );
288         }
289         ManagedRepository dstRepo = repositoryRegistry.getManagedRepository( dstRepositoryId );
290         if (dstRepo==null) {
291             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, dstRepositoryId ), 404 );
292         }
293         checkAuthority( auditInformation.getUser().getUsername(), srcRepositoryId, dstRepositoryId );
294         try
295         {
296             ContentItem srcItem = srcRepo.getContent( ).toItem( path );
297             ContentItem dstItem = dstRepo.getContent( ).toItem( path );
298             if (!srcItem.getAsset().exists()){
299                 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, srcRepositoryId, path ), 404 );
300             }
301             if (dstItem.getAsset().exists()) {
302                 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_EXISTS_AT_DEST, srcRepositoryId, path ), 400 );
303             }
304             FsStorageUtil.copyAsset( srcItem.getAsset( ), dstItem.getAsset( ), true );
305         }
306         catch ( LayoutException e )
307         {
308             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage() ) );
309         }
310         catch ( IOException e )
311         {
312             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_COPY_ERROR, e.getMessage() ) );
313         }
314         return Response.ok( ).build();
315     }
316
317     private void checkAuthority(final String userName, final String srcRepositoryId, final String dstRepositoryId ) throws ArchivaRestServiceException {
318         User user;
319         try
320         {
321             user = securitySystem.getUserManager().findUser( userName );
322         }
323         catch ( UserNotFoundException e )
324         {
325             httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" );
326             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_NOT_FOUND, userName ), 401 );
327         }
328         catch ( UserManagerException e )
329         {
330             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_MANAGER_ERROR, e.getMessage( ) ) );
331         }
332
333         // check karma on source : read
334         AuthenticationResult authn = new AuthenticationResult( true, userName, null );
335         SecuritySession securitySession = new DefaultSecuritySession( authn, user );
336         try
337         {
338             boolean authz =
339                 securitySystem.isAuthorized( securitySession, OPERATION_READ_REPOSITORY,
340                     srcRepositoryId );
341             if ( !authz )
342             {
343                 throw new ArchivaRestServiceException(ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, srcRepositoryId, OPERATION_READ_REPOSITORY ), 403);
344             }
345         }
346         catch ( AuthorizationException e )
347         {
348             log.error( "Error reading permission: {}", e.getMessage(), e );
349             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403);
350         }
351
352         // check karma on target: write
353         try
354         {
355             boolean authz =
356                 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_ADD_ARTIFACT,
357                     dstRepositoryId );
358             if ( !authz )
359             {
360                 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, dstRepositoryId, OPERATION_ADD_ARTIFACT ) );
361             }
362         }
363         catch ( AuthorizationException e )
364         {
365             log.error( "Error reading permission: {}", e.getMessage(), e );
366             throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403);
367         }
368
369
370     }
371
372     @Override
373     public Response deleteArtifact( String repositoryId, String path ) throws ArchivaRestServiceException
374     {
375
376         return null;
377     }
378
379
380     @Override
381     public Response removeProjectVersion( String repositoryId, String namespace, String projectId, String version ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException
382     {
383         return null;
384     }
385
386     @Override
387     public Response deleteProject( String repositoryId, String namespace, String projectId ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException
388     {
389         return null;
390     }
391
392     @Override
393     public Response deleteNamespace( String repositoryId, String namespace ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException
394     {
395         return null;
396     }
397
398 }