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