]> source.dussan.org Git - archiva.git/blob
ddf22be14000dd5dc52d1bfe67df6008c5407afb
[archiva.git] /
1 package org.apache.archiva.web.rss;
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 import com.sun.syndication.feed.synd.SyndFeed;
23 import com.sun.syndication.io.FeedException;
24 import com.sun.syndication.io.SyndFeedOutput;
25 import org.apache.archiva.metadata.repository.RepositorySession;
26 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
27 import org.apache.archiva.redback.authentication.AuthenticationException;
28 import org.apache.archiva.redback.policy.AccountLockedException;
29 import org.apache.archiva.redback.policy.MustChangePasswordException;
30 import org.apache.archiva.redback.users.UserManager;
31 import org.apache.archiva.redback.users.UserNotFoundException;
32 import org.apache.archiva.rss.processor.RssFeedProcessor;
33 import org.apache.archiva.security.AccessDeniedException;
34 import org.apache.archiva.security.ArchivaSecurityException;
35 import org.apache.archiva.security.PrincipalNotFoundException;
36 import org.apache.archiva.security.ServletAuthenticator;
37 import org.apache.archiva.security.UserRepositories;
38 import org.apache.archiva.security.common.ArchivaRoleConstants;
39 import org.apache.commons.codec.Decoder;
40 import org.apache.commons.codec.DecoderException;
41 import org.apache.commons.codec.binary.Base64;
42 import org.apache.commons.lang.StringUtils;
43 import org.apache.archiva.redback.authentication.AuthenticationResult;
44 import org.apache.archiva.redback.authorization.AuthorizationException;
45 import org.apache.archiva.redback.authorization.UnauthorizedException;
46 import org.apache.archiva.redback.system.SecuritySession;
47 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.web.context.WebApplicationContext;
51 import org.springframework.web.context.support.WebApplicationContextUtils;
52
53 import javax.servlet.ServletConfig;
54 import javax.servlet.ServletException;
55 import javax.servlet.http.HttpServlet;
56 import javax.servlet.http.HttpServletRequest;
57 import javax.servlet.http.HttpServletResponse;
58 import java.io.IOException;
59 import java.util.ArrayList;
60 import java.util.Collections;
61 import java.util.HashMap;
62 import java.util.List;
63 import java.util.Map;
64
65 /**
66  * Servlet for handling rss feed requests.
67  */
68 public class RssFeedServlet
69     extends HttpServlet
70 {
71     public static final String MIME_TYPE = "application/rss+xml; charset=UTF-8";
72
73     private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
74
75     private static final String COULD_NOT_AUTHENTICATE_USER = "Could not authenticate user";
76
77     private static final String USER_NOT_AUTHORIZED = "User not authorized to access feed.";
78
79     private Logger log = LoggerFactory.getLogger( RssFeedServlet.class );
80
81     private RssFeedProcessor processor;
82
83     private WebApplicationContext wac;
84
85     private UserRepositories userRepositories;
86
87     private ServletAuthenticator servletAuth;
88
89     private HttpAuthenticator httpAuth;
90
91     /**
92      * FIXME: this could be multiple implementations and needs to be configured.
93      */
94     private RepositorySessionFactory repositorySessionFactory;
95
96     @Override
97     public void init( ServletConfig servletConfig )
98         throws ServletException
99     {
100         super.init( servletConfig );
101         wac = WebApplicationContextUtils.getRequiredWebApplicationContext( servletConfig.getServletContext() );
102         userRepositories = wac.getBean( UserRepositories.class );
103         servletAuth = wac.getBean( ServletAuthenticator.class );
104         httpAuth = wac.getBean( "httpAuthenticator#basic", HttpAuthenticator.class );
105         // TODO: what if there are other types?
106         repositorySessionFactory = wac.getBean( "repositorySessionFactory", RepositorySessionFactory.class );
107     }
108
109     @Override
110     public void doGet( HttpServletRequest req, HttpServletResponse res )
111         throws ServletException, IOException
112     {
113         String repoId = null;
114         String groupId = null;
115         String artifactId = null;
116
117         String url = StringUtils.removeEnd( req.getRequestURL().toString(), "/" );
118         if ( StringUtils.countMatches( StringUtils.substringAfter( url, "feeds/" ), "/" ) > 0 )
119         {
120             artifactId = StringUtils.substringAfterLast( url, "/" );
121             groupId = StringUtils.substringBeforeLast( StringUtils.substringAfter( url, "feeds/" ), "/" );
122             groupId = StringUtils.replaceChars( groupId, '/', '.' );
123         }
124         else if ( StringUtils.countMatches( StringUtils.substringAfter( url, "feeds/" ), "/" ) == 0 )
125         {
126             repoId = StringUtils.substringAfterLast( url, "/" );
127         }
128         else
129         {
130             res.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid request url." );
131             return;
132         }
133
134         try
135         {
136             Map<String, String> map = new HashMap<>();
137             SyndFeed feed = null;
138
139             if ( isAllowed( req, repoId, groupId, artifactId ) )
140             {
141                 if ( repoId != null )
142                 {
143                     // new artifacts in repo feed request
144                     processor = wac.getBean( "rssFeedProcessor#new-artifacts", RssFeedProcessor.class );
145                     map.put( RssFeedProcessor.KEY_REPO_ID, repoId );
146                 }
147                 else if ( ( groupId != null ) && ( artifactId != null ) )
148                 {
149                     // TODO: this only works for guest - we could pass in the list of repos
150                     // new versions of artifact feed request
151                     processor = wac.getBean( "rssFeedProcessor#new-versions", RssFeedProcessor.class );
152                     map.put( RssFeedProcessor.KEY_GROUP_ID, groupId );
153                     map.put( RssFeedProcessor.KEY_ARTIFACT_ID, artifactId );
154                 }
155             }
156             else
157             {
158                 res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
159                 return;
160             }
161
162             RepositorySession repositorySession = repositorySessionFactory.createSession();
163             try
164             {
165                 feed = processor.process( map, repositorySession.getRepository() );
166             }
167             finally
168             {
169                 repositorySession.close();
170             }
171             if ( feed == null )
172             {
173                 res.sendError( HttpServletResponse.SC_NO_CONTENT, "No information available." );
174                 return;
175             }
176
177             res.setContentType( MIME_TYPE );
178
179             if ( repoId != null )
180             {
181                 feed.setLink( req.getRequestURL().toString() );
182             }
183             else if ( ( groupId != null ) && ( artifactId != null ) )
184             {
185                 feed.setLink( req.getRequestURL().toString() );
186             }
187
188             SyndFeedOutput output = new SyndFeedOutput();
189             output.output( feed, res.getWriter() );
190         }
191         catch ( UserNotFoundException unfe )
192         {
193             log.debug( COULD_NOT_AUTHENTICATE_USER, unfe );
194             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
195         }
196         catch ( AccountLockedException acce )
197         {
198             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
199         }
200         catch ( AuthenticationException authe )
201         {
202             log.debug( COULD_NOT_AUTHENTICATE_USER, authe );
203             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
204         }
205         catch ( FeedException ex )
206         {
207             log.debug( COULD_NOT_GENERATE_FEED_ERROR, ex );
208             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
209         }
210         catch ( MustChangePasswordException e )
211         {
212             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
213         }
214         catch ( UnauthorizedException e )
215         {
216             log.debug( e.getMessage() );
217             if ( repoId != null )
218             {
219                 res.setHeader( "WWW-Authenticate",
220                                "Basic realm=\"Repository Archiva Managed " + repoId + " Repository" );
221             }
222             else
223             {
224                 res.setHeader( "WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId );
225             }
226
227             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
228         }
229     }
230
231     /**
232      * Basic authentication.
233      *
234      * @param req
235      * @param repositoryId TODO
236      * @param groupId      TODO
237      * @param artifactId   TODO
238      * @return
239      */
240     private boolean isAllowed( HttpServletRequest req, String repositoryId, String groupId, String artifactId )
241         throws UserNotFoundException, AccountLockedException, AuthenticationException, MustChangePasswordException,
242         UnauthorizedException
243     {
244         String auth = req.getHeader( "Authorization" );
245         List<String> repoIds = new ArrayList<>();
246
247         if ( repositoryId != null )
248         {
249             repoIds.add( repositoryId );
250         }
251         else if ( artifactId != null && groupId != null )
252         {
253             if ( auth != null )
254             {
255                 if ( !auth.toUpperCase().startsWith( "BASIC " ) )
256                 {
257                     return false;
258                 }
259
260                 Decoder dec = new Base64();
261                 String usernamePassword = "";
262
263                 try
264                 {
265                     usernamePassword = new String( (byte[]) dec.decode( auth.substring( 6 ).getBytes() ) );
266                 }
267                 catch ( DecoderException ie )
268                 {
269                     log.warn( "Error decoding username and password: {}", ie.getMessage() );
270                 }
271
272                 if ( usernamePassword == null || usernamePassword.trim().equals( "" ) )
273                 {
274                     repoIds = getObservableRepos( UserManager.GUEST_USERNAME );
275                 }
276                 else
277                 {
278                     String[] userCredentials = usernamePassword.split( ":" );
279                     repoIds = getObservableRepos( userCredentials[0] );
280                 }
281             }
282             else
283             {
284                 repoIds = getObservableRepos( UserManager.GUEST_USERNAME );
285             }
286         }
287         else
288         {
289             return false;
290         }
291
292         for ( String repoId : repoIds )
293         {
294             try
295             {
296                 AuthenticationResult result = httpAuth.getAuthenticationResult( req, null );
297                 SecuritySession securitySession = httpAuth.getSecuritySession( req.getSession( true ) );
298
299                 if ( servletAuth.isAuthenticated( req, result ) && servletAuth.isAuthorized( req, securitySession,
300                                                                                              repoId,
301                                                                                              ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) )
302                 {
303                     return true;
304                 }
305             }
306             catch ( AuthorizationException e )
307             {
308
309             }
310             catch ( UnauthorizedException e )
311             {
312
313             }
314         }
315
316         throw new UnauthorizedException( "Access denied." );
317     }
318
319     private List<String> getObservableRepos( String principal )
320     {
321         try
322         {
323             return userRepositories.getObservableRepositoryIds( principal );
324         }
325         catch ( PrincipalNotFoundException e )
326         {
327             log.warn( e.getMessage(), e );
328         }
329         catch ( AccessDeniedException e )
330         {
331             log.warn( e.getMessage(), e );
332         }
333         catch ( ArchivaSecurityException e )
334         {
335             log.warn( e.getMessage(), e );
336         }
337
338         return Collections.emptyList();
339     }
340
341 }