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