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