]> source.dussan.org Git - archiva.git/blob
091489761024e374fd2346faa045bf2107de9cc1
[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.PrincipalNotFoundException;
43 import org.apache.maven.archiva.security.ServletAuthenticator;
44 import org.apache.maven.archiva.security.UserRepositories;
45 import org.codehaus.plexus.redback.authentication.AuthenticationException;
46 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
47 import org.codehaus.plexus.redback.authorization.AuthorizationException;
48 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
49 import org.codehaus.plexus.redback.policy.AccountLockedException;
50 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
51 import org.codehaus.plexus.redback.system.SecuritySession;
52 import org.codehaus.plexus.redback.users.UserManager;
53 import org.codehaus.plexus.redback.users.UserNotFoundException;
54 import org.codehaus.plexus.spring.PlexusToSpringUtils;
55 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.web.context.WebApplicationContext;
59 import org.springframework.web.context.support.WebApplicationContextUtils;
60
61 import com.sun.syndication.feed.synd.SyndFeed;
62 import com.sun.syndication.io.FeedException;
63 import com.sun.syndication.io.SyndFeedOutput;
64
65 /**
66  * Servlet for handling rss feed requests.
67  * 
68  * @version
69  */
70 public class RssFeedServlet
71     extends HttpServlet
72 {
73     public static final String MIME_TYPE = "application/rss+xml; charset=UTF-8";
74
75     private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
76
77     private static final String COULD_NOT_AUTHENTICATE_USER = "Could not authenticate user";
78
79     private static final String USER_NOT_AUTHORIZED = "User not authorized to access feed.";
80
81     private Logger log = LoggerFactory.getLogger( RssFeedServlet.class );
82
83     private RssFeedProcessor processor;
84
85     private WebApplicationContext wac;
86
87     private UserRepositories userRepositories;
88
89     private ServletAuthenticator servletAuth;
90
91     private HttpAuthenticator httpAuth;
92     
93     public void init( javax.servlet.ServletConfig servletConfig )
94         throws ServletException
95     {
96         super.init( servletConfig );
97         wac = WebApplicationContextUtils.getRequiredWebApplicationContext( servletConfig.getServletContext() );
98         userRepositories =
99             (UserRepositories) wac.getBean( PlexusToSpringUtils.buildSpringId( UserRepositories.class.getName() ) );
100         servletAuth =
101             (ServletAuthenticator) wac.getBean( PlexusToSpringUtils.buildSpringId( ServletAuthenticator.class.getName() ) );
102         httpAuth =
103             (HttpAuthenticator) wac.getBean( PlexusToSpringUtils.buildSpringId( HttpAuthenticator.ROLE, "basic" ) );
104     }
105
106     public void doGet( HttpServletRequest req, HttpServletResponse res )
107         throws ServletException, IOException
108     {
109         String repoId = null;
110         String groupId = null;
111         String artifactId = null;
112         
113         String url = StringUtils.removeEnd( req.getRequestURL().toString(), "/" );          
114         if( StringUtils.countMatches( StringUtils.substringAfter( url, "feeds/" ), "/" ) > 0 )
115         {
116             artifactId = StringUtils.substringAfterLast( url, "/" );
117             groupId = StringUtils.substringBeforeLast( StringUtils.substringAfter( url, "feeds/" ), "/");
118             groupId = StringUtils.replaceChars( groupId, '/', '.' );
119         }
120         else if( StringUtils.countMatches( StringUtils.substringAfter( url, "feeds/" ), "/" ) == 0 )
121         {
122             repoId = StringUtils.substringAfterLast( url, "/" );
123         }
124         else
125         {
126             res.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid request url." );
127             return;
128         }        
129         
130         try
131         {
132             Map<String, String> map = new HashMap<String, String>();
133             SyndFeed feed = null;
134             
135             if ( isAllowed( req, repoId, groupId, artifactId ) )
136             {
137                 if ( repoId != null )
138                 {
139                     // new artifacts in repo feed request
140                     processor =
141                         (RssFeedProcessor) wac.getBean( PlexusToSpringUtils.buildSpringId(
142                                                                                            RssFeedProcessor.class.getName(),
143                                                                                            "new-artifacts" ) );
144                     map.put( RssFeedProcessor.KEY_REPO_ID, repoId );
145                 }
146                 else if ( ( groupId != null ) && ( artifactId != null ) )
147                 {
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 ( ArchivaDatabaseException e )
185         {
186             log.debug( COULD_NOT_GENERATE_FEED_ERROR, e );
187             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
188         }
189         catch ( UserNotFoundException unfe )
190         {
191             log.debug( COULD_NOT_AUTHENTICATE_USER, unfe );
192             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
193         }
194         catch ( AccountLockedException acce )
195         {            
196             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
197         }
198         catch ( AuthenticationException authe )
199         {   
200             log.debug( COULD_NOT_AUTHENTICATE_USER, authe );
201             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
202         }
203         catch ( FeedException ex )
204         {
205             log.debug( COULD_NOT_GENERATE_FEED_ERROR, ex );
206             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
207         }
208         catch ( MustChangePasswordException e )
209         {            
210             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
211         }
212         catch ( UnauthorizedException e )
213         {
214             log.debug( e.getMessage() );
215             if ( repoId != null )
216             {
217                 res.setHeader("WWW-Authenticate", "Basic realm=\"Repository Archiva Managed " + repoId + " Repository" );
218             }
219             else
220             {
221                 res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId );
222             }
223             
224             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
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, false ) )
298                 {
299                     return true;
300                 }
301             }
302             catch ( AuthorizationException e )
303             {
304                 
305             }
306             catch ( UnauthorizedException e )
307             {
308              
309             }
310         }
311
312         throw new UnauthorizedException( "Access denied." );
313     }
314
315     private List<String> getObservableRepos( String principal )
316     {
317         try
318         {
319             return userRepositories.getObservableRepositoryIds( principal );
320         }
321         catch ( PrincipalNotFoundException e )
322         {
323             log.warn( e.getMessage(), e );
324         }
325         catch ( AccessDeniedException e )
326         {
327             log.warn( e.getMessage(), e );
328         }
329         catch ( ArchivaSecurityException e )
330         {
331             log.warn( e.getMessage(), e );
332         }
333
334         return Collections.emptyList();
335     }
336
337 }