]> source.dussan.org Git - archiva.git/blob
7e16bea22fe485ce26e4843355f73b686715526e
[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
29 import javax.servlet.ServletException;
30 import javax.servlet.http.HttpServlet;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33
34 import org.apache.archiva.rss.processor.RssFeedProcessor;
35 import org.apache.commons.codec.Decoder;
36 import org.apache.commons.codec.DecoderException;
37 import org.apache.commons.codec.binary.Base64;
38 import org.apache.commons.lang.StringUtils;
39 import org.apache.maven.archiva.database.ArchivaDatabaseException;
40 import org.apache.maven.archiva.security.AccessDeniedException;
41 import org.apache.maven.archiva.security.ArchivaSecurityException;
42 import org.apache.maven.archiva.security.ArchivaXworkUser;
43 import org.apache.maven.archiva.security.PrincipalNotFoundException;
44 import org.apache.maven.archiva.security.ServletAuthenticator;
45 import org.apache.maven.archiva.security.UserRepositories;
46 import org.codehaus.plexus.redback.authentication.AuthenticationException;
47 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
48 import org.codehaus.plexus.redback.authorization.AuthorizationException;
49 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
50 import org.codehaus.plexus.redback.policy.AccountLockedException;
51 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
52 import org.codehaus.plexus.redback.system.SecuritySession;
53 import org.codehaus.plexus.redback.users.UserManager;
54 import org.codehaus.plexus.redback.users.UserNotFoundException;
55 import org.codehaus.plexus.spring.PlexusToSpringUtils;
56 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.springframework.web.context.WebApplicationContext;
60 import org.springframework.web.context.support.WebApplicationContextUtils;
61
62 import com.sun.syndication.feed.synd.SyndFeed;
63 import com.sun.syndication.io.FeedException;
64 import com.sun.syndication.io.SyndFeedOutput;
65
66 /**
67  * Servlet for handling rss feed requests.
68  * 
69  * @version
70  */
71 public class RssFeedServlet
72     extends HttpServlet
73 {
74     public static final String MIME_TYPE = "application/rss+xml; charset=UTF-8";
75
76     private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
77
78     private static final String COULD_NOT_AUTHENTICATE_USER = "Could not authenticate user";
79
80     private static final String USER_NOT_AUTHORIZED = "User not authorized to access feed.";
81
82     private Logger log = LoggerFactory.getLogger( RssFeedServlet.class );
83
84     private RssFeedProcessor processor;
85
86     private WebApplicationContext wac;
87
88     private UserRepositories userRepositories;
89
90     private ServletAuthenticator servletAuth;
91
92     private HttpAuthenticator httpAuth;
93     
94     private ArchivaXworkUser archivaXworkUser;
95
96     public void init( javax.servlet.ServletConfig servletConfig )
97         throws ServletException
98     {
99         super.init( servletConfig );
100         wac = WebApplicationContextUtils.getRequiredWebApplicationContext( servletConfig.getServletContext() );
101         userRepositories =
102             (UserRepositories) wac.getBean( PlexusToSpringUtils.buildSpringId( UserRepositories.class.getName() ) );
103         servletAuth =
104             (ServletAuthenticator) wac.getBean( PlexusToSpringUtils.buildSpringId( ServletAuthenticator.class.getName() ) );
105         httpAuth =
106             (HttpAuthenticator) wac.getBean( PlexusToSpringUtils.buildSpringId( HttpAuthenticator.ROLE, "basic" ) );
107         archivaXworkUser = (ArchivaXworkUser) wac.getBean( PlexusToSpringUtils.buildSpringId( ArchivaXworkUser.class ) );
108     }
109
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<String, String>();
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 =
145                         (RssFeedProcessor) wac.getBean( PlexusToSpringUtils.buildSpringId(
146                                                                                            RssFeedProcessor.class.getName(),
147                                                                                            "new-artifacts" ) );
148                     map.put( RssFeedProcessor.KEY_REPO_ID, repoId );
149                 }
150                 else if ( ( groupId != null ) && ( artifactId != null ) )
151                 {
152                     // new versions of artifact feed request
153                     processor =
154                         (RssFeedProcessor) wac.getBean( PlexusToSpringUtils.buildSpringId(
155                                                                                            RssFeedProcessor.class.getName(),
156                                                                                            "new-versions" ) );
157                     map.put( RssFeedProcessor.KEY_GROUP_ID, groupId );
158                     map.put( RssFeedProcessor.KEY_ARTIFACT_ID, artifactId );
159                 }
160             }
161             else
162             {
163                 res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
164                 return;
165             }
166
167             feed = processor.process( map );            
168             if( feed == null )
169             {
170                 res.sendError( HttpServletResponse.SC_NO_CONTENT, "No information available." );
171                 return;
172             }
173             
174             res.setContentType( MIME_TYPE );
175                         
176             if ( repoId != null )
177             {   
178                 feed.setLink( req.getRequestURL().toString() );
179             }
180             else if ( ( groupId != null ) && ( artifactId != null ) )
181             {
182                 feed.setLink( req.getRequestURL().toString() );                
183             }
184
185             SyndFeedOutput output = new SyndFeedOutput();
186             output.output( feed, res.getWriter() );
187         }
188         catch ( ArchivaDatabaseException e )
189         {
190             log.debug( COULD_NOT_GENERATE_FEED_ERROR, e );
191             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
192         }
193         catch ( UserNotFoundException unfe )
194         {
195             log.debug( COULD_NOT_AUTHENTICATE_USER, unfe );
196             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
197         }
198         catch ( AccountLockedException acce )
199         {            
200             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
201         }
202         catch ( AuthenticationException authe )
203         {   
204             log.debug( COULD_NOT_AUTHENTICATE_USER, authe );
205             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
206         }
207         catch ( FeedException ex )
208         {
209             log.debug( COULD_NOT_GENERATE_FEED_ERROR, ex );
210             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
211         }
212         catch ( MustChangePasswordException e )
213         {            
214             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
215         }
216         catch ( UnauthorizedException e )
217         {
218             log.debug( e.getMessage() );
219             if ( repoId != null )
220             {
221                 res.setHeader("WWW-Authenticate", "Basic realm=\"Repository Archiva Managed " + repoId + " Repository" );
222             }
223             else
224             {
225                 res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId );
226             }
227             
228             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
229         }
230     }
231
232     /**
233      * Basic authentication.
234      * 
235      * @param req
236      * @param repositoryId TODO
237      * @param groupId TODO
238      * @param artifactId TODO
239      * @return
240      */
241     private boolean isAllowed( HttpServletRequest req, String repositoryId, String groupId, String artifactId )
242         throws UserNotFoundException, AccountLockedException, AuthenticationException, MustChangePasswordException,
243         UnauthorizedException
244     {
245         String auth = req.getHeader( "Authorization" );
246         List<String> repoIds = new ArrayList<String>();
247
248         if ( repositoryId != null )
249         {
250             repoIds.add( repositoryId );
251         }
252         else if ( artifactId != null && groupId != null )
253         {
254             if ( auth != null )
255             {
256                 if ( !auth.toUpperCase().startsWith( "BASIC " ) )
257                 {
258                     return false;
259                 }
260
261                 Decoder dec = new Base64();
262                 String usernamePassword = "";
263
264                 try
265                 {
266                     usernamePassword = new String( (byte[]) dec.decode( auth.substring( 6 ).getBytes() ) );
267                 }
268                 catch ( DecoderException ie )
269                 {
270                     log.warn( "Error decoding username and password.", ie.getMessage() );
271                 }
272
273                 if ( usernamePassword == null || usernamePassword.trim().equals( "" ) )
274                 {
275                     repoIds = getObservableRepos( UserManager.GUEST_USERNAME );
276                 }
277                 else
278                 {
279                     String[] userCredentials = usernamePassword.split( ":" );
280                     repoIds = getObservableRepos( userCredentials[0] );
281                 }
282             }
283             else
284             {
285                 repoIds = getObservableRepos( UserManager.GUEST_USERNAME );
286             }
287         }
288         else
289         {
290             return false;
291         }
292
293         for ( String repoId : repoIds )
294         {
295             try
296             {
297                 AuthenticationResult result = httpAuth.getAuthenticationResult( req, null );
298                 SecuritySession securitySession = httpAuth.getSecuritySession( req.getSession( true ) );
299
300                 if ( servletAuth.isAuthenticated( req, result ) &&
301                     servletAuth.isAuthorized( req, securitySession, repoId, false ) )
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 }