KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lenya > ac > impl > DefaultAccessController


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy of
6  * the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations under
14  * the License.
15  *
16  */

17
18 package org.apache.lenya.ac.impl;
19
20 import java.util.ArrayList JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.List JavaDoc;
23 import java.util.Map JavaDoc;
24 import java.util.regex.*;
25
26 import org.apache.avalon.framework.activity.Disposable;
27 import org.apache.avalon.framework.component.Component;
28 import org.apache.avalon.framework.configuration.Configurable;
29 import org.apache.avalon.framework.configuration.Configuration;
30 import org.apache.avalon.framework.configuration.ConfigurationException;
31 import org.apache.avalon.framework.logger.AbstractLogEnabled;
32 import org.apache.avalon.framework.parameters.ParameterException;
33 import org.apache.avalon.framework.parameters.Parameterizable;
34 import org.apache.avalon.framework.parameters.Parameters;
35 import org.apache.avalon.framework.service.ServiceException;
36 import org.apache.avalon.framework.service.ServiceManager;
37 import org.apache.avalon.framework.service.ServiceSelector;
38 import org.apache.avalon.framework.service.Serviceable;
39 import org.apache.cocoon.environment.Request;
40 import org.apache.cocoon.environment.Session;
41 import org.apache.lenya.ac.AccessControlException;
42 import org.apache.lenya.ac.AccessController;
43 import org.apache.lenya.ac.Accreditable;
44 import org.apache.lenya.ac.AccreditableManager;
45 import org.apache.lenya.ac.Authenticator;
46 import org.apache.lenya.ac.Authorizer;
47 import org.apache.lenya.ac.IPRange;
48 import org.apache.lenya.ac.Identity;
49 import org.apache.lenya.ac.Item;
50 import org.apache.lenya.ac.ItemManagerListener;
51 import org.apache.lenya.ac.Machine;
52 import org.apache.lenya.ac.PolicyManager;
53
54 /**
55  * Default access controller implementation.
56  * @version $Id: DefaultAccessController.java 43241 2004-08-16 16:36:57Z andreas $
57  */

