Sonar Fixes, Formatting
[aaf/authz.git] / cadi / aaf / src / test / java / org / onap / aaf / cadi / oauth / test / JU_OAuthTest.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.test;
23
24 import java.io.ByteArrayOutputStream;
25 import java.io.PrintStream;
26 import java.lang.reflect.Field;
27 import java.net.ConnectException;
28 import java.util.Date;
29 import java.util.GregorianCalendar;
30 import java.util.HashMap;
31
32 import org.junit.After;
33 import org.junit.AfterClass;
34 import org.junit.Before;
35 import org.junit.BeforeClass;
36 import org.junit.Test;
37 import org.onap.aaf.cadi.CadiException;
38 import org.onap.aaf.cadi.PropAccess;
39 import org.onap.aaf.cadi.client.Future;
40 import org.onap.aaf.cadi.client.Rcli;
41 import org.onap.aaf.cadi.client.Result;
42 import org.onap.aaf.cadi.client.Retryable;
43 import org.onap.aaf.cadi.config.Config;
44 import org.onap.aaf.cadi.config.SecurityInfoC;
45 import org.onap.aaf.cadi.oauth.TimedToken;
46 import org.onap.aaf.cadi.oauth.TokenClient;
47 import org.onap.aaf.cadi.oauth.TokenClientFactory;
48 import org.onap.aaf.cadi.oauth.TzClient;
49 import org.onap.aaf.cadi.principal.Kind;
50 import org.onap.aaf.misc.env.APIException;
51 import org.onap.aaf.misc.env.util.Chrono;
52
53 import aafoauth.v2_0.Introspect;
54 import aafoauth.v2_0.Token;
55 import junit.framework.Assert;
56
57 public class JU_OAuthTest {
58
59     private ByteArrayOutputStream outStream;
60
61     private static PropAccess access;
62     private static TokenClientFactory tcf;
63
64     @BeforeClass
65     public static void setUpBeforeClass()  {
66         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
67         System.setOut(new PrintStream(outStream));
68
69         access = new PropAccess();
70         access.setProperty(Config.CADI_LATITUDE, "38");
71         access.setProperty(Config.CADI_LONGITUDE, "-72");
72         try {
73             tcf = TokenClientFactory.instance(access);
74         } catch (Exception e) {
75             e.printStackTrace();
76             Assert.fail();
77         }
78     }
79
80     @AfterClass
81     public static void tearDownAfterClass() throws Exception {
82         Field field = SecurityInfoC.class.getDeclaredField("sicMap");
83         field.setAccessible(true);
84         field.set(null, new HashMap<>());
85     }
86
87     @Before
88     public void setUp() throws Exception {
89         outStream = new ByteArrayOutputStream();
90         System.setOut(new PrintStream(outStream));
91     }
92
93     @After
94     public void tearDown() throws Exception {
95         System.setOut(System.out);
96     }
97
98     @Test
99     public void testROPCFlowHappy() {
100         try {
101             // AAF OAuth
102             String client_id = access.getProperty(Config.AAF_APPID);
103             String client_secret = access.getProperty(Config.AAF_APPPASS);
104             String tokenServiceURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL);
105 //            Assert.assertNotNull(tokenServiceURL);
106             String tokenIntrospectURL = access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL);
107             String tokenAltIntrospectURL = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL);
108 //            Assert.assertNotNull(tokenIntrospectURL);
109             final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL);
110             String username = access.getProperty("cadi_username");
111
112             TokenClient tc;
113             Result<TimedToken> rtt;
114             if (true) {
115                 tc = tcf.newClient(tokenServiceURL, 3000);
116                 tc.client_creds(client_id,client_secret);
117                 tc.password(access.getProperty("cadi_username"),access.getProperty("cadi_password"));
118                 rtt = tc.getToken(Kind.BASIC_AUTH,"org.osaaf.aaf","org.osaaf.test");
119                 if (rtt.isOK()) {
120                     print(rtt.value);
121                     rtt = tc.refreshToken(rtt.value);
122                     if (rtt.isOK()) {
123                         print(rtt.value);
124                         TokenClient ic = tcf.newClient(tokenIntrospectURL,3000);
125                         ic.client_creds(client_id,client_secret);
126
127                         Result<Introspect> ri = ic.introspect(rtt.value.getAccessToken());
128                         if (ri.isOK()) {
129                             print(ri.value);
130                         } else {
131                             System.out.println(ri.code + ' ' + ri.error);
132                             Assert.fail(ri.code + ' ' + ri.error);
133                         }
134                         TzClient helloClient = tcf.newTzClient(endServicesURL);
135                         helloClient.setToken(client_id, rtt.value);
136 //                        String rv = serviceCall(helloClient);
137 //                        System.out.println(rv);
138         //                Assert.assertEquals("Hello AAF OAuth2\n",rv);
139                     } else {
140                         System.out.println(rtt.code + ' ' + rtt.error);
141                         Assert.fail(rtt.code + ' ' + rtt.error);
142                     }
143                 } else {
144                     System.out.println(rtt.code + ' ' + rtt.error);
145                     Assert.fail(rtt.code + ' ' + rtt.error);
146                 }
147             }
148
149             // ISAM Test
150             if (true) {
151                 System.out.println("**** ISAM TEST ****");
152                 tokenServiceURL=access.getProperty(Config.AAF_ALT_OAUTH2_TOKEN_URL);
153                 client_id=access.getProperty(Config.AAF_ALT_CLIENT_ID);
154                 client_secret=access.getProperty(Config.AAF_ALT_CLIENT_SECRET);
155                 if (tokenServiceURL!=null) {
156                     tc = tcf.newClient(tokenServiceURL, 3000);
157                     tc.client_creds(client_id, client_secret);
158                     int at = username.indexOf('@');
159
160                     tc.password(at>=0?username.substring(0, at):username,access.getProperty("cadi_password"));
161                     rtt = tc.getToken("org.osaaf.aaf","org.osaaf.test");
162                     if (rtt.isOK()) {
163                         print(rtt.value);
164                         rtt = tc.refreshToken(rtt.value);
165                         if (rtt.isOK()) {
166                             print(rtt.value);
167
168                             tc = tcf.newClient(tokenAltIntrospectURL, 3000);
169                             tc.client_creds(client_id, client_secret);
170                             Result<Introspect> rti = tc.introspect(rtt.value.getAccessToken());
171                             if (rti.isOK()) {
172                                 System.out.print("Normal ISAM ");
173                                 print(rti.value);
174                             } else {
175                                 System.out.println(rti.code + ' ' + rti.error);
176                                 Assert.fail(rtt.code + ' ' + rtt.error);
177                             }
178
179                             tc = tcf.newClient(tokenIntrospectURL, 3000);
180                             tc.client_creds(client_id, client_secret);
181                             rti = tc.introspect(rtt.value.getAccessToken());
182                             if (rti.isOK()) {
183                                 System.out.print("AAF with ISAM Token ");
184                                 print(rti.value);
185                             } else {
186                                 System.out.println(rti.code + ' ' + rti.error);
187                                 if (rti.code!=404) {
188                                     Assert.fail(rti.code + ' ' + rti.error);
189                                 }
190                             }
191
192                             TzClient tzClient = tcf.newTzClient(endServicesURL);
193                             tzClient.setToken(client_id, rtt.value);
194                             // Note: this is AAF's "Hello" server
195                             String rv = serviceCall(tzClient);
196                             System.out.println(rv);
197             //                Assert.assertEquals("Hello AAF OAuth2\n",rv);
198                         } else {
199                             System.out.println(rtt.code + ' ' + rtt.error);
200                             Assert.fail(rtt.code + ' ' + rtt.error);
201                         }
202                     } else {
203                         System.out.println(rtt.code + ' ' + rtt.error);
204                         Assert.fail(rtt.code + ' ' + rtt.error);
205                     }
206                 } else {
207                     Assert.fail(Config.AAF_ALT_OAUTH2_TOKEN_URL + " is required");
208                 }
209             }
210         } catch (Exception e) {
211 //            Assert.fail();
212         }
213     }
214
215
216 //    private TokenClient testROPCFlow(final String url, final String client_id, final String client_secret, String user, String password, final String ... scope) throws Exception {
217 //        TokenClient tclient = tcf.newClient(url,3000);
218 //        tclient.client_creds(client_id, client_secret);
219 //        if (user!=null && password!=null) {
220 //            tclient.password(user,password);
221 //        }
222 //        Result<TimedToken> rt = tclient.getToken(scope);
223 //        if (rt.isOK()) {
224 //            print(rt.value);
225 //            Result<Introspect> rti = tclient.introspect(rt.value.getAccessToken());
226 //            if (rti.isOK()) {
227 //                print(rti.value);
228 //            } else {
229 //                printAndFail(rti);
230 //            }
231 //        } else {
232 //            printAndFail(rt);
233 //        }
234 //        return tclient;
235 //    }
236
237     private String serviceCall(TzClient tzClient) throws Exception {
238         return tzClient.best(new Retryable<String>() {
239             @Override
240             public String code(Rcli<?> client) throws CadiException, ConnectException, APIException {
241                 Future<String> future = client.read(null,"text/plain");
242                 if (future.get(3000)) {
243                     return future.value;
244                 } else {
245                     throw new APIException(future.code()  + future.body());
246                 }
247             }
248         });
249     }
250 //    private void printAndFail(Result<?> rt) {
251 //        System.out.printf("HTTP Code %d: %s\n", rt.code, rt.error);
252 //        Assert.fail(rt.toString());
253 //    }
254
255     private void print(Token t) {
256         GregorianCalendar exp_date = new GregorianCalendar();
257         exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn());
258         System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n",
259         t.getAccessToken(),
260         t.getTokenType(),
261         t.getExpiresIn(),
262         Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))),
263         t.getScope(),
264         t.getRefreshToken());
265     }
266
267     private void print(Introspect ti) {
268         if (ti==null || ti.getClientId()==null) {
269             System.out.println("Empty Introspect");
270             return;
271         }
272         Date exp = new Date(ti.getExp()*1000); // seconds
273         System.out.printf("Introspect\n"
274                 + "\tAccessToken:\t%s\n"
275                 + "\tClient-id:\t%s\n"
276                 + "\tClient Type:\t%s\n"
277                 + "\tActive:  \t%s\n"
278                 + "\tUserName:\t%s\n"
279                 + "\tExpires: \t%d (%s)\n"
280                 + "\tScope:\t\t%s\n"
281                 + "\tContent:\t\t%s\n",
282         ti.getAccessToken(),
283         ti.getClientId(),
284         ti.getClientType(),
285         ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(),
286         ti.getUsername(),
287         ti.getExp(),
288         Chrono.timeStamp(exp),
289         ti.getScope(),
290         ti.getContent()==null?"":ti.getContent());
291
292         System.out.println();
293     }
294 }