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