Merge "Add docs structure & locate coverage"
[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.oauth.TokenClient.AUTHN_METHOD;
47 import org.onap.aaf.cadi.persist.Persist;
48 import org.onap.aaf.cadi.principal.Kind;
49 import org.onap.aaf.misc.env.APIException;
50 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
51
52 import aafoauth.v2_0.Token;
53
54 public class TokenClientFactory extends Persist<Token,TimedToken> {
55         private static TokenClientFactory instance;
56         private Map<String,AAFConHttp> aafcons = new ConcurrentHashMap<String, AAFConHttp>();
57         private SecurityInfoC<HttpURLConnection> hsi;
58         // Package on purpose
59         final Symm symm;        
60
61         private TokenClientFactory(Access pa) throws APIException, GeneralSecurityException, IOException, CadiException {
62                 super(pa, new RosettaEnv(pa.getProperties()),Token.class,"outgoing");
63                 symm = Symm.encrypt.obtain();
64                 hsi = SecurityInfoC.instance(access, HttpURLConnection.class);
65         }
66         
67         public synchronized static final TokenClientFactory instance(Access access) throws APIException, GeneralSecurityException, IOException, CadiException {
68                 if(instance==null) {
69                         instance = new TokenClientFactory(access);
70                 }
71                 return instance;
72         }
73
74         /**
75          * Pickup Timeout from Properties
76          * 
77          * @param tagOrURL
78          * @return
79          * @throws CadiException
80          * @throws LocatorException
81          * @throws APIException
82          */
83         public<INTR> TokenClient newClient(final String tagOrURL) throws CadiException, LocatorException, APIException {
84                 return newClient(tagOrURL,Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)));
85         }
86         
87         public<INTR> TokenClient newClient(final String tagOrURL, final int timeout) throws CadiException, LocatorException, APIException {
88                 AAFConHttp ach;
89                 if(tagOrURL==null) {
90                         throw new CadiException("parameter tagOrURL cannot be null.");
91                 } else {
92                         ach = aafcons.get(tagOrURL);
93                         if(ach==null) {
94                                 aafcons.put(tagOrURL, ach=new AAFConHttp(access,tagOrURL));
95                         }
96                 }
97                 char okind;
98                 if(Config.AAF_OAUTH2_TOKEN_URL.equals(tagOrURL) || 
99                         tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL, null))) {
100                                 okind = Kind.AAF_OAUTH;
101                         } else {
102                                 okind = Kind.OAUTH;
103                         }
104                 return new TokenClient(
105                                 okind,
106                                 this,
107                                 ach,
108                                 timeout,
109                                 AUTHN_METHOD.none);
110         }
111         
112         public TzClient newTzClient(final String locatorURL) throws CadiException, LocatorException {
113                 try {
114                         return new TzHClient(access,hsi,bestLocator(locatorURL));
115                 } catch (URISyntaxException e) {
116                         throw new LocatorException(e);
117                 }
118         }
119
120         static String getKey(char tokenSource,String client_id, String username, byte[] hash, String scope) throws CadiException {
121                 try {
122                         StringBuilder sb = new StringBuilder(client_id);
123                         sb.append('_');
124                         if(username!=null) {
125                                 sb.append(username);
126                         }
127                         sb.append('_');
128                         sb.append(tokenSource);
129                         byte[] tohash=scope.getBytes();
130                         if(hash!=null && hash.length>0) {
131                                 byte temp[] = new byte[hash.length+tohash.length];
132                                 System.arraycopy(tohash, 0, temp, 0, tohash.length);
133                                 System.arraycopy(hash, 0, temp, tohash.length, hash.length);
134                                 tohash = temp;
135                         }
136                         if(scope!=null && scope.length()>0) {
137                                 sb.append(Hash.toHexNo0x(Hash.hashSHA256(tohash)));
138                         }
139                         return sb.toString();
140                 } catch (NoSuchAlgorithmException e) {
141                         throw new CadiException(e);
142                 }
143         }
144
145         @Override
146         protected TimedToken newCacheable(Token t, long expires, byte[] hash, Path path) throws IOException {
147                 return new TimedToken(this,t,expires,hash,path);
148         }
149
150         public TimedToken putTimedToken(String key, Token token, byte[] hash) throws IOException, CadiException {
151                 TimedToken tt = new TimedToken(this,token,token.getExpiresIn()+(System.currentTimeMillis()/1000),hash,getPath(key));
152                 put(key,tt);
153                 return tt;
154         }
155         
156         private static final Pattern locatePattern = Pattern.compile("https://.*/locate/.*");
157         public Locator<URI> bestLocator(final String locatorURL ) throws LocatorException, URISyntaxException {
158                 if(locatorURL==null) {
159                         throw new LocatorException("Cannot have a null locatorURL in bestLocator");
160                 }
161                 if(locatorURL.startsWith("https://AAF_LOCATE_URL/") || locatePattern.matcher(locatorURL).matches()) {
162                         return new AAFLocator(hsi,new URI(locatorURL));
163                 } else {
164                         return new PropertyLocator(locatorURL);
165                 }
166                 // Note: Removed DME2Locator... If DME2 client is needed, use DME2Clients
167         }
168 }