migrate sdnr features to sulfur
[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.Test;
44 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.Config;
45 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.OAuthProviderConfig;
46 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.UnableToConfigureOAuthService;
47 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers.KeycloakProviderService;
48 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers.TokenCreator;
49
50 public class TestKeycloakAuthService {
51
52     private static HttpServer server;
53     private static ExecutorService httpThreadPool;
54     private static KeycloakProviderServiceToTest oauthService;
55     private static final int PORT = randomPort(50000, 55000);
56     private static final String KEYCLOAKURL = String.format("http://127.0.0.1:%d", PORT);
57     private static final String OAUTH_SECRET = "oauthsecret";
58     private static final String TOKENCREATOR_SECRET = "secret";
59     private static final String REDIRECT_URI = "/odlux/token?";
60
61     @BeforeClass
62     public static void init() throws IllegalArgumentException, Exception {
63
64         TokenCreator tokenCreator = TokenCreator.getInstance(Config.TOKENALG_HS256, TOKENCREATOR_SECRET, "issuer", 30*60);
65         OAuthProviderConfig config = new OAuthProviderConfig("kc", KEYCLOAKURL, null, "odlux.app", OAUTH_SECRET,
66                 "openid", "keycloak test", "onap",null, false);
67         oauthService = new KeycloakProviderServiceToTest(config, REDIRECT_URI, tokenCreator);
68         try {
69             initKeycloakTestWebserver(PORT, "/");
70         } catch (IOException e) {
71             fail(e.getMessage());
72         }
73     }
74
75     @AfterClass
76     public static void close() {
77         stopTestWebserver();
78     }
79
80     @Test
81     public void test() {
82         HttpServletRequest req;
83         HttpServletResponse resp = null;
84         String host = "http://localhost:8412";
85         final String state = "stateabc";
86         try {
87             req = mock(HttpServletRequest.class);
88             resp = mock(HttpServletResponse.class);
89             when(req.getParameter("code")).thenReturn("abcdefg");
90             when(req.getParameter("state")).thenReturn(state);
91             oauthService.handleRedirect(req, resp, host);
92         } catch (IOException e) {
93             fail(e.getMessage());
94         }
95         verify(resp).setStatus(302);
96         //verify(resp).setHeader("Location",any(String.class));
97     }
98
99     public void test2() {
100         oauthService.sendLoginRedirectResponse(null, null);
101     }
102
103     public static class KeycloakProviderServiceToTest extends KeycloakProviderService {
104
105         public KeycloakProviderServiceToTest(OAuthProviderConfig config, String redirectUri,
106                 TokenCreator tokenCreator) throws UnableToConfigureOAuthService {
107             super(config, redirectUri, tokenCreator);
108         }
109     }
110
111     private static int randomPort(int min, int max) {
112         Random random = new Random();
113         return random.nextInt(max + 1 - min) + min;
114     }
115
116     public static void initKeycloakTestWebserver(int port, String baseUri) throws IOException {
117         server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
118         httpThreadPool = Executors.newFixedThreadPool(5);
119         server.setExecutor(httpThreadPool);
120         server.createContext(baseUri, new MyHandler());
121         //server.createContext("/", new MyRootHandler());
122         server.setExecutor(null); // creates a default executor
123         server.start();
124         System.out.println("http server started");
125     }
126
127     public static void stopTestWebserver() {
128         if (server != null) {
129             server.stop(0);
130             httpThreadPool.shutdownNow();
131             System.out.println("http server stopped");
132         }
133     }
134
135     private static String loadResourceFileContent(String filename) {
136         try {
137             return Files.readString(new File(filename).toPath());
138         } catch (IOException e) {
139             fail(e.getMessage());
140         }
141         return null;
142     }
143
144     public static class MyHandler implements HttpHandler {
145         private static final String KEYCLOAK_TOKEN_ENDPOINT = "/auth/realms/onap/protocol/openid-connect/token";
146         private static final String KEYCLOAK_TOKEN_RESPONSE =
147                 loadResourceFileContent("src/test/resources/oauth/keycloak-token-response.json");
148
149         @Override
150         public void handle(HttpExchange t) throws IOException {
151             final String method = t.getRequestMethod();
152             final String uri = t.getRequestURI().toString();
153             System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
154             OutputStream os = null;
155             try {
156                 if (method.equals("POST")) {
157                     if (uri.equals(KEYCLOAK_TOKEN_ENDPOINT)) {
158                         t.sendResponseHeaders(200, KEYCLOAK_TOKEN_RESPONSE.length());
159                         os = t.getResponseBody();
160                         os.write(KEYCLOAK_TOKEN_RESPONSE.getBytes());
161                     } else {
162                         t.sendResponseHeaders(404, 0);
163                     }
164                 } else {
165                     t.sendResponseHeaders(404, 0);
166                 }
167                 System.out.println("req handled successful");
168
169             } catch (Exception e) {
170                 System.out.println(e.getMessage());
171             } finally {
172                 if (os != null) {
173                     os.close();
174                 }
175             }
176         }
177     }
178 }