]> source.dussan.org Git - archiva.git/blob
4a1afabda34ceaaea2df690b2792169c44f584ef
[archiva.git] /
1 package org.apache.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 com.sun.syndication.feed.synd.SyndFeed;
23 import com.sun.syndication.io.FeedException;
24 import com.sun.syndication.io.SyndFeedOutput;
25 import org.apache.archiva.metadata.repository.RepositorySession;
26 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
27 import org.apache.archiva.rss.processor.RssFeedProcessor;
28 import org.apache.commons.codec.Decoder;
29 import org.apache.commons.codec.DecoderException;
30 import org.apache.commons.codec.binary.Base64;
31 import org.apache.commons.lang.StringUtils;
32 import org.apache.archiva.security.AccessDeniedException;
33 import org.apache.archiva.security.ArchivaRoleConstants;
34 import org.apache.archiva.security.ArchivaSecurityException;
35 import org.apache.archiva.security.PrincipalNotFoundException;
36 import org.apache.archiva.security.ServletAuthenticator;
37 import org.apache.archiva.security.UserRepositories;
38 import org.codehaus.plexus.redback.authentication.AuthenticationException;
39 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
40 import org.codehaus.plexus.redback.authorization.AuthorizationException;
41 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
42 import org.codehaus.plexus.redback.policy.AccountLockedException;
43 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
44 import org.codehaus.plexus.redback.system.SecuritySession;
45 import org.codehaus.plexus.redback.users.UserManager;
46 import org.codehaus.plexus.redback.users.UserNotFoundException;
47 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.web.context.WebApplicationContext;
51 import org.springframework.web.context.support.WebApplicationContextUtils;
52
53 import javax.servlet.ServletException;
54 import javax.servlet.http.HttpServlet;
55 import javax.servlet.http.HttpServletRequest;
56 import javax.servlet.http.HttpServletResponse;
57 import java.io.IOException;
58 import java.util.ArrayList;
59 import java.util.Collections;
60 import java.util.HashMap;
61 import java.util.List;
62 import java.util.Map;
63
64 /**
65  * Servlet for handling rss feed requests.
66  */
67 public class RssFeedServlet
68     extends HttpServlet
69 {
70     public static final String MIME_TYPE = "application/rss+xml; charset=UTF-8";
71
72     private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
73
74     private static final String COULD_NOT_AUTHENTICATE_USER = "Could not authenticate user";
75
76     private static final String USER_NOT_AUTHORIZED = "User not authorized to access feed.";
77
78     private Logger log = LoggerFactory.getLogger( RssFeedServlet.class );
79
80     private RssFeedProcessor processor;
81
82     private WebApplicationContext wac;
83
84     private UserRepositories userRepositories;
85
86     private ServletAuthenticator servletAuth;
87
88     private HttpAuthenticator httpAuth;
89
90     private RepositorySessionFactory repositorySessionFactory;
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 = wac.getBean( UserRepositories.class );
98         servletAuth = wac.getBean( ServletAuthenticator.class );
99         httpAuth = wac.getBean( "httpAuthenticator#basic", HttpAuthenticator.class );
100         // TODO: what if there are other types?
101         repositorySessionFactory = wac.getBean( "repositorySessionFactory", RepositorySessionFactory.class );
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 = wac.getBean( "rssFeedProcessor#new-artifacts", RssFeedProcessor.class );
139                     map.put( RssFeedProcessor.KEY_REPO_ID, repoId );
140                 }
141                 else if ( ( groupId != null ) && ( artifactId != null ) )
142                 {
143                     // TODO: this only works for guest - we could pass in the list of repos
144                     // new versions of artifact feed request
145                     processor = wac.getBean( "rssFeedProcessor#new-versions", RssFeedProcessor.class );
146                     map.put( RssFeedProcessor.KEY_GROUP_ID, groupId );
147                     map.put( RssFeedProcessor.KEY_ARTIFACT_ID, artifactId );
148                 }
149             }
150             else
151             {
152                 res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
153                 return;
154             }
155
156             RepositorySession repositorySession = repositorySessionFactory.createSession();
157             try
158             {
159                 feed = processor.process( map, repositorySession.getRepository() );
160             }
161             finally
162             {
163                 repositorySession.close();
164             }
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 ( UserNotFoundException unfe )
186         {
187             log.debug( COULD_NOT_AUTHENTICATE_USER, unfe );
188             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
189         }
190         catch ( AccountLockedException acce )
191         {
192             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
193         }
194         catch ( AuthenticationException authe )
195         {
196             log.debug( COULD_NOT_AUTHENTICATE_USER, authe );
197             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
198         }
199         catch ( FeedException ex )
200         {
201             log.debug( COULD_NOT_GENERATE_FEED_ERROR, ex );
202             res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR );
203         }
204         catch ( MustChangePasswordException e )
205         {
206             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER );
207         }
208         catch ( UnauthorizedException e )
209         {
210             log.debug( e.getMessage() );
211             if ( repoId != null )
212             {
213                 res.setHeader( "WWW-Authenticate",
214                                "Basic realm=\"Repository Archiva Managed " + repoId + " Repository" );
215             }
216             else
217             {
218                 res.setHeader( "WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId );
219             }
220
221             res.sendError( HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED );
222         }
223     }
224
225     /**
226      * Basic authentication.
227      *
228      * @param req
229      * @param repositoryId TODO
230      * @param groupId      TODO
231      * @param artifactId   TODO
232      * @return
233      */
234     private boolean isAllowed( HttpServletRequest req, String repositoryId, String groupId, String artifactId )
235         throws UserNotFoundException, AccountLockedException, AuthenticationException, MustChangePasswordException,
236         UnauthorizedException
237     {
238         String auth = req.getHeader( "Authorization" );
239         List<String> repoIds = new ArrayList<String>();
240
241         if ( repositoryId != null )
242         {
243             repoIds.add( repositoryId );
244         }
245         else if ( artifactId != null && groupId != null )
246         {
247             if ( auth != null )
248             {
249                 if ( !auth.toUpperCase().startsWith( "BASIC " ) )
250                 {
251                     return false;
252                 }
253
254                 Decoder dec = new Base64();
255                 String usernamePassword = "";
256
257                 try
258                 {
259                     usernamePassword = new String( (byte[]) dec.decode( auth.substring( 6 ).getBytes() ) );
260                 }
261                 catch ( DecoderException ie )
262                 {
263                     log.warn( "Error decoding username and password.", ie.getMessage() );
264                 }
265
266                 if ( usernamePassword == null || usernamePassword.trim().equals( "" ) )
267                 {
268                     repoIds = getObservableRepos( UserManager.GUEST_USERNAME );
269                 }
270                 else
271                 {
272                     String[] userCredentials = usernamePassword.split( ":" );
273                     repoIds = getObservableRepos( userCredentials[0] );
274                 }
275             }
276             else
277             {
278                 repoIds = getObservableRepos( UserManager.GUEST_USERNAME );
279             }
280         }
281         else
282         {
283             return false;
284         }
285
286         for ( String repoId : repoIds )
287         {
288             try
289             {
290                 AuthenticationResult result = httpAuth.getAuthenticationResult( req, null );
291                 SecuritySession securitySession = httpAuth.getSecuritySession( req.getSession( true ) );
292
293                 if ( servletAuth.isAuthenticated( req, result ) && servletAuth.isAuthorized( req, securitySession,
294                                                                                              repoId,
295                                                                                              ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS ) )
296                 {
297                     return true;
298                 }
299             }
300             catch ( AuthorizationException e )
301             {
302
303             }
304             catch ( UnauthorizedException e )
305             {
306
307             }
308         }
309
310         throw new UnauthorizedException( "Access denied." );
311     }
312
313     private List<String> getObservableRepos( String principal )
314     {
315         try
316         {
317             return userRepositories.getObservableRepositoryIds( principal );
318         }
319         catch ( PrincipalNotFoundException e )
320         {
321             log.warn( e.getMessage(), e );
322         }
323         catch ( AccessDeniedException e )
324         {
325             log.warn( e.getMessage(), e );
326         }
327         catch ( ArchivaSecurityException e )
328         {
329             log.warn( e.getMessage(), e );
330         }
331
332         return Collections.emptyList();
333     }
334
335 }