Inventory TreeView Fixed
[ccsdk/features.git] / sdnr / wt / oauth-provider / provider-jar / src / test / java / org / onap / ccsdk / features / sdnr / wt / oauthprovider / test / TestKeycloakAuthService.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.oauthprovider.test;
23
24 import static org.junit.Assert.fail;
25 import static org.mockito.Mockito.mock;
26 import static org.mockito.Mockito.verify;
27 import static org.mockito.Mockito.when;
28 import com.sun.net.httpserver.HttpExchange;
29 import com.sun.net.httpserver.HttpHandler;
30 import com.sun.net.httpserver.HttpServer;
31 import java.io.File;
32 import java.io.IOException;
33 import java.io.OutputStream;
34 import java.net.InetSocketAddress;
35 import java.nio.file.Files;
36 import java.util.Random;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41 import org.junit.AfterClass;
42 import org.junit.BeforeClass;
43 import org.junit.Ignore;
44 import org.junit.Test;
45 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.Config;
46 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.OAuthProviderConfig;
47 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.UnableToConfigureOAuthService;
48 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers.KeycloakProviderService;
49 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers.TokenCreator;
50
51 public class TestKeycloakAuthService {
52
53     private static HttpServer server;
54     private static ExecutorService httpThreadPool;
55     private static KeycloakProviderServiceToTest oauthService;
56     private static final int PORT = randomPort(50000, 55000);
57     private static final String KEYCLOAKURL = String.format("http://127.0.0.1:%d", PORT);
58     private static final String OAUTH_SECRET = "oauthsecret";
59     private static final String TOKENCREATOR_SECRET = "secret";
60     private static final String REDIRECT_URI = "/odlux/token?";
61
62     @BeforeClass
63     public static void init() throws IllegalArgumentException, Exception {
64
65         TokenCreator tokenCreator = TokenCreator.getInstance(Config.TOKENALG_HS256, TOKENCREATOR_SECRET, "issuer", 30*60);
66         OAuthProviderConfig config = new OAuthProviderConfig("kc", KEYCLOAKURL, null, "odlux.app", OAUTH_SECRET,
67                 "openid", "keycloak test", "onap",null, false);
68         oauthService = new KeycloakProviderServiceToTest(config, REDIRECT_URI, tokenCreator);
69         try {
70             initKeycloakTestWebserver(PORT, "/");
71         } catch (IOException e) {
72             fail(e.getMessage());
73         }
74     }
75
76     @AfterClass
77     public static void close() {
78         stopTestWebserver();
79     }
80
81     @Test
82     public void test() {
83         HttpServletRequest req;
84         HttpServletResponse resp = null;
85         String host = "http://localhost:8412";
86         final String state = "stateabc";
87         try {
88             req = mock(HttpServletRequest.class);
89             resp = mock(HttpServletResponse.class);
90             when(req.getParameter("code")).thenReturn("abcdefg");
91             when(req.getParameter("state")).thenReturn(state);
92             oauthService.handleRedirect(req, resp, host);
93         } catch (IOException e) {
94             fail(e.getMessage());
95         }
96         verify(resp).setStatus(302);
97         //verify(resp).setHeader("Location",any(String.class));
98     }
99
100     public void test2() {
101         oauthService.sendLoginRedirectResponse(null, null);
102     }
103     @Ignore
104     @Test
105     public void test3() {
106         HttpServletResponse resp = mock(HttpServletResponse.class);
107         String token = "";
108         try {
109             oauthService.sendLogoutRedirectResponse(token, resp,"http://sdnr.onap/odlux/index.html");
110             verify(resp).setStatus(302);
111         } catch (IOException e) {
112             throw new RuntimeException(e);
113         }
114     }
115     public static class KeycloakProviderServiceToTest extends KeycloakProviderService {
116
117         public KeycloakProviderServiceToTest(OAuthProviderConfig config, String redirectUri,
118                 TokenCreator tokenCreator) throws UnableToConfigureOAuthService {
119             super(config, redirectUri, tokenCreator);
120         }
121     }
122
123     private static int randomPort(int min, int max) {
124         Random random = new Random();
125         return random.nextInt(max + 1 - min) + min;
126     }
127
128     public static void initKeycloakTestWebserver(int port, String baseUri) throws IOException {
129         server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
130         httpThreadPool = Executors.newFixedThreadPool(5);
131         server.setExecutor(httpThreadPool);
132         server.createContext(baseUri, new MyHandler());
133         //server.createContext("/", new MyRootHandler());
134         server.setExecutor(null); // creates a default executor
135         server.start();
136         System.out.println("http server started");
137     }
138
139     public static void stopTestWebserver() {
140         if (server != null) {
141             server.stop(0);
142             httpThreadPool.shutdownNow();
143             System.out.println("http server stopped");
144         }
145     }
146
147     private static String loadResourceFileContent(String filename) {
148         try {
149             return Files.readString(new File(filename).toPath());
150         } catch (IOException e) {
151             fail(e.getMessage());
152         }
153         return null;
154     }
155
156     public static class MyHandler implements HttpHandler {
157         private static final String KEYCLOAK_TOKEN_ENDPOINT = "/auth/realms/onap/protocol/openid-connect/token";
158         private static final String KEYCLOAK_LOGOUT_ENDPOINT = "/auth/realms/onap/protocol/openid-connect/logout";
159         private static final String KEYCLOAK_TOKEN_RESPONSE =
160                 loadResourceFileContent("src/test/resources/oauth/keycloak-token-response.json");
161
162         @Override
163         public void handle(HttpExchange t) throws IOException {
164             final String method = t.getRequestMethod();
165             final String uri = t.getRequestURI().toString();
166             System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
167             OutputStream os = null;
168             try {
169                 if("GET".equals(method)){
170                     if(KEYCLOAK_LOGOUT_ENDPOINT.equals(uri)){
171                         t.sendResponseHeaders(200, 0);
172                     }
173                 }
174                 else if ("POST".equals(method)) {
175                     if (uri.equals(KEYCLOAK_TOKEN_ENDPOINT)) {
176                         t.sendResponseHeaders(200, KEYCLOAK_TOKEN_RESPONSE.length());
177                         os = t.getResponseBody();
178                         os.write(KEYCLOAK_TOKEN_RESPONSE.getBytes());
179                     } else {
180                         t.sendResponseHeaders(404, 0);
181                     }
182                 } else {
183                     t.sendResponseHeaders(404, 0);
184                 }
185                 System.out.println("req handled successful");
186
187             } catch (Exception e) {
188                 System.out.println(e.getMessage());
189             } finally {
190                 if (os != null) {
191                     os.close();
192                 }
193             }
194         }
195     }
196 }