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