Improved Name Mapper tests.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / hs / provider / SharedMemoryShibHandle.java
1 /*
2  * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation
3  * for Advanced Internet Development, Inc. All rights reserved
4  * 
5  * 
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  * 
9  * Redistributions of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  * 
12  * Redistributions in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution, if any, must include
15  * the following acknowledgment: "This product includes software developed by
16  * the University Corporation for Advanced Internet Development
17  * <http://www.ucaid.edu> Internet2 Project. Alternately, this acknowledegement
18  * may appear in the software itself, if and wherever such third-party
19  * acknowledgments normally appear.
20  * 
21  * Neither the name of Shibboleth nor the names of its contributors, nor
22  * Internet2, nor the University Corporation for Advanced Internet Development,
23  * Inc., nor UCAID may be used to endorse or promote products derived from this
24  * software without specific prior written permission. For written permission,
25  * please contact shibboleth@shibboleth.org
26  * 
27  * Products derived from this software may not be called Shibboleth, Internet2,
28  * UCAID, or the University Corporation for Advanced Internet Development, nor
29  * may Shibboleth appear in their name, without prior written permission of the
30  * University Corporation for Advanced Internet Development.
31  * 
32  * 
33  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
34  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
35  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
36  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
37  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
38  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
39  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY
40  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
41  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
45  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46  */
47 package edu.internet2.middleware.shibboleth.hs.provider;
48
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.Iterator;
52 import java.util.Map;
53 import java.util.Set;
54 import java.util.Map.Entry;
55
56 import org.apache.log4j.Logger;
57 import org.doomdark.uuid.UUIDGenerator;
58 import org.opensaml.SAMLException;
59 import org.opensaml.SAMLNameIdentifier;
60 import org.w3c.dom.Element;
61
62 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
63 import edu.internet2.middleware.shibboleth.common.IdentityProvider;
64 import edu.internet2.middleware.shibboleth.common.InvalidNameIdentifierException;
65 import edu.internet2.middleware.shibboleth.common.NameIdentifierMappingException;
66 import edu.internet2.middleware.shibboleth.common.ServiceProvider;
67 import edu.internet2.middleware.shibboleth.hs.HSNameIdentifierMapping;
68
69 /**
70  * @author Walter Hoehn
71  */
72 public class SharedMemoryShibHandle extends AQHNameIdentifierMapping implements HSNameIdentifierMapping {
73
74         protected HandleCache cache = HandleCache.instance();
75         private static Logger log = Logger.getLogger(SharedMemoryShibHandle.class.getName());
76
77         public SharedMemoryShibHandle(Element config) throws NameIdentifierMappingException {
78                 super(config);
79         }
80
81         public SAMLNameIdentifier getNameIdentifierName(
82                 AuthNPrincipal principal,
83                 ServiceProvider sProv,
84                 IdentityProvider idProv)
85                 throws NameIdentifierMappingException {
86
87                 if (principal == null) {
88                         log.error("A principal must be supplied for Attribute Query Handle creation.");
89                         throw new IllegalArgumentException("A principal must be supplied for Attribute Query Handle creation.");
90                 }
91
92                 String handle = UUIDGenerator.getInstance().generateRandomBasedUUID().toString();
93                 log.debug("Assigning handle (" + handle + ") to principal (" + principal.getName() + ").");
94                 synchronized (cache.handleEntries) {
95                         cache.handleEntries.put(handle, createHandleEntry(principal));
96                 }
97
98                 try {
99                         return new SAMLNameIdentifier(handle, idProv.getId(), getNameIdentifierFormat().toString());
100                 } catch (SAMLException e) {
101                         throw new NameIdentifierMappingException("Unable to generate Attribute Query Handle: " + e);
102                 }
103
104         }
105
106         public AuthNPrincipal getPrincipal(SAMLNameIdentifier nameId, ServiceProvider sProv, IdentityProvider idProv)
107                 throws NameIdentifierMappingException, InvalidNameIdentifierException {
108
109                 synchronized (cache.handleEntries) {
110                         if (!cache.handleEntries.containsKey(nameId.getName())) {
111                                 log.debug("The Name Mapping Cache does not contain an entry for this Attribute Query Handle.");
112                                 throw new InvalidNameIdentifierException("The Name Mapping Cache does not contain an entry for this Attribute Query Handle.");
113                         }
114                 }
115
116                 HandleEntry handleEntry;
117                 synchronized (cache.handleEntries) {
118                         handleEntry = (HandleEntry) cache.handleEntries.get(nameId.getName());
119                 }
120
121                 if (handleEntry.isExpired()) {
122                         log.debug("Attribute Query Handle is expired.");
123                         synchronized (cache.handleEntries) {
124                                 cache.handleEntries.remove(nameId.getName());
125                         }
126                         throw new InvalidNameIdentifierException("Attribute Query Handle is expired.");
127                 } else {
128                         log.debug("Attribute Query Handle recognized.");
129                         return handleEntry.principal;
130                 }
131         }
132
133 }
134
135 class HandleCache {
136
137         protected Map handleEntries = new HashMap();
138         private static HandleCache instance;
139         protected MemoryRepositoryCleaner cleaner = new MemoryRepositoryCleaner();
140         private static Logger log = Logger.getLogger(HandleCache.class.getName());
141
142         protected HandleCache() {
143         }
144
145         public static synchronized HandleCache instance() {
146                 if (instance == null) {
147                         instance = new HandleCache();
148                         return instance;
149                 }
150                 return instance;
151         }
152         /**
153          * @see java.lang.Object#finalize()
154          */
155         protected void finalize() throws Throwable {
156                 super.finalize();
157                 synchronized (cleaner) {
158                         cleaner.shutdown = true;
159                         cleaner.interrupt();
160                 }
161         }
162
163         private class MemoryRepositoryCleaner extends Thread {
164
165                 private boolean shutdown = false;
166
167                 public MemoryRepositoryCleaner() {
168                         super();
169                         log.debug("Starting memory-based shib handle cache cleanup thread.");
170                         start();
171                 }
172
173                 public void run() {
174                         try {
175                                 sleep(1 * 60 * 1000);
176                         } catch (InterruptedException e) {
177                                 log.debug("Memory-based shib handle cache cleanup interrupted.");
178                         }
179                         while (true) {
180                                 try {
181                                         if (shutdown) {
182                                                 log.debug("Stopping Memory-based shib handle cache cleanup thread.");
183                                                 return;
184                                         }
185                                         Set needsDeleting = new HashSet();
186                                         synchronized (handleEntries) {
187                                                 Iterator iterator = handleEntries.entrySet().iterator();
188                                                 while (iterator.hasNext()) {
189                                                         Entry entry = (Entry) iterator.next();
190                                                         HandleEntry handleEntry = (HandleEntry) entry.getValue();
191                                                         if (handleEntry.isExpired()) {
192                                                                 needsDeleting.add(entry.getKey());
193                                                         }
194                                                 }
195                                                 //release the lock to be friendly
196                                                 Iterator deleteIterator = needsDeleting.iterator();
197                                                 while (deleteIterator.hasNext()) {
198                                                         synchronized (handleEntries) {
199                                                                 log.debug("Expiring an Attribute Query Handle from the memory cache.");
200                                                                 handleEntries.remove(deleteIterator.next());
201                                                         }
202                                                 }
203                                         }
204                                         sleep(1 * 60 * 1000);
205                                 } catch (InterruptedException e) {
206                                         log.debug("Memory-based shib handle cache cleanup interrupted.");
207                                 }
208                         }
209                 }
210         }
211
212 }