58 public class DefaultAccessController extends AbstractLogEnabled implements AccessController,
59         Configurable, Serviceable, Disposable, ItemManagerListener {
60
61     protected static final String JavaDoc AUTHORIZER_ELEMENT = "authorizer";
62     protected static final String JavaDoc TYPE_ATTRIBUTE = "type";
63     protected static final String JavaDoc ACCREDITABLE_MANAGER_ELEMENT = "accreditable-manager";
64     protected static final String JavaDoc POLICY_MANAGER_ELEMENT = "policy-manager";
65
66     private static final String JavaDoc REGEX = "([0-9]{1,3}\\.){3}[0-9]{1,3}";
67     private ServiceSelector accreditableManagerSelector;
68     private AccreditableManager accreditableManager;
69     private ServiceSelector authorizerSelector;
70     private Map JavaDoc authorizers = new HashMap JavaDoc();
71     private List JavaDoc authorizerKeys = new ArrayList JavaDoc();
72     private ServiceSelector policyManagerSelector;
73     private PolicyManager policyManager;
74     private Authenticator authenticator;
75
76     /**
77      * @see org.apache.lenya.ac.AccessController#authenticate(org.apache.cocoon.environment.Request)
78      */

79     public boolean authenticate(Request request) throws AccessControlException {
80
81         assert request != null;
82         boolean authenticated = getAuthenticator().authenticate(getAccreditableManager(), request);
83
84         return authenticated;
85     }
86
87     /**
88      * @see org.apache.lenya.ac.AccessController#authorize(org.apache.cocoon.environment.Request)
89      */

90     public boolean authorize(Request request) throws AccessControlException {
91
92         assert request != null;
93
94         boolean authorized = false;
95
96         getLogger().debug("=========================================================");
97         getLogger().debug("Beginning authorization.");
98
99         if (hasAuthorizers()) {
100             Authorizer[] authorizers = getAuthorizers();
101             int i = 0;
102             authorized = true;
103
104             while ((i < authorizers.length) && authorized) {
105
106                 if (getLogger().isDebugEnabled()) {
107                     getLogger().debug("---------------------------------------------------------");
108                     getLogger().debug("Invoking authorizer [" + authorizers[i] + "]");
109                 }
110
111                 if (authorizers[i] instanceof PolicyAuthorizer) {
112                     PolicyAuthorizer authorizer = (PolicyAuthorizer) authorizers[i];
113                     authorizer.setAccreditableManager(accreditableManager);
114                     authorizer.setPolicyManager(policyManager);
115                 }
116
117                 authorized = authorized && authorizers[i].authorize(request);
118
119                 if (getLogger().isDebugEnabled()) {
120                     getLogger().debug(
121                             "Authorizer [" + authorizers[i] + "] returned [" + authorized + "]");
122                 }
123
124                 i++;
125             }
126         }
127
128         if (getLogger().isDebugEnabled()) {
129             getLogger().debug("=========================================================");
130             getLogger().debug("Authorization complete, result: [" + authorized + "]");
131             getLogger().debug("=========================================================");
132         }
133
134         return authorized;
135     }
136
137     /**
138      * @see org.apache.avalon.framework.configuration.Configurable#configure(org.apache.avalon.framework.configuration.Configuration)
139      */

140     public void configure(Configuration conf) throws ConfigurationException {
141
142         try {
143             setupAccreditableManager(conf);
144             setupAuthorizers(conf);
145             setupPolicyManager(conf);
146             setupAuthenticator();
147         } catch (ConfigurationException e) {
148             throw e;
149         } catch (Exception JavaDoc e) {
150             throw new ConfigurationException("Configuration failed: ", e);
151         }
152     }
153
154     /**
155      * Configures or parameterizes a component, depending on the implementation
156      * as Configurable or Parameterizable.
157      * @param component The component.
158      * @param configuration The configuration to use.
159      * @throws ConfigurationException when an error occurs during configuration.
160      * @throws ParameterException when an error occurs during parameterization.
161      */

162     public static void configureOrParameterize(Component component, Configuration configuration)
163             throws ConfigurationException, ParameterException {
164         if (component instanceof Configurable) {
165             ((Configurable) component).configure(configuration);
166         }
167         if (component instanceof Parameterizable) {
168             Parameters parameters = Parameters.fromConfiguration(configuration);
169             ((Parameterizable) component).parameterize(parameters);
170         }
171     }
172
173     /**
174      * Creates the accreditable manager.
175      *
176      * @param configuration The access controller configuration.
177      * @throws ConfigurationException when the configuration failed.
178      * @throws ServiceException when something went wrong.
179      * @throws ParameterException when something went wrong.
180      */

181     protected void setupAccreditableManager(Configuration configuration)
182             throws ConfigurationException, ServiceException, ParameterException {
183
184         Configuration accreditableManagerConfiguration = configuration.getChild(
185                 ACCREDITABLE_MANAGER_ELEMENT, false);
186         if (accreditableManagerConfiguration != null) {
187             String JavaDoc accreditableManagerType = accreditableManagerConfiguration
188                     .getAttribute(TYPE_ATTRIBUTE);
189             if (getLogger().isDebugEnabled()) {
190                 getLogger().debug("AccreditableManager type: [" + accreditableManagerType + "]");
191             }
192
193             accreditableManagerSelector = (ServiceSelector) manager.lookup(AccreditableManager.ROLE
194                     + "Selector");
195             accreditableManager = (AccreditableManager) accreditableManagerSelector
196                     .select(accreditableManagerType);
197             accreditableManager.addItemManagerListener(this);
198             configureOrParameterize(accreditableManager, accreditableManagerConfiguration);
199         }
200     }
201
202     /**
203      * Creates the authorizers.
204      *
205      * @param configuration The access controller configuration.
206      * @throws ConfigurationException when the configuration failed.
207      * @throws ServiceException when something went wrong.
208      * @throws ParameterException when something went wrong.
209      */

210     protected void setupAuthorizers(Configuration configuration) throws ServiceException,
211             ConfigurationException, ParameterException {
212         Configuration[] authorizerConfigurations = configuration.getChildren(AUTHORIZER_ELEMENT);
213         if (authorizerConfigurations.length > 0) {
214             authorizerSelector = (ServiceSelector) manager.lookup(Authorizer.ROLE + "Selector");
215
216             for (int i = 0; i < authorizerConfigurations.length; i++) {
217                 String JavaDoc type = authorizerConfigurations[i].getAttribute(TYPE_ATTRIBUTE);
218                 if (getLogger().isDebugEnabled()) {
219                     getLogger().debug("Adding authorizer [" + type + "]");
220                 }
221
222                 Authorizer authorizer = (Authorizer) authorizerSelector.select(type);
223                 authorizerKeys.add(type);
224                 authorizers.put(type, authorizer);
225                 configureOrParameterize(authorizer, authorizerConfigurations[i]);
226             }
227         }
228     }
229
230     /**
231      * Creates the policy manager.
232      *
233      * @param configuration The access controller configuration.
234      * @throws ConfigurationException when the configuration failed.
235      * @throws ServiceException when something went wrong.
236      * @throws ParameterException when something went wrong.
237      */

238     protected void setupPolicyManager(Configuration configuration) throws ServiceException,
239             ConfigurationException, ParameterException {
240         Configuration policyManagerConfiguration = configuration.getChild(POLICY_MANAGER_ELEMENT,
241                 false);
242         if (policyManagerConfiguration != null) {
243             String JavaDoc policyManagerType = policyManagerConfiguration.getAttribute(TYPE_ATTRIBUTE);
244             if (getLogger().isDebugEnabled()) {
245                 getLogger().debug("Adding policy manager type: [" + policyManagerType + "]");
246             }
247             policyManagerSelector = (ServiceSelector) manager.lookup(PolicyManager.ROLE
248                     + "Selector");
249             policyManager = (PolicyManager) policyManagerSelector.select(policyManagerType);
250             configureOrParameterize(policyManager, policyManagerConfiguration);
251         }
252     }
253
254     /**
255      * Sets up the authenticator.
256      *
257      * @throws ServiceException when something went wrong.
258      */

259     protected void setupAuthenticator() throws ServiceException {
260         authenticator = (Authenticator) manager.lookup(Authenticator.ROLE);
261     }
262
263     private ServiceManager manager;
264
265     /**
266      * Set the global component manager.
267      *
268      * @param manager The global component manager
269      * @throws ServiceException when something went wrong.
270      */

271     public void service(ServiceManager manager) throws ServiceException {
272         this.manager = manager;
273     }
274
275     /**
276      * Returns the service manager.
277      *
278      * @return A service manager.
279      */

280     protected ServiceManager getManager() {
281         return manager;
282     }
283
284     /**
285      * Returns the authorizers of this action.
286      *
287      * @return An array of authorizers.
288      */

289     public Authorizer[] getAuthorizers() {
290
291         Authorizer[] authorizerArray = new Authorizer[authorizers.size()];
292         for (int i = 0; i < authorizers.size(); i++) {
293             String JavaDoc key = (String JavaDoc) authorizerKeys.get(i);
294             authorizerArray[i] = (Authorizer) authorizers.get(key);
295         }
296
297         return authorizerArray;
298     }
299
300     /**
301      * Returns if this action has authorizers.
302      *
303      * @return A boolean value.
304      */

305     protected boolean hasAuthorizers() {
306         return !authorizers.isEmpty();
307     }
308
309     /**
310      * @see org.apache.avalon.framework.activity.Disposable#dispose()
311      */

312     public void dispose() {
313
314         if (accreditableManagerSelector != null) {
315             if (accreditableManager != null) {
316                 accreditableManager.removeItemManagerListener(this);
317                 accreditableManagerSelector.release(accreditableManager);
318             }
319             getManager().release(accreditableManagerSelector);
320         }
321
322         if (policyManagerSelector != null) {
323             if (policyManager != null) {
324                 policyManagerSelector.release(policyManager);
325             }
326             getManager().release(policyManagerSelector);
327         }
328
329         if (authorizerSelector != null) {
330             Authorizer[] authorizers = getAuthorizers();
331             for (int i = 0; i < authorizers.length; i++) {
332                 authorizerSelector.release(authorizers[i]);
333             }
334             getManager().release(authorizerSelector);
335         }
336
337         if (authenticator != null) {
338             getManager().release(authenticator);
339         }
340
341         if (getLogger().isDebugEnabled()) {
342             getLogger().debug("Disposing [" + this + "]");
343         }
344     }
345
346     /**
347      * Returns the accreditable manager.
348      *
349      * @return An accreditable manager.
350      */

351     public AccreditableManager getAccreditableManager() {
352         return accreditableManager;
353     }
354
355     /**
356      * Returns the policy manager.
357      *
358      * @return A policy manager.
359      */

360     public PolicyManager getPolicyManager() {
361         return policyManager;
362     }
363
364     /**
365      * Returns the authenticator.
366      *
367      * @return The authenticator.
368      */

369     public Authenticator getAuthenticator() {
370         return authenticator;
371     }
372
373     /**
374      * Checks if this identity was initialized by this access controller.
375      *
376      * @param identity An identity.
377      * @return A boolean value.
378      * @throws AccessControlException when something went wrong.
379      */

380     public boolean ownsIdenity(Identity identity) throws AccessControlException {
381         return identity.belongsTo(getAccreditableManager());
382     }
383
384     /**
385      * @see org.apache.lenya.ac.AccessController#setupIdentity(org.apache.cocoon.environment.Request)
386      */

387     public void setupIdentity(Request request) throws AccessControlException {
388         Session session = request.getSession(true);
389         if (!hasValidIdentity(session)) {
390             Identity identity = new Identity();
391             String JavaDoc remoteAddress = request.getRemoteAddr();
392             String JavaDoc clientAddress = request.getHeader("x-forwarded-for");
393
394             if (clientAddress != null) {
395                 Pattern p = Pattern.compile(REGEX);
396                 Matcher m = p.matcher(clientAddress);
397
398                 if (m.find()) {
399                     remoteAddress = m.group();
400                 }
401             }
402
403             getLogger().info("Remote Address to use: [" + remoteAddress + "]");
404
405             Machine machine = new Machine(remoteAddress);
406             IPRange[] ranges = accreditableManager.getIPRangeManager().getIPRanges();
407             for (int i = 0; i < ranges.length; i++) {
408                 if (ranges[i].contains(machine)) {
409                     machine.addIPRange(ranges[i]);
410                 }
411             }
412
413             identity.addIdentifiable(machine);
414             session.setAttribute(Identity.class.getName(), identity);
415         }
416     }
417
418     /**
419      * Checks if the session contains an identity that is not null and belongs
420      * to the used access controller.
421      *
422      * @param session The current session.
423      * @return A boolean value.
424      * @throws AccessControlException when something went wrong.
425      */

426     protected boolean hasValidIdentity(Session session) throws AccessControlException {
427         boolean valid = true;
428         Identity identity = (Identity) session.getAttribute(Identity.class.getName());
429         if (identity == null || !ownsIdenity(identity)) {
430             valid = false;
431         }
432         return valid;
433     }
434
435     /**
436      * @see org.apache.lenya.ac.ItemManagerListener#itemAdded(org.apache.lenya.ac.Item)
437      */

438     public void itemAdded(Item item) throws AccessControlException {
439         if (getLogger().isDebugEnabled()) {
440             getLogger().debug("Item was added: [" + item + "]");
441             getLogger().debug("Notifying policy manager");
442         }
443         if (item instanceof Accreditable) {
444             getPolicyManager().accreditableAdded(getAccreditableManager(), (Accreditable) item);
445         }
446     }
447
448     /**
449      * @see org.apache.lenya.ac.ItemManagerListener#itemRemoved(org.apache.lenya.ac.Item)
450      */

451     public void itemRemoved(Item item) throws AccessControlException {
452         if (getLogger().isDebugEnabled()) {
453             getLogger().debug("Item was removed: [" + item + "]");
454             getLogger().debug("Notifying policy manager");
455         }
456         getPolicyManager().accreditableRemoved(getAccreditableManager(), (Accreditable) item);
457     }
458
459 }
Popular Tags