dda3ba1e0e895fa245062ada7391439601ff9967
[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.Config;
45 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.data.OAuthProviderConfig;
46 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers.GitlabProviderService;
47 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers.TokenCreator;
48
49 public class TestGitlabAuthService {
50
51     private static HttpServer server;
52     private static ExecutorService httpThreadPool;
53     private static GitlabProviderServiceToTest oauthService;
54     private static final int PORT = randomPort(50000, 55000);
55     private static final String GITURL = String.format("http://127.0.0.1:%d", PORT);
56     private static final String OAUTH_SECRET = "oauthsecret";
57     private static final String TOKENCREATOR_SECRET = "secret";
58     private static final String REDIRECT_URI = "/odlux/token?";
59
60     @BeforeClass
61     public static void init() throws IllegalArgumentException, Exception {
62
63         TokenCreator tokenCreator = TokenCreator.getInstance(Config.TOKENALG_HS256, TOKENCREATOR_SECRET, "issuer", 30*60);
64         OAuthProviderConfig config = new OAuthProviderConfig("git", GITURL, null, "odlux.app", OAUTH_SECRET, "openid",
65                 "gitlab test", "", false);
66         oauthService = new GitlabProviderServiceToTest(config, REDIRECT_URI, tokenCreator);
67         try {
68             initGitlabTestWebserver(PORT, "/");
69         } catch (IOException e) {
70             fail(e.getMessage());
71         }
72     }
73
74     @AfterClass
75     public static void close() {
76         stopTestWebserver();
77     }
78
79     @Test
80     public void test() {
81         HttpServletRequest req;
82         HttpServletResponse resp = null;
83         String host = "http://localhost:8412";
84         final String state = "stateabc";
85         try {
86             req = mock(HttpServletRequest.class);
87             resp = mock(HttpServletResponse.class);
88             when(req.getParameter("code")).thenReturn("abcdefg");
89             when(req.getParameter("state")).thenReturn(state);
90             oauthService.addState(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 GitlabProviderServiceToTest extends GitlabProviderService {
104
105         public GitlabProviderServiceToTest(OAuthProviderConfig config, String redirectUri, TokenCreator tokenCreator) {
106             super(config, redirectUri, tokenCreator);
107         }
108
109         public void addState(String state) {
110             this.randomIds.add(state);
111         }
112     }
113
114     private static int randomPort(int min, int max) {
115         Random random = new Random();
116         return random.nextInt(max + 1 - min) + min;
117     }
118
119     public static void initGitlabTestWebserver(int port, String baseUri) throws IOException {
120         server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
121         httpThreadPool = Executors.newFixedThreadPool(5);
122         server.setExecutor(httpThreadPool);
123         server.createContext(baseUri, new MyHandler());
124         //server.createContext("/", new MyRootHandler());
125         server.setExecutor(null); // creates a default executor
126         server.start();
127         System.out.println("http server started");
128     }
129
130     public static void stopTestWebserver() {
131         if (server != null) {
132             server.stop(0);
133             httpThreadPool.shutdownNow();
134             System.out.println("http server stopped");
135         }
136     }
137
138     private static String loadResourceFileContent(String filename) {
139         try {
140             return Files.readString(new File(filename).toPath());
141         } catch (IOException e) {
142             fail(e.getMessage());
143         }
144         return null;
145     }
146
147     public static class MyHandler implements HttpHandler {
148         private static final String GITLAB_TOKEN_ENDPOINT = "/oauth/token";
149         private static final String GITLAB_USER_ENDPOINT = "/api/v4/user";
150         private static final String GITLAB_GROUP_ENDPOINT = "/api/v4/groups?min_access_level=10";
151         private static final String GITLAB_TOKEN_RESPONSE =
152                 loadResourceFileContent("src/test/resources/oauth/gitlab-token-response.json");
153         private static final String GITLAB_USER_RESPONSE =
154                 loadResourceFileContent("src/test/resources/oauth/gitlab-user-response.json");
155         private static final String GITLAB_GROUP_RESPONSE =
156                 loadResourceFileContent("src/test/resources/oauth/gitlab-groups-response.json");
157
158         @Override
159         public void handle(HttpExchange t) throws IOException {
160             final String method = t.getRequestMethod();
161             final String uri = t.getRequestURI().toString();
162             System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
163             OutputStream os = null;
164             try {
165                 if (method.equals("GET")) {
166                     if (uri.equals(GITLAB_USER_ENDPOINT)) {
167                         t.sendResponseHeaders(200, GITLAB_USER_RESPONSE.length());
168                         os = t.getResponseBody();
169                         os.write(GITLAB_USER_RESPONSE.getBytes());
170                     } else if (uri.equals(GITLAB_GROUP_ENDPOINT)) {
171                         t.sendResponseHeaders(200, GITLAB_GROUP_RESPONSE.length());
172                         os = t.getResponseBody();
173                         os.write(GITLAB_GROUP_RESPONSE.getBytes());
174                     }
175                 } else if (method.equals("POST")) {
176                     if (uri.equals(GITLAB_TOKEN_ENDPOINT)) {
177                         t.sendResponseHeaders(200, GITLAB_TOKEN_RESPONSE.length());
178                         os = t.getResponseBody();
179                         os.write(GITLAB_TOKEN_RESPONSE.getBytes());
180                     } else {
181                         t.sendResponseHeaders(404, 0);
182                     }
183                 } else {
184                     t.sendResponseHeaders(404, 0);
185                 }
186                 System.out.println("req handled successful");
187
188             } catch (Exception e) {
189                 System.out.println(e.getMessage());
190             } finally {
191                 if (os != null) {
192                     os.close();
193                 }
194             }
195         }
196     }
197 }