Merge "Moved null ref check to line before dereferencing"
[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.Set;
33 import java.util.TreeSet;
34 import java.util.concurrent.ConcurrentHashMap;
35 import java.util.regex.Pattern;
36
37 import org.onap.aaf.cadi.Access;
38 import org.onap.aaf.cadi.CadiException;
39 import org.onap.aaf.cadi.Hash;
40 import org.onap.aaf.cadi.Locator;
41 import org.onap.aaf.cadi.LocatorException;
42 import org.onap.aaf.cadi.Symm;
43 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
44 import org.onap.aaf.cadi.aaf.v2_0.AAFLocator;
45 import org.onap.aaf.cadi.config.Config;
46 import org.onap.aaf.cadi.config.SecurityInfoC;
47 import org.onap.aaf.cadi.configure.Agent;
48 import org.onap.aaf.cadi.locator.PropertyLocator;
49 import org.onap.aaf.cadi.locator.SingleEndpointLocator;
50 import org.onap.aaf.cadi.oauth.TokenClient.AUTHN_METHOD;
51 import org.onap.aaf.cadi.persist.Persist;
52 import org.onap.aaf.cadi.principal.Kind;
53 import org.onap.aaf.misc.env.APIException;
54 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
55
56 import aafoauth.v2_0.Token;
57
58 public class TokenClientFactory extends Persist<Token,TimedToken> {
59     private static TokenClientFactory instance;
60     private final Set<String> alts;
61     private Map<String,AAFConHttp> aafcons = new ConcurrentHashMap<>();
62     private SecurityInfoC<HttpURLConnection> hsi;
63     // Package on purpose
64     final Symm symm;
65
66     private TokenClientFactory(Access pa) throws APIException, GeneralSecurityException, IOException, CadiException {
67         super(pa, new RosettaEnv(pa.getProperties()),Token.class,"outgoing");
68         
69         Map<String, String> aaf_urls = Agent.loadURLs(pa);
70         alts = new TreeSet<>();
71         
72         if (access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null)==null) {
73             access.getProperties().put(Config.AAF_OAUTH2_TOKEN_URL, aaf_urls.get(Config.AAF_OAUTH2_TOKEN_URL)); // Default to AAF
74         }
75         
76         if (access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL,null)==null) {
77             access.getProperties().put(Config.AAF_OAUTH2_INTROSPECT_URL, aaf_urls.get(Config.AAF_OAUTH2_INTROSPECT_URL)); // Default to AAF);
78         }
79         
80         for(String tag : new String[] {Config.AAF_ALT_OAUTH2_TOKEN_URL, Config.AAF_ALT_OAUTH2_INTROSPECT_URL}) {
81                 String value = access.getProperty(tag, null);
82                 if(value!=null) {
83                         alts.add(tag);
84                         alts.add(value);
85                 }
86         }
87         
88         symm = Symm.encrypt.obtain();
89         hsi = SecurityInfoC.instance(access, HttpURLConnection.class);
90     }
91     
92     public synchronized static final TokenClientFactory instance(Access access) throws APIException, GeneralSecurityException, IOException, CadiException {
93         if (instance==null) {
94             instance = new TokenClientFactory(access);
95         }
96         return instance;
97     }
98     
99     /**
100      * Pickup Timeout from Properties
101      * 
102      * @param tagOrURL
103      * @return
104      * @throws CadiException
105      * @throws LocatorException
106      * @throws APIException
107      */
108     public<INTR> TokenClient newClient(final String tagOrURL) throws CadiException, LocatorException, APIException {
109         return newClient(tagOrURL,Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)));
110     }
111     
112     public<INTR> TokenClient newClient(final String tagOrURL, final int timeout) throws CadiException, LocatorException, APIException {
113         AAFConHttp ach;
114         if (tagOrURL==null) {
115             throw new CadiException("parameter tagOrURL cannot be null.");
116         } else {
117             ach = aafcons.get(tagOrURL);
118             if (ach==null) {
119                 aafcons.put(tagOrURL, ach=new AAFConHttp(access,tagOrURL));
120             }
121         }
122         char okind;
123         if (alts.contains(tagOrURL)) {
124                 okind = Kind.OAUTH;
125         } else {
126             okind = Kind.AAF_OAUTH;
127         }
128         TokenClient tci = new TokenClient(
129                 okind,
130                 this,
131                 ach,
132                 timeout,
133                 AUTHN_METHOD.none);
134         tci.client_creds(access);
135         return tci;
136     }
137     
138     public TzClient newTzClient(final String locatorURL) throws CadiException, LocatorException {
139         try {
140             return new TzHClient(access,hsi,bestLocator(locatorURL));
141         } catch (URISyntaxException e) {
142             throw new LocatorException(e);
143         }
144     }
145
146     static String getKey(char tokenSource,String client_id, String username, byte[] hash, String scope) throws CadiException {
147         try {
148             StringBuilder sb = new StringBuilder(client_id);
149             sb.append('_');
150             if (username!=null) {
151                 sb.append(username);
152             }
153             sb.append('_');
154             sb.append(tokenSource);
155             if (scope!=null) {
156                 byte[] tohash=scope.getBytes();
157                 if (hash!=null && hash.length>0) {
158                     byte temp[] = new byte[hash.length+tohash.length];
159                     System.arraycopy(tohash, 0, temp, 0, tohash.length);
160                     System.arraycopy(hash, 0, temp, tohash.length, hash.length);
161                     tohash = temp;
162                 }
163                 if (scope.length()>0) {
164                     sb.append(Hash.toHexNo0x(Hash.hashSHA256(tohash)));
165                 }
166             }
167             return sb.toString();
168         } catch (NoSuchAlgorithmException e) {
169             throw new CadiException(e);
170         }
171     }
172
173     @Override
174     protected TimedToken newCacheable(Token t, long expires, byte[] hash, Path path) throws IOException {
175         return new TimedToken(this,t,expires,hash,path);
176     }
177
178     public TimedToken putTimedToken(String key, Token token, byte[] hash) throws IOException, CadiException {
179         TimedToken tt = new TimedToken(this,token,token.getExpiresIn()+(System.currentTimeMillis()/1000),hash,getPath(key));
180         put(key,tt);
181         return tt;
182     }
183     
184     private static final Pattern locatePattern = Pattern.compile("https://.*/locate/.*");
185     public Locator<URI> bestLocator(final String locatorURL ) throws LocatorException, URISyntaxException {
186         if (locatorURL==null) {
187             throw new LocatorException("Cannot have a null locatorURL in bestLocator");
188         }
189         if (locatorURL.startsWith("https://AAF_LOCATE_URL/") || locatePattern.matcher(locatorURL).matches()) {
190             return new AAFLocator(hsi,new URI(locatorURL));
191         } else if (locatorURL.indexOf(',')>0) { // multiple URLs is a Property Locator
192             return new PropertyLocator(locatorURL);
193         } else {
194             return new SingleEndpointLocator(locatorURL);
195         }
196         // Note: Removed DME2Locator... If DME2 client is needed, use DME2Clients
197     }
198 }