Collection syntax change because of Sonar
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / oauth / TokenClientFactory.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi.oauth;
23
24 import java.io.IOException;
25 import java.net.HttpURLConnection;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.nio.file.Path;
29 import java.security.GeneralSecurityException;
30 import java.security.NoSuchAlgorithmException;
31 import java.util.Map;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.regex.Pattern;
34
35 import org.onap.aaf.cadi.Access;
36 import org.onap.aaf.cadi.CadiException;
37 import org.onap.aaf.cadi.Hash;
38 import org.onap.aaf.cadi.Locator;
39 import org.onap.aaf.cadi.LocatorException;
40 import org.onap.aaf.cadi.Symm;
41 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
42 import org.onap.aaf.cadi.aaf.v2_0.AAFLocator;
43 import org.onap.aaf.cadi.config.Config;
44 import org.onap.aaf.cadi.config.SecurityInfoC;
45 import org.onap.aaf.cadi.locator.PropertyLocator;
46 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
47 import org.onap.aaf.cadi.oauth.TokenClient.AUTHN_METHOD;
48 import org.onap.aaf.cadi.persist.Persist;
49 import org.onap.aaf.cadi.principal.Kind;
50 import org.onap.aaf.misc.env.APIException;
51 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
52
53 import aafoauth.v2_0.Token;
54
55 public class TokenClientFactory extends Persist<Token,TimedToken> {
56         private static TokenClientFactory instance;
57         private Map<String,AAFConHttp> aafcons = new ConcurrentHashMap<>();
58         private SecurityInfoC<HttpURLConnection> hsi;
59         // Package on purpose
60         final Symm symm;
61
62         private TokenClientFactory(Access pa) throws APIException, GeneralSecurityException, IOException, CadiException {
63                 super(pa, new RosettaEnv(pa.getProperties()),Token.class,"outgoing");
64                 
65                 if(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null)==null) {
66                         access.getProperties().put(Config.AAF_OAUTH2_TOKEN_URL, "https://AAF_LOCATE_URL/AAF_NS.token/2.0"); // Default to AAF
67                 }
68                 if(access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL,null)==null) {
69                         access.getProperties().put(Config.AAF_OAUTH2_INTROSPECT_URL, "https://AAF_LOCATE_URL/AAF_NS.introspect/2.0"); // Default to AAF);
70                 }
71
72                 symm = Symm.encrypt.obtain();
73                 hsi = SecurityInfoC.instance(access, HttpURLConnection.class);
74         }
75         
76         public synchronized static final TokenClientFactory instance(Access access) throws APIException, GeneralSecurityException, IOException, CadiException {
77                 if(instance==null) {
78                         instance = new TokenClientFactory(access);
79                 }
80                 return instance;
81         }
82         
83         /**
84          * Pickup Timeout from Properties
85          * 
86          * @param tagOrURL
87          * @return
88          * @throws CadiException
89          * @throws LocatorException
90          * @throws APIException
91          */
92         public<INTR> TokenClient newClient(final String tagOrURL) throws CadiException, LocatorException, APIException {
93                 return newClient(tagOrURL,Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)));
94         }
95         
96         public<INTR> TokenClient newClient(final String tagOrURL, final int timeout) throws CadiException, LocatorException, APIException {
97                 AAFConHttp ach;
98                 if(tagOrURL==null) {
99                         throw new CadiException("parameter tagOrURL cannot be null.");
100                 } else {
101                         ach = aafcons.get(tagOrURL);
102                         if(ach==null) {
103                                 aafcons.put(tagOrURL, ach=new AAFConHttp(access,tagOrURL));
104                         }
105                 }
106                 char okind;
107                 if( Config.AAF_OAUTH2_TOKEN_URL.equals(tagOrURL) ||
108                         Config.AAF_OAUTH2_INTROSPECT_URL.equals(tagOrURL) ||
109                         tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL, null)) ||
110                         tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL, null))
111                         ) {
112                                 okind = Kind.AAF_OAUTH;
113                         } else {
114                                 okind = Kind.OAUTH;
115                         }
116                 TokenClient tci = new TokenClient(
117                                 okind,
118                                 this,
119                                 ach,
120                                 timeout,
121                                 AUTHN_METHOD.none);
122                 tci.client_creds(access);
123                 return tci;
124         }
125         
126         public TzClient newTzClient(final String locatorURL) throws CadiException, LocatorException {
127                 try {
128                         return new TzHClient(access,hsi,bestLocator(locatorURL));
129                 } catch (URISyntaxException e) {
130                         throw new LocatorException(e);
131                 }
132         }
133
134         static String getKey(char tokenSource,String client_id, String username, byte[] hash, String scope) throws CadiException {
135                 try {
136                         StringBuilder sb = new StringBuilder(client_id);
137                         sb.append('_');
138                         if(username!=null) {
139                                 sb.append(username);
140                         }
141                         sb.append('_');
142                         sb.append(tokenSource);
143                         byte[] tohash=scope.getBytes();
144                         if(hash!=null && hash.length>0) {
145                                 byte temp[] = new byte[hash.length+tohash.length];
146                                 System.arraycopy(tohash, 0, temp, 0, tohash.length);
147                                 System.arraycopy(hash, 0, temp, tohash.length, hash.length);
148                                 tohash = temp;
149                         }
150                         if(scope!=null && scope.length()>0) {
151                                 sb.append(Hash.toHexNo0x(Hash.hashSHA256(tohash)));
152                         }
153                         return sb.toString();
154                 } catch (NoSuchAlgorithmException e) {
155                         throw new CadiException(e);
156                 }
157         }
158
159         @Override
160         protected TimedToken newCacheable(Token t, long expires, byte[] hash, Path path) throws IOException {
161                 return new TimedToken(this,t,expires,hash,path);
162         }
163
164         public TimedToken putTimedToken(String key, Token token, byte[] hash) throws IOException, CadiException {
165                 TimedToken tt = new TimedToken(this,token,token.getExpiresIn()+(System.currentTimeMillis()/1000),hash,getPath(key));
166                 put(key,tt);
167                 return tt;
168         }
169         
170         private static final Pattern locatePattern = Pattern.compile("https://.*/locate/.*");
171         public Locator<URI> bestLocator(final String locatorURL ) throws LocatorException, URISyntaxException {
172                 if(locatorURL==null) {
173                         throw new LocatorException("Cannot have a null locatorURL in bestLocator");
174                 }
175                 if(locatorURL.startsWith("https://AAF_LOCATE_URL/") || locatePattern.matcher(locatorURL).matches()) {
176                         return new AAFLocator(hsi,new URI(locatorURL));
177                 } else if(locatorURL.indexOf(',')>0) { // multiple URLs is a Property Locator
178                         return new PropertyLocator(locatorURL);
179                 } else {
180                         return new SingleEndpointLocator(locatorURL);
181                 }
182                 // Note: Removed DME2Locator... If DME2 client is needed, use DME2Clients
183         }
184 }