You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GenerateActionTest.java 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.server.usertoken.ws;
  21. import javax.annotation.Nullable;
  22. import org.junit.Before;
  23. import org.junit.Rule;
  24. import org.junit.Test;
  25. import org.junit.rules.ExpectedException;
  26. import org.sonar.api.utils.System2;
  27. import org.sonar.db.DbTester;
  28. import org.sonar.db.user.UserDto;
  29. import org.sonar.server.exceptions.BadRequestException;
  30. import org.sonar.server.exceptions.ForbiddenException;
  31. import org.sonar.server.exceptions.NotFoundException;
  32. import org.sonar.server.exceptions.ServerException;
  33. import org.sonar.server.exceptions.UnauthorizedException;
  34. import org.sonar.server.tester.UserSessionRule;
  35. import org.sonar.server.usertoken.TokenGenerator;
  36. import org.sonar.server.ws.TestRequest;
  37. import org.sonar.server.ws.WsActionTester;
  38. import org.sonarqube.ws.MediaTypes;
  39. import org.sonarqube.ws.UserTokens.GenerateWsResponse;
  40. import static org.assertj.core.api.Assertions.assertThat;
  41. import static org.mockito.ArgumentMatchers.anyString;
  42. import static org.mockito.Mockito.mock;
  43. import static org.mockito.Mockito.when;
  44. import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN;
  45. import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_NAME;
  46. import static org.sonar.test.JsonAssert.assertJson;
  47. public class GenerateActionTest {
  48. private static final String TOKEN_NAME = "Third Party Application";
  49. @Rule
  50. public DbTester db = DbTester.create(System2.INSTANCE);
  51. @Rule
  52. public UserSessionRule userSession = UserSessionRule.standalone();
  53. @Rule
  54. public ExpectedException expectedException = ExpectedException.none();
  55. private TokenGenerator tokenGenerator = mock(TokenGenerator.class);
  56. private WsActionTester ws = new WsActionTester(
  57. new GenerateAction(db.getDbClient(), System2.INSTANCE, tokenGenerator, new UserTokenSupport(db.getDbClient(), userSession)));
  58. @Before
  59. public void setUp() {
  60. when(tokenGenerator.generate()).thenReturn("123456789");
  61. when(tokenGenerator.hash(anyString())).thenReturn("987654321");
  62. }
  63. @Test
  64. public void json_example() {
  65. UserDto user1 = db.users().insertUser(u -> u.setLogin("grace.hopper"));
  66. UserDto user2 = db.users().insertUser(u -> u.setLogin("ada.lovelace"));
  67. logInAsSystemAdministrator();
  68. String response = ws.newRequest()
  69. .setMediaType(MediaTypes.JSON)
  70. .setParam(PARAM_LOGIN, user1.getLogin())
  71. .setParam(PARAM_NAME, TOKEN_NAME)
  72. .execute().getInput();
  73. assertJson(response).ignoreFields("createdAt").isSimilarTo(getClass().getResource("generate-example.json"));
  74. }
  75. @Test
  76. public void a_user_can_generate_token_for_himself() {
  77. UserDto user = db.users().insertUser();
  78. userSession.logIn(user);
  79. GenerateWsResponse response = newRequest(null, TOKEN_NAME);
  80. assertThat(response.getLogin()).isEqualTo(user.getLogin());
  81. assertThat(response.getCreatedAt()).isNotEmpty();
  82. }
  83. @Test
  84. public void fail_if_login_does_not_exist() {
  85. logInAsSystemAdministrator();
  86. expectedException.expect(NotFoundException.class);
  87. expectedException.expectMessage("User with login 'unknown-login' doesn't exist");
  88. newRequest("unknown-login", "any-name");
  89. }
  90. @Test
  91. public void fail_if_name_is_blank() {
  92. UserDto user = db.users().insertUser();
  93. logInAsSystemAdministrator();
  94. expectedException.expect(IllegalArgumentException.class);
  95. expectedException.expectMessage("The 'name' parameter is missing");
  96. newRequest(user.getLogin(), " ");
  97. }
  98. @Test
  99. public void fail_if_token_with_same_login_and_name_exists() {
  100. UserDto user = db.users().insertUser();
  101. logInAsSystemAdministrator();
  102. db.users().insertToken(user, t -> t.setName(TOKEN_NAME));
  103. expectedException.expect(BadRequestException.class);
  104. expectedException.expectMessage(String.format("A user token for login '%s' and name 'Third Party Application' already exists", user.getLogin()));
  105. newRequest(user.getLogin(), TOKEN_NAME);
  106. }
  107. @Test
  108. public void fail_if_token_hash_already_exists_in_db() {
  109. UserDto user = db.users().insertUser();
  110. logInAsSystemAdministrator();
  111. when(tokenGenerator.hash(anyString())).thenReturn("987654321");
  112. db.users().insertToken(user, t -> t.setTokenHash("987654321"));
  113. expectedException.expect(ServerException.class);
  114. expectedException.expectMessage("Error while generating token. Please try again.");
  115. newRequest(user.getLogin(), TOKEN_NAME);
  116. }
  117. @Test
  118. public void throw_ForbiddenException_if_non_administrator_creates_token_for_someone_else() {
  119. UserDto user = db.users().insertUser();
  120. userSession.logIn().setNonSystemAdministrator();
  121. expectedException.expect(ForbiddenException.class);
  122. newRequest(user.getLogin(), TOKEN_NAME);
  123. }
  124. @Test
  125. public void throw_UnauthorizedException_if_not_logged_in() {
  126. UserDto user = db.users().insertUser();
  127. userSession.anonymous();
  128. expectedException.expect(UnauthorizedException.class);
  129. newRequest(user.getLogin(), TOKEN_NAME);
  130. }
  131. private GenerateWsResponse newRequest(@Nullable String login, String name) {
  132. TestRequest testRequest = ws.newRequest()
  133. .setParam(PARAM_NAME, name);
  134. if (login != null) {
  135. testRequest.setParam(PARAM_LOGIN, login);
  136. }
  137. return testRequest.executeProtobuf(GenerateWsResponse.class);
  138. }
  139. private void logInAsSystemAdministrator() {
  140. userSession.logIn().setSystemAdministrator();
  141. }
  142. }