2  * ============LICENSE_START=======================================================
 
   3  * ONAP : ccsdk features
 
   4  * ================================================================================
 
   5  * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property.
 
   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
 
  12  *     http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  22 package org.onap.ccsdk.features.sdnr.wt.oauthprovider.test;
 
  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;
 
  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.GitlabProviderService;
 
  46 import org.onap.ccsdk.features.sdnr.wt.oauthprovider.providers.TokenCreator;
 
  48 public class TestGitlabAuthService {
 
  50     private static HttpServer server;
 
  51     private static ExecutorService httpThreadPool;
 
  52     private static GitlabProviderServiceToTest oauthService;
 
  53     private static final int PORT = randomPort(50000, 55000);
 
  54     private static final String GITURL = 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?";
 
  60     public static void init() {
 
  62         TokenCreator tokenCreator = TokenCreator.getInstance(TOKENCREATOR_SECRET, "issuer");
 
  63         OAuthProviderConfig config =
 
  64                 new OAuthProviderConfig("git", GITURL, "odlux.app", OAUTH_SECRET, "openid", "gitlab test");
 
  65         oauthService = new GitlabProviderServiceToTest(config, REDIRECT_URI, tokenCreator);
 
  67             initGitlabTestWebserver(PORT, "/");
 
  68         } catch (IOException e) {
 
  74     public static void close() {
 
  80         HttpServletRequest req;
 
  81         HttpServletResponse resp = null;
 
  82         String host = "http://localhost:8412";
 
  83         final String state = "stateabc";
 
  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.addState(state);
 
  90             oauthService.handleRedirect(req, resp, host);
 
  91         } catch (IOException e) {
 
  94         verify(resp).setStatus(302);
 
  95         //verify(resp).setHeader("Location",any(String.class));
 
  99         oauthService.sendLoginRedirectResponse(null, null);
 
 102     public static class GitlabProviderServiceToTest extends GitlabProviderService {
 
 104         public GitlabProviderServiceToTest(OAuthProviderConfig config, String redirectUri, TokenCreator tokenCreator) {
 
 105             super(config, redirectUri, tokenCreator);
 
 108         public void addState(String state) {
 
 109             this.randomIds.add(state);
 
 113     private static int randomPort(int min, int max) {
 
 114         Random random = new Random();
 
 115         return random.nextInt(max + 1 - min) + min;
 
 118     public static void initGitlabTestWebserver(int port, String baseUri) throws IOException {
 
 119         server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
 
 120         httpThreadPool = Executors.newFixedThreadPool(5);
 
 121         server.setExecutor(httpThreadPool);
 
 122         server.createContext(baseUri, new MyHandler());
 
 123         //server.createContext("/", new MyRootHandler());
 
 124         server.setExecutor(null); // creates a default executor
 
 126         System.out.println("http server started");
 
 129     public static void stopTestWebserver() {
 
 130         if (server != null) {
 
 132             httpThreadPool.shutdownNow();
 
 133             System.out.println("http server stopped");
 
 137     private static String loadResourceFileContent(String filename) {
 
 139             return Files.readString(new File(filename).toPath());
 
 140         } catch (IOException e) {
 
 141             fail(e.getMessage());
 
 145     public static class MyHandler implements HttpHandler {
 
 146         private static final String GITLAB_TOKEN_ENDPOINT = "/oauth/token";
 
 147         private static final String GITLAB_USER_ENDPOINT = "/api/v4/user";
 
 148         private static final String GITLAB_GROUP_ENDPOINT = "/api/v4/groups?min_access_level=10";
 
 149         private static final String GITLAB_TOKEN_RESPONSE = loadResourceFileContent("src/test/resources/oauth/gitlab-token-response.json");
 
 150         private static final String GITLAB_USER_RESPONSE =loadResourceFileContent("src/test/resources/oauth/gitlab-user-response.json");
 
 151         private static final String GITLAB_GROUP_RESPONSE =loadResourceFileContent("src/test/resources/oauth/gitlab-groups-response.json");
 
 154         public void handle(HttpExchange t) throws IOException {
 
 155             final String method = t.getRequestMethod();
 
 156             final String uri = t.getRequestURI().toString();
 
 157             System.out.println(String.format("req received: %s %s", method, t.getRequestURI()));
 
 158             OutputStream os = null;
 
 159             String response = "";
 
 161                 if (method.equals("GET")) {
 
 162                     if(uri.equals(GITLAB_USER_ENDPOINT)) {
 
 163                         t.sendResponseHeaders(200, GITLAB_USER_RESPONSE.length());
 
 164                         os = t.getResponseBody();
 
 165                         os.write(GITLAB_USER_RESPONSE.getBytes());
 
 167                     else if(uri.equals(GITLAB_GROUP_ENDPOINT)) {
 
 168                         t.sendResponseHeaders(200, GITLAB_GROUP_RESPONSE.length());
 
 169                         os = t.getResponseBody();
 
 170                         os.write(GITLAB_GROUP_RESPONSE.getBytes());
 
 172                 } else if (method.equals("POST")) {
 
 173                     if(uri.equals(GITLAB_TOKEN_ENDPOINT)){
 
 174                         t.sendResponseHeaders(200, GITLAB_TOKEN_RESPONSE.length());
 
 175                         os = t.getResponseBody();
 
 176                         os.write(GITLAB_TOKEN_RESPONSE.getBytes());
 
 179                         t.sendResponseHeaders(404, 0);
 
 182                     t.sendResponseHeaders(404, 0);
 
 184                 System.out.println("req handled successful");
 
 186             } catch (Exception e) {
 
 187                 System.out.println(e.getMessage());