]> source.dussan.org Git - sonarqube.git/blob
346090977b9119c166ddfff7d97897124b035e17
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2024 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.alm.client.github;
21
22 import com.tngtech.java.junit.dataprovider.DataProvider;
23 import com.tngtech.java.junit.dataprovider.DataProviderRunner;
24 import com.tngtech.java.junit.dataprovider.UseDataProvider;
25 import java.io.IOException;
26 import java.nio.charset.StandardCharsets;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.function.Function;
31 import javax.annotation.Nullable;
32 import org.apache.commons.io.IOUtils;
33 import org.junit.Before;
34 import org.junit.ClassRule;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.mockito.ArgumentCaptor;
38 import org.slf4j.event.Level;
39 import org.sonar.alm.client.ApplicationHttpClient.RateLimit;
40 import org.sonar.auth.github.GsonRepositoryCollaborator;
41 import org.sonar.auth.github.GsonRepositoryTeam;
42 import org.sonar.auth.github.AppInstallationToken;
43 import org.sonar.auth.github.GithubAppConfiguration;
44 import org.sonar.auth.github.GithubAppInstallation;
45 import org.sonar.auth.github.GithubBinding;
46 import org.sonar.auth.github.security.AccessToken;
47 import org.sonar.alm.client.github.security.AppToken;
48 import org.sonar.alm.client.github.security.GithubAppSecurity;
49 import org.sonar.auth.github.security.UserAccessToken;
50 import org.sonar.api.testfixtures.log.LogAndArguments;
51 import org.sonar.api.testfixtures.log.LogTester;
52 import org.sonar.api.utils.log.LoggerLevel;
53 import org.sonar.auth.github.GitHubSettings;
54 import org.sonar.auth.github.GsonRepositoryPermissions;
55 import org.sonar.auth.github.client.GithubApplicationClient;
56 import org.sonarqube.ws.client.HttpException;
57
58 import static java.net.HttpURLConnection.HTTP_CREATED;
59 import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
60 import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
61 import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
62 import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
63 import static org.assertj.core.api.Assertions.assertThat;
64 import static org.assertj.core.api.Assertions.assertThatCode;
65 import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
66 import static org.assertj.core.api.Assertions.assertThatThrownBy;
67 import static org.assertj.core.groups.Tuple.tuple;
68 import static org.mockito.ArgumentMatchers.any;
69 import static org.mockito.ArgumentMatchers.anyString;
70 import static org.mockito.ArgumentMatchers.eq;
71 import static org.mockito.Mockito.mock;
72 import static org.mockito.Mockito.verify;
73 import static org.mockito.Mockito.when;
74 import static org.sonar.alm.client.ApplicationHttpClient.GetResponse;
75
76 @RunWith(DataProviderRunner.class)
77 public class GithubApplicationClientImplTest {
78   private static final String ORG_NAME = "ORG_NAME";
79   private static final String TEAM_NAME = "team1";
80   private static final String REPO_NAME = "repo1";
81   private static final String APP_URL = "https://github.com/";
82   private static final String REPO_TEAMS_ENDPOINT = "/repos/ORG_NAME/repo1/teams";
83   private static final String REPO_COLLABORATORS_ENDPOINT = "/repos/ORG_NAME/repo1/collaborators?affiliation=direct";
84   private static final int INSTALLATION_ID = 1;
85   private static final String APP_JWT_TOKEN = "APP_TOKEN_JWT";
86   private static final String PAYLOAD_2_ORGS = """
87     [
88       {
89         "id": 1,
90         "account": {
91           "login": "org1",
92           "type": "Organization"
93         },
94         "target_type": "Organization",
95         "permissions": {
96           "members": "read",
97           "metadata": "read"
98         },
99         "suspended_at": "2023-05-30T08:40:55Z"
100       },
101       {
102         "id": 2,
103         "account": {
104           "login": "org2",
105           "type": "Organization"
106         },
107         "target_type": "Organization",
108         "permissions": {
109           "members": "read",
110           "metadata": "read"
111         }
112       }
113     ]""";
114
115   private static final RateLimit RATE_LIMIT = new RateLimit(Integer.MAX_VALUE, Integer.MAX_VALUE, 0L);
116
117   @ClassRule
118   public static LogTester logTester = new LogTester().setLevel(LoggerLevel.WARN);
119
120   private GithubApplicationHttpClient githubApplicationHttpClient = mock();
121   private GithubAppSecurity appSecurity = mock();
122   private GithubAppConfiguration githubAppConfiguration = mock();
123   private GitHubSettings gitHubSettings = mock();
124
125   private GithubPaginatedHttpClient githubPaginatedHttpClient = mock();
126   private AppInstallationToken appInstallationToken = mock();
127   private GithubApplicationClient underTest;
128
129
130   private String appUrl = "Any URL";
131
132   @Before
133   public void setup() {
134     when(githubAppConfiguration.getApiEndpoint()).thenReturn(appUrl);
135     underTest = new GithubApplicationClientImpl(githubApplicationHttpClient, appSecurity, gitHubSettings, githubPaginatedHttpClient);
136     logTester.clear();
137   }
138
139   @Test
140   @UseDataProvider("invalidApiEndpoints")
141   public void checkApiEndpoint_Invalid(String url, String expectedMessage) {
142     GithubAppConfiguration configuration = new GithubAppConfiguration(1L, "", url);
143
144     assertThatThrownBy(() -> underTest.checkApiEndpoint(configuration))
145       .isInstanceOf(IllegalArgumentException.class)
146       .hasMessage(expectedMessage);
147   }
148
149   @DataProvider
150   public static Object[][] invalidApiEndpoints() {
151     return new Object[][] {
152       {"", "Missing URL"},
153       {"ftp://api.github.com", "Only http and https schemes are supported"},
154       {"https://github.com", "Invalid GitHub URL"}
155     };
156   }
157
158   @Test
159   @UseDataProvider("validApiEndpoints")
160   public void checkApiEndpoint(String url) {
161     GithubAppConfiguration configuration = new GithubAppConfiguration(1L, "", url);
162
163     assertThatCode(() -> underTest.checkApiEndpoint(configuration)).isNull();
164   }
165
166   @DataProvider
167   public static Object[][] validApiEndpoints() {
168     return new Object[][] {
169       {"https://github.sonarsource.com/api/v3"},
170       {"https://api.github.com"},
171       {"https://github.sonarsource.com/api/v3/"},
172       {"https://api.github.com/"},
173       {"HTTPS://api.github.com/"},
174       {"HTTP://api.github.com/"},
175       {"HtTpS://github.SonarSource.com/api/v3"},
176       {"HtTpS://github.sonarsource.com/api/V3"},
177       {"HtTpS://github.sonarsource.COM/ApI/v3"}
178     };
179   }
180
181   @Test
182   public void checkAppPermissions_IOException() throws IOException {
183     AppToken appToken = mockAppToken();
184
185     when(githubApplicationHttpClient.get(appUrl, appToken, "/app")).thenThrow(new IOException("OOPS"));
186
187     assertThatThrownBy(() -> underTest.checkAppPermissions(githubAppConfiguration))
188       .isInstanceOf(IllegalArgumentException.class)
189       .hasMessage("Failed to validate configuration, check URL and Private Key");
190   }
191
192   @Test
193   @UseDataProvider("checkAppPermissionsErrorCodes")
194   public void checkAppPermissions_ErrorCodes(int errorCode, String expectedMessage) throws IOException {
195     AppToken appToken = mockAppToken();
196
197     when(githubApplicationHttpClient.get(appUrl, appToken, "/app")).thenReturn(new ErrorGetResponse(errorCode, null));
198
199     assertThatThrownBy(() -> underTest.checkAppPermissions(githubAppConfiguration))
200       .isInstanceOf(IllegalArgumentException.class)
201       .hasMessage(expectedMessage);
202   }
203
204   @DataProvider
205   public static Object[][] checkAppPermissionsErrorCodes() {
206     return new Object[][] {
207       {HTTP_UNAUTHORIZED, "Authentication failed, verify the Client Id, Client Secret and Private Key fields"},
208       {HTTP_FORBIDDEN, "Authentication failed, verify the Client Id, Client Secret and Private Key fields"},
209       {HTTP_NOT_FOUND, "Failed to check permissions with Github, check the configuration"}
210     };
211   }
212
213   @Test
214   public void checkAppPermissions_MissingPermissions() throws IOException {
215     AppToken appToken = mockAppToken();
216
217     when(githubApplicationHttpClient.get(appUrl, appToken, "/app")).thenReturn(new OkGetResponse("{}"));
218
219     assertThatThrownBy(() -> underTest.checkAppPermissions(githubAppConfiguration))
220       .isInstanceOf(IllegalArgumentException.class)
221       .hasMessage("Failed to get app permissions, unexpected response body");
222   }
223
224   @Test
225   public void checkAppPermissions_IncorrectPermissions() throws IOException {
226     AppToken appToken = mockAppToken();
227
228     String json = "{"
229                   + "      \"permissions\": {\n"
230                   + "        \"checks\": \"read\",\n"
231                   + "        \"metadata\": \"read\",\n"
232                   + "        \"pull_requests\": \"read\"\n"
233                   + "      }\n"
234                   + "}";
235
236     when(githubApplicationHttpClient.get(appUrl, appToken, "/app")).thenReturn(new OkGetResponse(json));
237
238     assertThatThrownBy(() -> underTest.checkAppPermissions(githubAppConfiguration))
239       .isInstanceOf(IllegalArgumentException.class)
240       .hasMessage("Missing permissions; permission granted on pull_requests is 'read', should be 'write', checks is 'read', should be 'write'");
241   }
242
243   @Test
244   public void checkAppPermissions() throws IOException {
245     AppToken appToken = mockAppToken();
246
247     String json = "{"
248                   + "      \"permissions\": {\n"
249                   + "        \"checks\": \"write\",\n"
250                   + "        \"metadata\": \"read\",\n"
251                   + "        \"pull_requests\": \"write\"\n"
252                   + "      }\n"
253                   + "}";
254
255     when(githubApplicationHttpClient.get(appUrl, appToken, "/app")).thenReturn(new OkGetResponse(json));
256
257     assertThatCode(() -> underTest.checkAppPermissions(githubAppConfiguration)).isNull();
258   }
259
260   @Test
261   public void getInstallationId_returns_installation_id_of_given_account() throws IOException {
262     AppToken appToken = new AppToken(APP_JWT_TOKEN);
263     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
264     when(githubApplicationHttpClient.get(appUrl, appToken, "/repos/torvalds/linux/installation"))
265       .thenReturn(new OkGetResponse("{" +
266         "  \"id\": 2," +
267         "  \"account\": {" +
268         "    \"login\": \"torvalds\"" +
269         "  }" +
270         "}"));
271
272     assertThat(underTest.getInstallationId(githubAppConfiguration, "torvalds/linux")).hasValue(2L);
273   }
274
275   @Test
276   public void getInstallationId_throws_IAE_if_fail_to_create_app_token() {
277     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenThrow(IllegalArgumentException.class);
278
279     assertThatThrownBy(() -> underTest.getInstallationId(githubAppConfiguration, "torvalds"))
280       .isInstanceOf(IllegalArgumentException.class);
281   }
282
283   @Test
284   public void getInstallationId_return_empty_if_no_installation_found_for_githubAccount() throws IOException {
285     AppToken appToken = new AppToken(APP_JWT_TOKEN);
286     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
287     when(githubApplicationHttpClient.get(appUrl, appToken, "/repos/torvalds/linux/installation"))
288       .thenReturn(new ErrorGetResponse(404, null));
289
290     assertThat(underTest.getInstallationId(githubAppConfiguration, "torvalds")).isEmpty();
291   }
292
293   @Test
294   @UseDataProvider("githubServers")
295   public void createUserAccessToken_returns_empty_if_access_token_cant_be_created(String apiUrl, String appUrl) throws IOException {
296     when(githubApplicationHttpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
297       .thenReturn(new Response(400, null));
298
299     assertThatThrownBy(() -> underTest.createUserAccessToken(appUrl, "clientId", "clientSecret", "code"))
300       .isInstanceOf(IllegalStateException.class);
301     verify(githubApplicationHttpClient).post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code");
302   }
303
304   @Test
305   @UseDataProvider("githubServers")
306   public void createUserAccessToken_fail_if_access_token_request_fails(String apiUrl, String appUrl) throws IOException {
307     when(githubApplicationHttpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
308       .thenThrow(new IOException("OOPS"));
309
310     assertThatThrownBy(() -> underTest.createUserAccessToken(apiUrl, "clientId", "clientSecret", "code"))
311       .isInstanceOf(IllegalStateException.class)
312       .hasMessage("Failed to create GitHub's user access token");
313
314     verify(githubApplicationHttpClient).post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code");
315   }
316
317   @Test
318   @UseDataProvider("githubServers")
319   public void createUserAccessToken_throws_illegal_argument_exception_if_access_token_code_is_expired(String apiUrl, String appUrl) throws IOException {
320     when(githubApplicationHttpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
321       .thenReturn(new OkGetResponse("error_code=100&error=expired_or_invalid"));
322
323     assertThatThrownBy(() -> underTest.createUserAccessToken(apiUrl, "clientId", "clientSecret", "code"))
324       .isInstanceOf(IllegalArgumentException.class);
325
326     verify(githubApplicationHttpClient).post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code");
327   }
328
329   @Test
330   @UseDataProvider("githubServers")
331   public void createUserAccessToken_from_authorization_code_returns_access_token(String apiUrl, String appUrl) throws IOException {
332     String token = randomAlphanumeric(10);
333     when(githubApplicationHttpClient.post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code"))
334       .thenReturn(new OkGetResponse("access_token=" + token + "&status="));
335
336     UserAccessToken userAccessToken = underTest.createUserAccessToken(apiUrl, "clientId", "clientSecret", "code");
337
338     assertThat(userAccessToken)
339       .extracting(UserAccessToken::getValue, UserAccessToken::getAuthorizationHeaderPrefix)
340       .containsOnly(token, "token");
341     verify(githubApplicationHttpClient).post(appUrl, null, "/login/oauth/access_token?client_id=clientId&client_secret=clientSecret&code=code");
342   }
343
344   @Test
345   public void getApp_returns_id() throws IOException {
346     AppToken appToken = new AppToken(APP_JWT_TOKEN);
347     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
348     when(githubApplicationHttpClient.get(appUrl, appToken, "/app"))
349       .thenReturn(new OkGetResponse("{\"installations_count\": 2}"));
350
351     assertThat(underTest.getApp(githubAppConfiguration).getInstallationsCount()).isEqualTo(2L);
352   }
353
354   @Test
355   public void getApp_whenStatusCodeIsNotOk_shouldThrowHttpException() throws IOException {
356     AppToken appToken = new AppToken(APP_JWT_TOKEN);
357     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
358     when(githubApplicationHttpClient.get(appUrl, appToken, "/app"))
359       .thenReturn(new ErrorGetResponse(418, "I'm a teapot"));
360
361     assertThatThrownBy(() -> underTest.getApp(githubAppConfiguration))
362       .isInstanceOfSatisfying(HttpException.class, httpException -> {
363         assertThat(httpException.code()).isEqualTo(418);
364         assertThat(httpException.url()).isEqualTo("Any URL/app");
365         assertThat(httpException.content()).isEqualTo("I'm a teapot");
366       });
367   }
368
369   @DataProvider
370   public static Object[][] githubServers() {
371     return new Object[][] {
372       {"https://github.sonarsource.com/api/v3", "https://github.sonarsource.com"},
373       {"https://api.github.com", "https://github.com"},
374       {"https://github.sonarsource.com/api/v3/", "https://github.sonarsource.com"},
375       {"https://api.github.com/", "https://github.com"},
376     };
377   }
378
379   @Test
380   public void listOrganizations_fail_on_failure() throws IOException {
381     String appUrl = "https://github.sonarsource.com";
382     AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
383
384     when(githubApplicationHttpClient.get(appUrl, accessToken, String.format("/user/installations?page=%s&per_page=%s", 1, 100)))
385       .thenThrow(new IOException("OOPS"));
386
387     assertThatThrownBy(() -> underTest.listOrganizations(appUrl, accessToken, 1, 100))
388       .isInstanceOf(IllegalStateException.class)
389       .hasMessage("Failed to list all organizations accessible by user access token on %s", appUrl);
390   }
391
392   @Test
393   public void listOrganizations_fail_if_pageIndex_out_of_bounds() {
394     UserAccessToken token = new UserAccessToken("token");
395     assertThatThrownBy(() -> underTest.listOrganizations(appUrl, token, 0, 100))
396       .isInstanceOf(IllegalArgumentException.class)
397       .hasMessage("'page' must be larger than 0.");
398   }
399
400   @Test
401   public void listOrganizations_fail_if_pageSize_out_of_bounds() {
402     UserAccessToken token = new UserAccessToken("token");
403     assertThatThrownBy(() -> underTest.listOrganizations(appUrl, token, 1, 0))
404       .isInstanceOf(IllegalArgumentException.class)
405       .hasMessage("'pageSize' must be a value larger than 0 and smaller or equal to 100.");
406     assertThatThrownBy(() -> underTest.listOrganizations("", token, 1, 101))
407       .isInstanceOf(IllegalArgumentException.class)
408       .hasMessage("'pageSize' must be a value larger than 0 and smaller or equal to 100.");
409   }
410
411   @Test
412   public void listOrganizations_returns_no_installations() throws IOException {
413     String appUrl = "https://github.sonarsource.com";
414     AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
415     String responseJson = "{\n"
416                           + "  \"total_count\": 0\n"
417                           + "} ";
418
419     when(githubApplicationHttpClient.get(appUrl, accessToken, String.format("/user/installations?page=%s&per_page=%s", 1, 100)))
420       .thenReturn(new OkGetResponse(responseJson));
421
422     GithubApplicationClient.Organizations organizations = underTest.listOrganizations(appUrl, accessToken, 1, 100);
423
424     assertThat(organizations.getTotal()).isZero();
425     assertThat(organizations.getOrganizations()).isNull();
426   }
427
428   @Test
429   public void listOrganizations_returns_pages_results() throws IOException {
430     String appUrl = "https://github.sonarsource.com";
431     AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
432     String responseJson = "{\n"
433                           + "  \"total_count\": 2,\n"
434                           + "  \"installations\": [\n"
435                           + "    {\n"
436                           + "      \"id\": 1,\n"
437                           + "      \"account\": {\n"
438                           + "        \"login\": \"github\",\n"
439                           + "        \"id\": 1,\n"
440                           + "        \"node_id\": \"MDEyOk9yZ2FuaXphdGlvbjE=\",\n"
441                           + "        \"url\": \"https://github.sonarsource.com/api/v3/orgs/github\",\n"
442                           + "        \"repos_url\": \"https://github.sonarsource.com/api/v3/orgs/github/repos\",\n"
443                           + "        \"events_url\": \"https://github.sonarsource.com/api/v3/orgs/github/events\",\n"
444                           + "        \"hooks_url\": \"https://github.sonarsource.com/api/v3/orgs/github/hooks\",\n"
445                           + "        \"issues_url\": \"https://github.sonarsource.com/api/v3/orgs/github/issues\",\n"
446                           + "        \"members_url\": \"https://github.sonarsource.com/api/v3/orgs/github/members{/member}\",\n"
447                           + "        \"public_members_url\": \"https://github.sonarsource.com/api/v3/orgs/github/public_members{/member}\",\n"
448                           + "        \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n"
449                           + "        \"description\": \"A great organization\"\n"
450                           + "      },\n"
451                           + "      \"access_tokens_url\": \"https://github.sonarsource.com/api/v3/app/installations/1/access_tokens\",\n"
452                           + "      \"repositories_url\": \"https://github.sonarsource.com/api/v3/installation/repositories\",\n"
453                           + "      \"html_url\": \"https://github.com/organizations/github/settings/installations/1\",\n"
454                           + "      \"app_id\": 1,\n"
455                           + "      \"target_id\": 1,\n"
456                           + "      \"target_type\": \"Organization\",\n"
457                           + "      \"permissions\": {\n"
458                           + "        \"checks\": \"write\",\n"
459                           + "        \"metadata\": \"read\",\n"
460                           + "        \"contents\": \"read\"\n"
461                           + "      },\n"
462                           + "      \"events\": [\n"
463                           + "        \"push\",\n"
464                           + "        \"pull_request\"\n"
465                           + "      ],\n"
466                           + "      \"single_file_name\": \"config.yml\"\n"
467                           + "    },\n"
468                           + "    {\n"
469                           + "      \"id\": 3,\n"
470                           + "      \"account\": {\n"
471                           + "        \"login\": \"octocat\",\n"
472                           + "        \"id\": 2,\n"
473                           + "        \"node_id\": \"MDQ6VXNlcjE=\",\n"
474                           + "        \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n"
475                           + "        \"gravatar_id\": \"\",\n"
476                           + "        \"url\": \"https://github.sonarsource.com/api/v3/users/octocat\",\n"
477                           + "        \"html_url\": \"https://github.com/octocat\",\n"
478                           + "        \"followers_url\": \"https://github.sonarsource.com/api/v3/users/octocat/followers\",\n"
479                           + "        \"following_url\": \"https://github.sonarsource.com/api/v3/users/octocat/following{/other_user}\",\n"
480                           + "        \"gists_url\": \"https://github.sonarsource.com/api/v3/users/octocat/gists{/gist_id}\",\n"
481                           + "        \"starred_url\": \"https://github.sonarsource.com/api/v3/users/octocat/starred{/owner}{/repo}\",\n"
482                           + "        \"subscriptions_url\": \"https://github.sonarsource.com/api/v3/users/octocat/subscriptions\",\n"
483                           + "        \"organizations_url\": \"https://github.sonarsource.com/api/v3/users/octocat/orgs\",\n"
484                           + "        \"repos_url\": \"https://github.sonarsource.com/api/v3/users/octocat/repos\",\n"
485                           + "        \"events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/events{/privacy}\",\n"
486                           + "        \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/received_events\",\n"
487                           + "        \"type\": \"User\",\n"
488                           + "        \"site_admin\": false\n"
489                           + "      },\n"
490                           + "      \"access_tokens_url\": \"https://github.sonarsource.com/api/v3/app/installations/1/access_tokens\",\n"
491                           + "      \"repositories_url\": \"https://github.sonarsource.com/api/v3/installation/repositories\",\n"
492                           + "      \"html_url\": \"https://github.com/organizations/github/settings/installations/1\",\n"
493                           + "      \"app_id\": 1,\n"
494                           + "      \"target_id\": 1,\n"
495                           + "      \"target_type\": \"Organization\",\n"
496                           + "      \"permissions\": {\n"
497                           + "        \"checks\": \"write\",\n"
498                           + "        \"metadata\": \"read\",\n"
499                           + "        \"contents\": \"read\"\n"
500                           + "      },\n"
501                           + "      \"events\": [\n"
502                           + "        \"push\",\n"
503                           + "        \"pull_request\"\n"
504                           + "      ],\n"
505                           + "      \"single_file_name\": \"config.yml\"\n"
506                           + "    }\n"
507                           + "  ]\n"
508                           + "} ";
509
510     when(githubApplicationHttpClient.get(appUrl, accessToken, String.format("/user/installations?page=%s&per_page=%s", 1, 100)))
511       .thenReturn(new OkGetResponse(responseJson));
512
513     GithubApplicationClient.Organizations organizations = underTest.listOrganizations(appUrl, accessToken, 1, 100);
514
515     assertThat(organizations.getTotal()).isEqualTo(2);
516     assertThat(organizations.getOrganizations()).extracting(GithubApplicationClient.Organization::getLogin).containsOnly("github", "octocat");
517   }
518
519   @Test
520   public void getWhitelistedGithubAppInstallations_whenWhitelistNotSpecified_doesNotFilter() throws IOException {
521     List<GithubAppInstallation> allOrgInstallations = getGithubAppInstallationsFromGithubResponse(PAYLOAD_2_ORGS);
522     assertOrgDeserialization(allOrgInstallations);
523   }
524
525   private static void assertOrgDeserialization(List<GithubAppInstallation> orgs) {
526     GithubAppInstallation org1 = orgs.get(0);
527     assertThat(org1.installationId()).isEqualTo("1");
528     assertThat(org1.organizationName()).isEqualTo("org1");
529     assertThat(org1.permissions().getMembers()).isEqualTo("read");
530     assertThat(org1.isSuspended()).isTrue();
531
532     GithubAppInstallation org2 = orgs.get(1);
533     assertThat(org2.installationId()).isEqualTo("2");
534     assertThat(org2.organizationName()).isEqualTo("org2");
535     assertThat(org2.permissions().getMembers()).isEqualTo("read");
536     assertThat(org2.isSuspended()).isFalse();
537   }
538
539   @Test
540   public void getWhitelistedGithubAppInstallations_whenWhitelistSpecified_filtersWhitelistedOrgs() throws IOException {
541     when(gitHubSettings.getOrganizations()).thenReturn(Set.of("org2"));
542     List<GithubAppInstallation> orgInstallations = getGithubAppInstallationsFromGithubResponse(PAYLOAD_2_ORGS);
543     assertThat(orgInstallations)
544       .hasSize(1)
545       .extracting(GithubAppInstallation::organizationName)
546       .containsExactlyInAnyOrder("org2");
547   }
548
549   @Test
550   public void getWhitelistedGithubAppInstallations_whenEmptyResponse_shouldReturnEmpty() throws IOException {
551     List<GithubAppInstallation> allOrgInstallations = getGithubAppInstallationsFromGithubResponse("[]");
552     assertThat(allOrgInstallations).isEmpty();
553   }
554
555   @Test
556   public void getWhitelistedGithubAppInstallations_whenNoOrganization_shouldReturnEmpty() throws IOException {
557     List<GithubAppInstallation> allOrgInstallations = getGithubAppInstallationsFromGithubResponse("""
558       [
559         {
560           "id": 1,
561           "account": {
562             "login": "user1",
563             "type": "User"
564           },
565           "target_type": "User",
566           "permissions": {
567             "metadata": "read"
568           }
569         }
570       ]""");
571     assertThat(allOrgInstallations).isEmpty();
572   }
573
574   @SuppressWarnings("unchecked")
575   private List<GithubAppInstallation> getGithubAppInstallationsFromGithubResponse(String content) throws IOException {
576     AppToken appToken = new AppToken(APP_JWT_TOKEN);
577     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
578     when(githubPaginatedHttpClient.get(eq(appUrl), eq(appToken), eq("/app/installations"), any()))
579       .thenAnswer(invocation -> {
580         Function<String, List<GithubBinding.GsonInstallation>> deserializingFunction = invocation.getArgument(3, Function.class);
581         return deserializingFunction.apply(content);
582       });
583     return underTest.getWhitelistedGithubAppInstallations(githubAppConfiguration);
584   }
585
586   @Test
587   public void getWhitelistedGithubAppInstallations_whenGithubReturnsError_shouldReThrow() {
588     AppToken appToken = new AppToken(APP_JWT_TOKEN);
589     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(appToken);
590     when(githubPaginatedHttpClient.get(any(), any(), any(), any())).thenThrow(new IllegalStateException("exception"));
591
592     assertThatThrownBy(() -> underTest.getWhitelistedGithubAppInstallations(githubAppConfiguration))
593       .isInstanceOf(IllegalStateException.class)
594       .hasMessage("exception");
595   }
596
597   @Test
598   public void listRepositories_fail_on_failure() throws IOException {
599     String appUrl = "https://github.sonarsource.com";
600     AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
601
602     when(githubApplicationHttpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "org:test", 1, 100)))
603       .thenThrow(new IOException("OOPS"));
604
605     assertThatThrownBy(() -> underTest.listRepositories(appUrl, accessToken, "test", null, 1, 100))
606       .isInstanceOf(IllegalStateException.class)
607       .hasMessage("Failed to list all repositories of 'test' accessible by user access token on 'https://github.sonarsource.com' using query 'fork:true+org:test'");
608   }
609
610   @Test
611   public void listRepositories_fail_if_pageIndex_out_of_bounds() {
612     UserAccessToken token = new UserAccessToken("token");
613     assertThatThrownBy(() -> underTest.listRepositories(appUrl, token, "test", null, 0, 100))
614       .isInstanceOf(IllegalArgumentException.class)
615       .hasMessage("'page' must be larger than 0.");
616   }
617
618   @Test
619   public void listRepositories_fail_if_pageSize_out_of_bounds() {
620     UserAccessToken token = new UserAccessToken("token");
621     assertThatThrownBy(() -> underTest.listRepositories(appUrl, token, "test", null, 1, 0))
622       .isInstanceOf(IllegalArgumentException.class)
623       .hasMessage("'pageSize' must be a value larger than 0 and smaller or equal to 100.");
624     assertThatThrownBy(() -> underTest.listRepositories("", token, "test", null, 1, 101))
625       .isInstanceOf(IllegalArgumentException.class)
626       .hasMessage("'pageSize' must be a value larger than 0 and smaller or equal to 100.");
627   }
628
629   @Test
630   public void listRepositories_returns_empty_results() throws IOException {
631     String appUrl = "https://github.sonarsource.com";
632     AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
633     String responseJson = "{\n"
634                           + "  \"total_count\": 0\n"
635                           + "}";
636
637     when(githubApplicationHttpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "fork:true+org:github", 1, 100)))
638       .thenReturn(new OkGetResponse(responseJson));
639
640     GithubApplicationClient.Repositories repositories = underTest.listRepositories(appUrl, accessToken, "github", null, 1, 100);
641
642     assertThat(repositories.getTotal()).isZero();
643     assertThat(repositories.getRepositories()).isNull();
644   }
645
646   @Test
647   public void listRepositories_returns_pages_results() throws IOException {
648     String appUrl = "https://github.sonarsource.com";
649     AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
650     String responseJson = "{\n"
651                           + "  \"total_count\": 2,\n"
652                           + "  \"incomplete_results\": false,\n"
653                           + "  \"items\": [\n"
654                           + "    {\n"
655                           + "      \"id\": 3081286,\n"
656                           + "      \"node_id\": \"MDEwOlJlcG9zaXRvcnkzMDgxMjg2\",\n"
657                           + "      \"name\": \"HelloWorld\",\n"
658                           + "      \"full_name\": \"github/HelloWorld\",\n"
659                           + "      \"owner\": {\n"
660                           + "        \"login\": \"github\",\n"
661                           + "        \"id\": 872147,\n"
662                           + "        \"node_id\": \"MDQ6VXNlcjg3MjE0Nw==\",\n"
663                           + "        \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n"
664                           + "        \"gravatar_id\": \"\",\n"
665                           + "        \"url\": \"https://github.sonarsource.com/api/v3/users/github\",\n"
666                           + "        \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/github/received_events\",\n"
667                           + "        \"type\": \"User\"\n"
668                           + "      },\n"
669                           + "      \"private\": false,\n"
670                           + "      \"html_url\": \"https://github.com/github/HelloWorld\",\n"
671                           + "      \"description\": \"A C implementation of HelloWorld\",\n"
672                           + "      \"fork\": false,\n"
673                           + "      \"url\": \"https://github.sonarsource.com/api/v3/repos/github/HelloWorld\",\n"
674                           + "      \"created_at\": \"2012-01-01T00:31:50Z\",\n"
675                           + "      \"updated_at\": \"2013-01-05T17:58:47Z\",\n"
676                           + "      \"pushed_at\": \"2012-01-01T00:37:02Z\",\n"
677                           + "      \"homepage\": \"\",\n"
678                           + "      \"size\": 524,\n"
679                           + "      \"stargazers_count\": 1,\n"
680                           + "      \"watchers_count\": 1,\n"
681                           + "      \"language\": \"Assembly\",\n"
682                           + "      \"forks_count\": 0,\n"
683                           + "      \"open_issues_count\": 0,\n"
684                           + "      \"master_branch\": \"master\",\n"
685                           + "      \"default_branch\": \"master\",\n"
686                           + "      \"score\": 1.0\n"
687                           + "    },\n"
688                           + "    {\n"
689                           + "      \"id\": 3081286,\n"
690                           + "      \"node_id\": \"MDEwOlJlcG9zaXRvcnkzMDgxMjg2\",\n"
691                           + "      \"name\": \"HelloUniverse\",\n"
692                           + "      \"full_name\": \"github/HelloUniverse\",\n"
693                           + "      \"owner\": {\n"
694                           + "        \"login\": \"github\",\n"
695                           + "        \"id\": 872147,\n"
696                           + "        \"node_id\": \"MDQ6VXNlcjg3MjE0Nw==\",\n"
697                           + "        \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n"
698                           + "        \"gravatar_id\": \"\",\n"
699                           + "        \"url\": \"https://github.sonarsource.com/api/v3/users/github\",\n"
700                           + "        \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/github/received_events\",\n"
701                           + "        \"type\": \"User\"\n"
702                           + "      },\n"
703                           + "      \"private\": false,\n"
704                           + "      \"html_url\": \"https://github.com/github/HelloUniverse\",\n"
705                           + "      \"description\": \"A C implementation of HelloUniverse\",\n"
706                           + "      \"fork\": false,\n"
707                           + "      \"url\": \"https://github.sonarsource.com/api/v3/repos/github/HelloUniverse\",\n"
708                           + "      \"created_at\": \"2012-01-01T00:31:50Z\",\n"
709                           + "      \"updated_at\": \"2013-01-05T17:58:47Z\",\n"
710                           + "      \"pushed_at\": \"2012-01-01T00:37:02Z\",\n"
711                           + "      \"homepage\": \"\",\n"
712                           + "      \"size\": 524,\n"
713                           + "      \"stargazers_count\": 1,\n"
714                           + "      \"watchers_count\": 1,\n"
715                           + "      \"language\": \"Assembly\",\n"
716                           + "      \"forks_count\": 0,\n"
717                           + "      \"open_issues_count\": 0,\n"
718                           + "      \"master_branch\": \"master\",\n"
719                           + "      \"default_branch\": \"master\",\n"
720                           + "      \"score\": 1.0\n"
721                           + "    }\n"
722                           + "  ]\n"
723                           + "}";
724
725     when(githubApplicationHttpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "fork:true+org:github", 1, 100)))
726       .thenReturn(new OkGetResponse(responseJson));
727     GithubApplicationClient.Repositories repositories = underTest.listRepositories(appUrl, accessToken, "github", null, 1, 100);
728
729     assertThat(repositories.getTotal()).isEqualTo(2);
730     assertThat(repositories.getRepositories())
731       .extracting(GithubApplicationClient.Repository::getName, GithubApplicationClient.Repository::getFullName)
732       .containsOnly(tuple("HelloWorld", "github/HelloWorld"), tuple("HelloUniverse", "github/HelloUniverse"));
733   }
734
735   @Test
736   public void listRepositories_returns_search_results() throws IOException {
737     String appUrl = "https://github.sonarsource.com";
738     AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
739     String responseJson = "{\n"
740                           + "  \"total_count\": 2,\n"
741                           + "  \"incomplete_results\": false,\n"
742                           + "  \"items\": [\n"
743                           + "    {\n"
744                           + "      \"id\": 3081286,\n"
745                           + "      \"node_id\": \"MDEwOlJlcG9zaXRvcnkzMDgxMjg2\",\n"
746                           + "      \"name\": \"HelloWorld\",\n"
747                           + "      \"full_name\": \"github/HelloWorld\",\n"
748                           + "      \"owner\": {\n"
749                           + "        \"login\": \"github\",\n"
750                           + "        \"id\": 872147,\n"
751                           + "        \"node_id\": \"MDQ6VXNlcjg3MjE0Nw==\",\n"
752                           + "        \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n"
753                           + "        \"gravatar_id\": \"\",\n"
754                           + "        \"url\": \"https://github.sonarsource.com/api/v3/users/github\",\n"
755                           + "        \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/github/received_events\",\n"
756                           + "        \"type\": \"User\"\n"
757                           + "      },\n"
758                           + "      \"private\": false,\n"
759                           + "      \"html_url\": \"https://github.com/github/HelloWorld\",\n"
760                           + "      \"description\": \"A C implementation of HelloWorld\",\n"
761                           + "      \"fork\": false,\n"
762                           + "      \"url\": \"https://github.sonarsource.com/api/v3/repos/github/HelloWorld\",\n"
763                           + "      \"created_at\": \"2012-01-01T00:31:50Z\",\n"
764                           + "      \"updated_at\": \"2013-01-05T17:58:47Z\",\n"
765                           + "      \"pushed_at\": \"2012-01-01T00:37:02Z\",\n"
766                           + "      \"homepage\": \"\",\n"
767                           + "      \"size\": 524,\n"
768                           + "      \"stargazers_count\": 1,\n"
769                           + "      \"watchers_count\": 1,\n"
770                           + "      \"language\": \"Assembly\",\n"
771                           + "      \"forks_count\": 0,\n"
772                           + "      \"open_issues_count\": 0,\n"
773                           + "      \"master_branch\": \"master\",\n"
774                           + "      \"default_branch\": \"master\",\n"
775                           + "      \"score\": 1.0\n"
776                           + "    }\n"
777                           + "  ]\n"
778                           + "}";
779
780     when(githubApplicationHttpClient.get(appUrl, accessToken, String.format("/search/repositories?q=%s&page=%s&per_page=%s", "world+fork:true+org:github", 1, 100)))
781       .thenReturn(new GetResponse() {
782         @Override
783         public Optional<String> getNextEndPoint() {
784           return Optional.empty();
785         }
786
787         @Override
788         public int getCode() {
789           return 200;
790         }
791
792         @Override
793         public Optional<String> getContent() {
794           return Optional.of(responseJson);
795         }
796
797         @Override
798         public RateLimit getRateLimit() {
799           return RATE_LIMIT;
800         }
801       });
802
803     GithubApplicationClient.Repositories repositories = underTest.listRepositories(appUrl, accessToken, "github", "world", 1, 100);
804
805     assertThat(repositories.getTotal()).isEqualTo(2);
806     assertThat(repositories.getRepositories())
807       .extracting(GithubApplicationClient.Repository::getName, GithubApplicationClient.Repository::getFullName)
808       .containsOnly(tuple("HelloWorld", "github/HelloWorld"));
809   }
810
811   @Test
812   public void getRepository_returns_empty_when_repository_doesnt_exist() throws IOException {
813     when(githubApplicationHttpClient.get(any(), any(), any()))
814       .thenReturn(new Response(404, null));
815
816     Optional<GithubApplicationClient.Repository> repository = underTest.getRepository(appUrl, new UserAccessToken("temp"), "octocat/Hello-World");
817
818     assertThat(repository).isEmpty();
819   }
820
821   @Test
822   public void getRepository_fails_on_failure() throws IOException {
823     String repositoryKey = "octocat/Hello-World";
824
825     when(githubApplicationHttpClient.get(any(), any(), any()))
826       .thenThrow(new IOException("OOPS"));
827
828     UserAccessToken token = new UserAccessToken("temp");
829     assertThatThrownBy(() -> underTest.getRepository(appUrl, token, repositoryKey))
830       .isInstanceOf(IllegalStateException.class)
831       .hasMessage("Failed to get repository 'octocat/Hello-World' on 'Any URL' (this might be related to the GitHub App installation scope)");
832   }
833
834   @Test
835   public void getRepository_returns_repository() throws IOException {
836     String appUrl = "https://github.sonarsource.com";
837     AccessToken accessToken = new UserAccessToken(randomAlphanumeric(10));
838     String responseJson = "{\n"
839                           + "  \"id\": 1296269,\n"
840                           + "  \"node_id\": \"MDEwOlJlcG9zaXRvcnkxMjk2MjY5\",\n"
841                           + "  \"name\": \"Hello-World\",\n"
842                           + "  \"full_name\": \"octocat/Hello-World\",\n"
843                           + "  \"owner\": {\n"
844                           + "    \"login\": \"octocat\",\n"
845                           + "    \"id\": 1,\n"
846                           + "    \"node_id\": \"MDQ6VXNlcjE=\",\n"
847                           + "    \"avatar_url\": \"https://github.sonarsource.com/images/error/octocat_happy.gif\",\n"
848                           + "    \"gravatar_id\": \"\",\n"
849                           + "    \"url\": \"https://github.sonarsource.com/api/v3/users/octocat\",\n"
850                           + "    \"html_url\": \"https://github.com/octocat\",\n"
851                           + "    \"followers_url\": \"https://github.sonarsource.com/api/v3/users/octocat/followers\",\n"
852                           + "    \"following_url\": \"https://github.sonarsource.com/api/v3/users/octocat/following{/other_user}\",\n"
853                           + "    \"gists_url\": \"https://github.sonarsource.com/api/v3/users/octocat/gists{/gist_id}\",\n"
854                           + "    \"starred_url\": \"https://github.sonarsource.com/api/v3/users/octocat/starred{/owner}{/repo}\",\n"
855                           + "    \"subscriptions_url\": \"https://github.sonarsource.com/api/v3/users/octocat/subscriptions\",\n"
856                           + "    \"organizations_url\": \"https://github.sonarsource.com/api/v3/users/octocat/orgs\",\n"
857                           + "    \"repos_url\": \"https://github.sonarsource.com/api/v3/users/octocat/repos\",\n"
858                           + "    \"events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/events{/privacy}\",\n"
859                           + "    \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/received_events\",\n"
860                           + "    \"type\": \"User\",\n"
861                           + "    \"site_admin\": false\n"
862                           + "  },\n"
863                           + "  \"private\": false,\n"
864                           + "  \"html_url\": \"https://github.com/octocat/Hello-World\",\n"
865                           + "  \"description\": \"This your first repo!\",\n"
866                           + "  \"fork\": false,\n"
867                           + "  \"url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World\",\n"
868                           + "  \"archive_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/{archive_format}{/ref}\",\n"
869                           + "  \"assignees_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/assignees{/user}\",\n"
870                           + "  \"blobs_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/blobs{/sha}\",\n"
871                           + "  \"branches_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/branches{/branch}\",\n"
872                           + "  \"collaborators_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/collaborators{/collaborator}\",\n"
873                           + "  \"comments_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/comments{/number}\",\n"
874                           + "  \"commits_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/commits{/sha}\",\n"
875                           + "  \"compare_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/compare/{base}...{head}\",\n"
876                           + "  \"contents_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/contents/{+path}\",\n"
877                           + "  \"contributors_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/contributors\",\n"
878                           + "  \"deployments_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/deployments\",\n"
879                           + "  \"downloads_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/downloads\",\n"
880                           + "  \"events_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/events\",\n"
881                           + "  \"forks_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/forks\",\n"
882                           + "  \"git_commits_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/commits{/sha}\",\n"
883                           + "  \"git_refs_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/refs{/sha}\",\n"
884                           + "  \"git_tags_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/tags{/sha}\",\n"
885                           + "  \"git_url\": \"git:github.com/octocat/Hello-World.git\",\n"
886                           + "  \"issue_comment_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/issues/comments{/number}\",\n"
887                           + "  \"issue_events_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/issues/events{/number}\",\n"
888                           + "  \"issues_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/issues{/number}\",\n"
889                           + "  \"keys_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/keys{/key_id}\",\n"
890                           + "  \"labels_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/labels{/name}\",\n"
891                           + "  \"languages_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/languages\",\n"
892                           + "  \"merges_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/merges\",\n"
893                           + "  \"milestones_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/milestones{/number}\",\n"
894                           + "  \"notifications_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/notifications{?since,all,participating}\",\n"
895                           + "  \"pulls_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/pulls{/number}\",\n"
896                           + "  \"releases_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/releases{/id}\",\n"
897                           + "  \"ssh_url\": \"git@github.com:octocat/Hello-World.git\",\n"
898                           + "  \"stargazers_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/stargazers\",\n"
899                           + "  \"statuses_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/statuses/{sha}\",\n"
900                           + "  \"subscribers_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/subscribers\",\n"
901                           + "  \"subscription_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/subscription\",\n"
902                           + "  \"tags_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/tags\",\n"
903                           + "  \"teams_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/teams\",\n"
904                           + "  \"trees_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/git/trees{/sha}\",\n"
905                           + "  \"clone_url\": \"https://github.com/octocat/Hello-World.git\",\n"
906                           + "  \"mirror_url\": \"git:git.example.com/octocat/Hello-World\",\n"
907                           + "  \"hooks_url\": \"https://github.sonarsource.com/api/v3/repos/octocat/Hello-World/hooks\",\n"
908                           + "  \"svn_url\": \"https://svn.github.com/octocat/Hello-World\",\n"
909                           + "  \"homepage\": \"https://github.com\",\n"
910                           + "  \"language\": null,\n"
911                           + "  \"forks_count\": 9,\n"
912                           + "  \"stargazers_count\": 80,\n"
913                           + "  \"watchers_count\": 80,\n"
914                           + "  \"size\": 108,\n"
915                           + "  \"default_branch\": \"master\",\n"
916                           + "  \"open_issues_count\": 0,\n"
917                           + "  \"is_template\": true,\n"
918                           + "  \"topics\": [\n"
919                           + "    \"octocat\",\n"
920                           + "    \"atom\",\n"
921                           + "    \"electron\",\n"
922                           + "    \"api\"\n"
923                           + "  ],\n"
924                           + "  \"has_issues\": true,\n"
925                           + "  \"has_projects\": true,\n"
926                           + "  \"has_wiki\": true,\n"
927                           + "  \"has_pages\": false,\n"
928                           + "  \"has_downloads\": true,\n"
929                           + "  \"archived\": false,\n"
930                           + "  \"disabled\": false,\n"
931                           + "  \"visibility\": \"public\",\n"
932                           + "  \"pushed_at\": \"2011-01-26T19:06:43Z\",\n"
933                           + "  \"created_at\": \"2011-01-26T19:01:12Z\",\n"
934                           + "  \"updated_at\": \"2011-01-26T19:14:43Z\",\n"
935                           + "  \"permissions\": {\n"
936                           + "    \"admin\": false,\n"
937                           + "    \"push\": false,\n"
938                           + "    \"pull\": true\n"
939                           + "  },\n"
940                           + "  \"allow_rebase_merge\": true,\n"
941                           + "  \"template_repository\": null,\n"
942                           + "  \"allow_squash_merge\": true,\n"
943                           + "  \"allow_merge_commit\": true,\n"
944                           + "  \"subscribers_count\": 42,\n"
945                           + "  \"network_count\": 0,\n"
946                           + "  \"anonymous_access_enabled\": false,\n"
947                           + "  \"license\": {\n"
948                           + "    \"key\": \"mit\",\n"
949                           + "    \"name\": \"MIT License\",\n"
950                           + "    \"spdx_id\": \"MIT\",\n"
951                           + "    \"url\": \"https://github.sonarsource.com/api/v3/licenses/mit\",\n"
952                           + "    \"node_id\": \"MDc6TGljZW5zZW1pdA==\"\n"
953                           + "  },\n"
954                           + "  \"organization\": {\n"
955                           + "    \"login\": \"octocat\",\n"
956                           + "    \"id\": 1,\n"
957                           + "    \"node_id\": \"MDQ6VXNlcjE=\",\n"
958                           + "    \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n"
959                           + "    \"gravatar_id\": \"\",\n"
960                           + "    \"url\": \"https://github.sonarsource.com/api/v3/users/octocat\",\n"
961                           + "    \"html_url\": \"https://github.com/octocat\",\n"
962                           + "    \"followers_url\": \"https://github.sonarsource.com/api/v3/users/octocat/followers\",\n"
963                           + "    \"following_url\": \"https://github.sonarsource.com/api/v3/users/octocat/following{/other_user}\",\n"
964                           + "    \"gists_url\": \"https://github.sonarsource.com/api/v3/users/octocat/gists{/gist_id}\",\n"
965                           + "    \"starred_url\": \"https://github.sonarsource.com/api/v3/users/octocat/starred{/owner}{/repo}\",\n"
966                           + "    \"subscriptions_url\": \"https://github.sonarsource.com/api/v3/users/octocat/subscriptions\",\n"
967                           + "    \"organizations_url\": \"https://github.sonarsource.com/api/v3/users/octocat/orgs\",\n"
968                           + "    \"repos_url\": \"https://github.sonarsource.com/api/v3/users/octocat/repos\",\n"
969                           + "    \"events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/events{/privacy}\",\n"
970                           + "    \"received_events_url\": \"https://github.sonarsource.com/api/v3/users/octocat/received_events\",\n"
971                           + "    \"type\": \"Organization\",\n"
972                           + "    \"site_admin\": false\n"
973                           + "  }"
974                           + "}";
975
976     when(githubApplicationHttpClient.get(appUrl, accessToken, "/repos/octocat/Hello-World"))
977       .thenReturn(new GetResponse() {
978         @Override
979         public Optional<String> getNextEndPoint() {
980           return Optional.empty();
981         }
982
983         @Override
984         public int getCode() {
985           return 200;
986         }
987
988         @Override
989         public Optional<String> getContent() {
990           return Optional.of(responseJson);
991         }
992
993         @Override
994         public RateLimit getRateLimit() {
995           return RATE_LIMIT;
996         }
997       });
998
999     Optional<GithubApplicationClient.Repository> repository = underTest.getRepository(appUrl, accessToken, "octocat/Hello-World");
1000
1001     assertThat(repository)
1002       .isPresent()
1003       .get()
1004       .extracting(GithubApplicationClient.Repository::getId, GithubApplicationClient.Repository::getName, GithubApplicationClient.Repository::getFullName,
1005         GithubApplicationClient.Repository::getUrl, GithubApplicationClient.Repository::isPrivate, GithubApplicationClient.Repository::getDefaultBranch)
1006       .containsOnly(1296269L, "Hello-World", "octocat/Hello-World", "https://github.com/octocat/Hello-World", false, "master");
1007   }
1008
1009   @Test
1010   public void createAppInstallationToken_throws_IAE_if_application_token_cant_be_created() {
1011     mockNoApplicationJwtToken();
1012
1013     assertThatThrownBy(() -> underTest.createAppInstallationToken(githubAppConfiguration, INSTALLATION_ID))
1014       .isInstanceOf(IllegalArgumentException.class);
1015   }
1016
1017   private void mockNoApplicationJwtToken() {
1018     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenThrow(IllegalArgumentException.class);
1019   }
1020
1021   @Test
1022   public void createAppInstallationToken_returns_empty_if_post_throws_IOE() throws IOException {
1023     mockAppToken();
1024     when(githubApplicationHttpClient.post(anyString(), any(AccessToken.class), anyString())).thenThrow(IOException.class);
1025     Optional<AppInstallationToken> accessToken = underTest.createAppInstallationToken(githubAppConfiguration, INSTALLATION_ID);
1026
1027     assertThat(accessToken).isEmpty();
1028     assertThat(logTester.getLogs(Level.WARN)).extracting(LogAndArguments::getRawMsg).anyMatch(s -> s.startsWith("Failed to request"));
1029   }
1030
1031   @Test
1032   public void createAppInstallationToken_returns_empty_if_access_token_cant_be_created() throws IOException {
1033     AppToken appToken = mockAppToken();
1034     mockAccessTokenCallingGithubFailure();
1035
1036     Optional<AppInstallationToken> accessToken = underTest.createAppInstallationToken(githubAppConfiguration, INSTALLATION_ID);
1037
1038     assertThat(accessToken).isEmpty();
1039     verify(githubApplicationHttpClient).post(appUrl, appToken, "/app/installations/" + INSTALLATION_ID + "/access_tokens");
1040   }
1041
1042   @Test
1043   public void createAppInstallationToken_from_installation_id_returns_access_token() throws IOException {
1044     AppToken appToken = mockAppToken();
1045     AppInstallationToken installToken = mockCreateAccessTokenCallingGithub();
1046
1047     Optional<AppInstallationToken> accessToken = underTest.createAppInstallationToken(githubAppConfiguration, INSTALLATION_ID);
1048
1049     assertThat(accessToken).hasValue(installToken);
1050     verify(githubApplicationHttpClient).post(appUrl, appToken, "/app/installations/" + INSTALLATION_ID + "/access_tokens");
1051   }
1052
1053   @Test
1054   public void getRepositoryTeams_returnsRepositoryTeams() throws IOException {
1055     ArgumentCaptor<Function<String, List<GsonRepositoryTeam>>> deserializerCaptor = ArgumentCaptor.forClass(Function.class);
1056
1057     when(githubPaginatedHttpClient.get(eq(APP_URL), eq(appInstallationToken), eq(REPO_TEAMS_ENDPOINT), deserializerCaptor.capture())).thenReturn(expectedTeams());
1058
1059     Set<GsonRepositoryTeam> repoTeams = underTest.getRepositoryTeams(APP_URL, appInstallationToken, ORG_NAME, REPO_NAME);
1060
1061     assertThat(repoTeams)
1062       .containsExactlyInAnyOrderElementsOf(expectedTeams());
1063
1064     String responseContent = getResponseContent("repo-teams-full-response.json");
1065     assertThat(deserializerCaptor.getValue().apply(responseContent)).containsExactlyElementsOf(expectedTeams());
1066   }
1067
1068   @Test
1069   public void getRepositoryTeams_whenGitHubCallThrowsException_shouldRethrow() {
1070     when(githubPaginatedHttpClient.get(eq(APP_URL), eq(appInstallationToken), eq(REPO_TEAMS_ENDPOINT), any())).thenThrow(new IllegalStateException("error"));
1071
1072     assertThatIllegalStateException()
1073       .isThrownBy(() -> underTest.getRepositoryTeams(APP_URL, appInstallationToken, ORG_NAME, REPO_NAME))
1074       .withMessage("error");
1075   }
1076
1077   private static List<GsonRepositoryTeam> expectedTeams() {
1078     return List.of(
1079       new GsonRepositoryTeam("team1", 1, "team1", "pull", new GsonRepositoryPermissions(true, true, true, true, true)),
1080       new GsonRepositoryTeam("team2", 2, "team2", "push", new GsonRepositoryPermissions(false, false, true, true, true)));
1081   }
1082
1083   @Test
1084   public void getRepositoryCollaborators_returnsCollaboratorsFromGithub() throws IOException {
1085     ArgumentCaptor<Function<String, List<GsonRepositoryCollaborator>>> deserializerCaptor = ArgumentCaptor.forClass(Function.class);
1086
1087     when(githubPaginatedHttpClient.get(eq(APP_URL), eq(appInstallationToken), eq(REPO_COLLABORATORS_ENDPOINT), deserializerCaptor.capture())).thenReturn(expectedCollaborators());
1088
1089     Set<GsonRepositoryCollaborator> repoTeams = underTest.getRepositoryCollaborators(APP_URL, appInstallationToken, ORG_NAME, REPO_NAME);
1090
1091     assertThat(repoTeams)
1092       .containsExactlyInAnyOrderElementsOf(expectedCollaborators());
1093
1094     String responseContent = getResponseContent("repo-collaborators-full-response.json");
1095     assertThat(deserializerCaptor.getValue().apply(responseContent)).containsExactlyElementsOf(expectedCollaborators());
1096
1097   }
1098
1099   @Test
1100   public void getRepositoryCollaborators_whenGitHubCallThrowsException_shouldRethrow() {
1101     when(githubPaginatedHttpClient.get(eq(APP_URL), eq(appInstallationToken), eq(REPO_COLLABORATORS_ENDPOINT), any())).thenThrow(new IllegalStateException("error"));
1102
1103     assertThatIllegalStateException()
1104       .isThrownBy(() -> underTest.getRepositoryCollaborators(APP_URL, appInstallationToken, ORG_NAME, REPO_NAME))
1105       .withMessage("error");
1106   }
1107
1108   private static String getResponseContent(String path) throws IOException {
1109     return IOUtils.toString(GithubApplicationClientImplTest.class.getResourceAsStream(path), StandardCharsets.UTF_8);
1110   }
1111
1112   private static List<GsonRepositoryCollaborator> expectedCollaborators() {
1113     return List.of(
1114       new GsonRepositoryCollaborator("jean-michel", 1, "role1", new GsonRepositoryPermissions(true, true, true, true, true)),
1115       new GsonRepositoryCollaborator("jean-pierre", 2, "role2", new GsonRepositoryPermissions(false, false, true, true, true)));
1116   }
1117
1118   private void mockAccessTokenCallingGithubFailure() throws IOException {
1119     Response response = mock(Response.class);
1120     when(response.getContent()).thenReturn(Optional.empty());
1121     when(response.getCode()).thenReturn(HTTP_UNAUTHORIZED);
1122     when(githubApplicationHttpClient.post(eq(appUrl), any(AppToken.class), eq("/app/installations/" + INSTALLATION_ID + "/access_tokens"))).thenReturn(response);
1123   }
1124
1125   private AppToken mockAppToken() {
1126     String jwt = randomAlphanumeric(5);
1127     when(appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey())).thenReturn(new AppToken(jwt));
1128     return new AppToken(jwt);
1129   }
1130
1131   private AppInstallationToken mockCreateAccessTokenCallingGithub() throws IOException {
1132     String token = randomAlphanumeric(5);
1133     Response response = mock(Response.class);
1134     when(response.getContent()).thenReturn(Optional.of("{" +
1135                                                        "  \"token\": \"" + token + "\"" +
1136                                                        "}"));
1137     when(response.getCode()).thenReturn(HTTP_CREATED);
1138     when(githubApplicationHttpClient.post(eq(appUrl), any(AppToken.class), eq("/app/installations/" + INSTALLATION_ID + "/access_tokens"))).thenReturn(response);
1139     return new AppInstallationToken(token);
1140   }
1141
1142   private static class OkGetResponse extends Response {
1143     private OkGetResponse(String content) {
1144       super(200, content);
1145     }
1146   }
1147
1148   private static class ErrorGetResponse extends Response {
1149     ErrorGetResponse() {
1150       super(401, null);
1151     }
1152
1153     ErrorGetResponse(int code, String content) {
1154       super(code, content);
1155     }
1156   }
1157
1158   private static class Response implements GetResponse {
1159     private final int code;
1160     private final String content;
1161     private final String nextEndPoint;
1162
1163     private Response(int code, @Nullable String content) {
1164       this(code, content, null);
1165     }
1166
1167     private Response(int code, @Nullable String content, @Nullable String nextEndPoint) {
1168       this.code = code;
1169       this.content = content;
1170       this.nextEndPoint = nextEndPoint;
1171     }
1172
1173     @Override
1174     public int getCode() {
1175       return code;
1176     }
1177
1178     @Override
1179     public Optional<String> getContent() {
1180       return Optional.ofNullable(content);
1181     }
1182
1183     @Override
1184     public RateLimit getRateLimit() {
1185       return RATE_LIMIT;
1186     }
1187
1188     @Override
1189     public Optional<String> getNextEndPoint() {
1190       return Optional.ofNullable(nextEndPoint);
1191     }
1192   }
1193 }