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