GithubScm extends AbstractScm { static void validateAccessTokenScopes(HttpURLConnection connection) { String scopesHeader = connection.getHeaderField("X-OAuth-Scopes"); if(scopesHeader == null){ throw new ServiceException.PreconditionRequired("No scopes associated with this token. Expected scopes 'user:email, repo'."); } List<String> scopes = new ArrayList<>(); for(String s: scopesHeader.split(",")){ scopes.add(s.trim()); } List<String> missingScopes = new ArrayList<>(); if(!scopes.contains(USER_EMAIL_SCOPE) && !scopes.contains(USER_SCOPE)){ missingScopes.add(USER_EMAIL_SCOPE); } if(!scopes.contains(REPO_SCOPE)){ missingScopes.add(REPO_SCOPE); } if(!missingScopes.isEmpty()){ throw new ServiceException.PreconditionRequired("Invalid token, its missing scopes: "+ StringUtils.join(missingScopes, ",")); } } GithubScm(Reachable parent); @Override Link getLink(); @Override @Nonnull String getId(); @Override @Nonnull String getUri(); String getCredentialDomainName(); @Override String getCredentialId(); @Override Object getState(); @Override Container<ScmOrganization> getOrganizations(); @Override ScmServerEndpointContainer getServers(); boolean isOrganizationAvatarSupported(); @Override HttpResponse validateAndCreate(@JsonBody JSONObject request); static final String ID; }
@Test public void validateAccessTokenScopes() throws Exception { HttpURLConnection httpURLConnectionMock = mock(HttpURLConnection.class); doNothing().when(httpURLConnectionMock).connect(); URL urlMock = mock(URL.class); whenNew(URL.class).withAnyArguments().thenReturn(urlMock); when(urlMock.openConnection(Proxy.NO_PROXY)).thenReturn(httpURLConnectionMock); when(httpURLConnectionMock.getHeaderField("X-OAuth-Scopes")).thenReturn("user:email,repo"); when(httpURLConnectionMock.getResponseCode()).thenReturn(200); HttpURLConnection httpURLConnection = GithubScm.connect(GitHubSCMSource.GITHUB_URL, "abcd"); GithubScm.validateAccessTokenScopes(httpURLConnection); }