Skip to content

Commit

Permalink
SLCORE-1032 Wrong token error during sync - [New design]
Browse files Browse the repository at this point in the history
  • Loading branch information
kirill-knize-sonarsource committed Dec 17, 2024
1 parent 71b5f80 commit 0483733
Show file tree
Hide file tree
Showing 43 changed files with 712 additions and 249 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,22 @@

import java.net.URI;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.Nullable;
import javax.inject.Named;
import javax.inject.Singleton;
import org.eclipse.lsp4j.jsonrpc.ResponseErrorException;
import org.eclipse.lsp4j.jsonrpc.messages.ResponseError;
import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger;
import org.sonarsource.sonarlint.core.connection.ConnectionManager;
import org.sonarsource.sonarlint.core.connection.ServerConnection;
import org.sonarsource.sonarlint.core.commons.progress.SonarLintCancelMonitor;
import org.sonarsource.sonarlint.core.http.ConnectionAwareHttpClientProvider;
import org.sonarsource.sonarlint.core.http.HttpClient;
import org.sonarsource.sonarlint.core.http.HttpClientProvider;
import org.sonarsource.sonarlint.core.repository.connection.ConnectionConfigurationRepository;
import org.sonarsource.sonarlint.core.rpc.protocol.SonarLintRpcClient;
import org.sonarsource.sonarlint.core.rpc.protocol.SonarLintRpcErrorCode;
import org.sonarsource.sonarlint.core.rpc.protocol.backend.connection.common.TransientSonarCloudConnectionDto;
import org.sonarsource.sonarlint.core.rpc.protocol.backend.connection.common.TransientSonarQubeConnectionDto;
Expand All @@ -42,24 +47,30 @@
import org.sonarsource.sonarlint.core.serverapi.ServerApi;
import org.sonarsource.sonarlint.core.serverapi.ServerApiHelper;
import org.sonarsource.sonarlint.core.serverconnection.ServerVersionAndStatusChecker;
import org.sonarsource.sonarlint.core.storage.StorageService;
import org.sonarsource.sonarlint.core.sync.LastWebApiErrorNotificationService;

import static org.apache.commons.lang.StringUtils.removeEnd;

@Named
@Singleton
public class ServerApiProvider {
public class ServerApiProvider implements ConnectionManager {

private static final SonarLintLogger LOG = SonarLintLogger.get();
private final ConnectionConfigurationRepository connectionRepository;
private final ConnectionAwareHttpClientProvider awareHttpClientProvider;
private final HttpClientProvider httpClientProvider;
private final StorageService storageService;
private final SonarLintRpcClient client;
private final URI sonarCloudUri;

public ServerApiProvider(ConnectionConfigurationRepository connectionRepository, ConnectionAwareHttpClientProvider awareHttpClientProvider, HttpClientProvider httpClientProvider,
SonarCloudActiveEnvironment sonarCloudActiveEnvironment) {
SonarCloudActiveEnvironment sonarCloudActiveEnvironment, StorageService storageService, SonarLintRpcClient client) {
this.connectionRepository = connectionRepository;
this.awareHttpClientProvider = awareHttpClientProvider;
this.httpClientProvider = httpClientProvider;
this.storageService = storageService;
this.client = client;
this.sonarCloudUri = sonarCloudActiveEnvironment.getUri();
}

Expand Down Expand Up @@ -100,7 +111,7 @@ public ServerApi getServerApi(String baseUrl, @Nullable String organization, Str
return new ServerApi(params, httpClientProvider.getHttpClientWithPreemptiveAuth(token, isBearerSupported));
}

public ServerApi getServerApiOrThrow(String connectionId) {
private ServerApi getServerApiOrThrow(String connectionId) {
var params = connectionRepository.getEndpointParams(connectionId);
if (params.isEmpty()) {
var error = new ResponseError(SonarLintRpcErrorCode.CONNECTION_NOT_FOUND, "Connection '" + connectionId + "' is gone", connectionId);
Expand Down Expand Up @@ -137,4 +148,41 @@ private HttpClient getClientFor(EndpointParams params, Either<TokenDto, Username
userPass -> httpClientProvider.getHttpClientWithPreemptiveAuth(userPass.getUsername(), userPass.getPassword()));
}

@Override
public ServerConnection getConnectionOrThrow(String connectionId) {
var serverApi = getServerApiOrThrow(connectionId);
return new ServerConnection(connectionId, serverApi, new LastWebApiErrorNotificationService(storageService), client);
}

@Override
public Optional<ServerConnection> tryGetConnection(String connectionId) {
return getServerApi(connectionId)
.map(serverApi -> new ServerConnection(connectionId, serverApi, new LastWebApiErrorNotificationService(storageService), client));
}

public Optional<ServerConnection> tryGetConnectionWithoutCredentials(String connectionId) {
return getServerApiWithoutCredentials(connectionId)
.map(serverApi -> new ServerConnection(connectionId, serverApi, new LastWebApiErrorNotificationService(storageService), client));
}

@Override
public ServerApi getTransientConnection(String token,@Nullable String organization, String baseUrl) {
return getServerApi(baseUrl, organization, token);
}

@Override
public Optional<ServerConnection> getValidConnection(String connectionId) {
return tryGetConnection(connectionId).filter(ServerConnection::isValid);
}

@Override
public void withValidConnection(String connectionId, Consumer<ServerConnection> serverConnectionCall) {
// wrap the consumer call which is web API call and handle the connection state to avoid spamming the server with notifications
getValidConnection(connectionId).ifPresent(serverConnectionCall);
}

@Override
public <T> Optional<T> withValidConnectionAndReturn(String connectionId, Function<ServerConnection, Optional<T>> serverConnectionCall) {
return getValidConnection(connectionId).flatMap(serverConnectionCall);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ public Optional<ServerProject> getSonarProject(String connectionId, String sonar
return singleProjectsCache.get(new SonarProjectKey(connectionId, sonarProjectKey), () -> {
LOG.debug("Query project '{}' on connection '{}'...", sonarProjectKey, connectionId);
try {
return serverApiProvider.getServerApi(connectionId).flatMap(s -> s.component().getProject(sonarProjectKey, cancelMonitor));
return serverApiProvider.tryGetConnection(connectionId)
.flatMap(connection -> connection.withClientApiAndReturn(s -> s.component().getProject(sonarProjectKey, cancelMonitor)));
} catch (Exception e) {
LOG.error("Error while querying project '{}' from connection '{}'", sonarProjectKey, connectionId, e);
return Optional.empty();
Expand All @@ -137,7 +138,9 @@ public TextSearchIndex<ServerProject> getTextSearchIndex(String connectionId, So
LOG.debug("Load projects from connection '{}'...", connectionId);
List<ServerProject> projects;
try {
projects = serverApiProvider.getServerApi(connectionId).map(s -> s.component().getAllProjects(cancelMonitor)).orElse(List.of());
projects = serverApiProvider.tryGetConnection(connectionId)
.map(connection -> connection.withClientApiAndReturn(s -> s.component().getAllProjects(cancelMonitor)))
.orElse(List.of());
} catch (Exception e) {
LOG.error("Error while querying projects from connection '{}'", connectionId, e);
return new TextSearchIndex<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,23 +107,23 @@ private void queueCheckIfSoonUnsupported(String connectionId, String configScope
try {
var connection = connectionRepository.getConnectionById(connectionId);
if (connection != null && connection.getKind() == ConnectionKind.SONARQUBE) {
var serverApi = serverApiProvider.getServerApiWithoutCredentials(connectionId);
if (serverApi.isPresent()) {
var version = synchronizationService.getServerConnection(connectionId, serverApi.get()).readOrSynchronizeServerVersion(serverApi.get(), cancelMonitor);
var isCached = cacheConnectionIdPerVersion.containsKey(connectionId) && cacheConnectionIdPerVersion.get(connectionId).compareTo(version) == 0;
if (!isCached && VersionUtils.isVersionSupportedDuringGracePeriod(version)) {
client.showSoonUnsupportedMessage(
new ShowSoonUnsupportedMessageParams(
String.format(UNSUPPORTED_NOTIFICATION_ID, connectionId, version.getName()),
configScopeId,
String.format(NOTIFICATION_MESSAGE, version.getName(), connectionId, VersionUtils.getCurrentLts())
)
);
LOG.debug(String.format("Connection '%s' with version '%s' is detected to be soon unsupported",
connection.getConnectionId(), version.getName()));
}
cacheConnectionIdPerVersion.put(connectionId, version);
}
serverApiProvider.tryGetConnectionWithoutCredentials(connectionId)
.ifPresent(serverConnection -> serverConnection.withClientApi(serverApi -> {
var version = synchronizationService.readOrSynchronizeServerVersion(connectionId, serverApi, cancelMonitor);
var isCached = cacheConnectionIdPerVersion.containsKey(connectionId) && cacheConnectionIdPerVersion.get(connectionId).compareTo(version) == 0;
if (!isCached && VersionUtils.isVersionSupportedDuringGracePeriod(version)) {
client.showSoonUnsupportedMessage(
new ShowSoonUnsupportedMessageParams(
String.format(UNSUPPORTED_NOTIFICATION_ID, connectionId, version.getName()),
configScopeId,
String.format(NOTIFICATION_MESSAGE, version.getName(), connectionId, VersionUtils.getCurrentLts())
)
);
LOG.debug(String.format("Connection '%s' with version '%s' is detected to be soon unsupported",
connection.getConnectionId(), version.getName()));
}
cacheConnectionIdPerVersion.put(connectionId, version);
}));
}
} catch (Exception e) {
LOG.error("Error while checking if soon unsupported", e);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* SonarLint Core - Implementation
* Copyright (C) 2016-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonarsource.sonarlint.core.connection;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.sonarsource.sonarlint.core.serverapi.ServerApi;

public interface ConnectionManager {
ServerConnection getConnectionOrThrow(String connectionId);
Optional<ServerConnection> tryGetConnection(String connectionId);

/**
* Having dedicated TransientConnection class makes sense only if we handle the connection errors from there.
* Which brings up the problem of managing global state for notifications because we don't know the connection ID. <br/><br/>
* On other hand providing ServerApis directly, all Web API calls from transient ServerApi are not protected by checks for connection state.
* So we still can spam server with unprotected requests.
* It's not a big problem because we don't use such requests during scheduled sync.
* They are mostly related to setting up the connection or other user-triggered actions.
*/
ServerApi getTransientConnection(String token, @Nullable String organization, String baseUrl);
Optional<ServerConnection> getValidConnection(String connectionId);
void withValidConnection(String connectionId, Consumer<ServerConnection> serverConnectionCall);
<T> Optional<T> withValidConnectionAndReturn(String connectionId, Function<ServerConnection, Optional<T>> serverConnectionCall);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* SonarLint Core - Implementation
* Copyright (C) 2016-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonarsource.sonarlint.core.connection;

public enum ConnectionState {
NEVER_USED, ACTIVE, INVALID_CREDENTIALS, MISSING_PERMISSION, NETWORK_ERROR
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* SonarLint Core - Implementation
* Copyright (C) 2016-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonarsource.sonarlint.core.connection;

import java.time.Period;
import java.time.ZonedDateTime;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.sonarsource.sonarlint.core.rpc.protocol.SonarLintRpcClient;
import org.sonarsource.sonarlint.core.rpc.protocol.client.sync.InvalidTokenParams;
import org.sonarsource.sonarlint.core.serverapi.ServerApi;
import org.sonarsource.sonarlint.core.serverapi.exception.ForbiddenException;
import org.sonarsource.sonarlint.core.serverapi.exception.UnauthorizedException;
import org.sonarsource.sonarlint.core.sync.LastWebApiErrorNotificationService;

public class ServerConnection {

private static final Period WRONG_TOKEN_NOTIFICATION_INTERVAL = Period.ofDays(1);
private final String connectionId;
private final ServerApi serverApi;
private final SonarLintRpcClient client;
private ConnectionState state = ConnectionState.NEVER_USED;
@Nullable
private ZonedDateTime lastNotificationTime;
private final LastWebApiErrorNotificationService lastWebApiErrorNotificationService;

public ServerConnection(String connectionId, ServerApi serverApi, LastWebApiErrorNotificationService lastWebApiErrorNotificationService, SonarLintRpcClient client) {
this.connectionId = connectionId;
this.serverApi = serverApi;
this.lastWebApiErrorNotificationService = lastWebApiErrorNotificationService;
this.lastNotificationTime = lastWebApiErrorNotificationService.getLastWebApiErrorNotification(connectionId);
this.client = client;
}

public boolean isSonarCloud() {
return serverApi.isSonarCloud();
}

public boolean isValid() {
return state == ConnectionState.NEVER_USED || state == ConnectionState.ACTIVE;
}

public <T> T withClientApiAndReturn(Function<ServerApi, T> serverApiConsumer) {
try {
var result = serverApiConsumer.apply(serverApi);
state = ConnectionState.ACTIVE;
return result;
} catch (ForbiddenException e) {
state = ConnectionState.INVALID_CREDENTIALS;
notifyClientAboutWrongTokenIfNeeded();
} catch (UnauthorizedException e) {
state = ConnectionState.MISSING_PERMISSION;
notifyClientAboutWrongTokenIfNeeded();
}
return null;
}

public void withClientApi(Consumer<ServerApi> serverApiConsumer) {
try {
serverApiConsumer.accept(serverApi);
state = ConnectionState.ACTIVE;
} catch (ForbiddenException e) {
state = ConnectionState.INVALID_CREDENTIALS;
notifyClientAboutWrongTokenIfNeeded();
} catch (UnauthorizedException e) {
state = ConnectionState.MISSING_PERMISSION;
notifyClientAboutWrongTokenIfNeeded();
}
}

private boolean shouldNotifyAboutWrongToken() {
if (state != ConnectionState.INVALID_CREDENTIALS && state != ConnectionState.MISSING_PERMISSION) {
return false;
}
if (lastNotificationTime == null) {
return true;
}
return lastNotificationTime.plus(WRONG_TOKEN_NOTIFICATION_INTERVAL).isBefore(ZonedDateTime.now());
}

private void notifyClientAboutWrongTokenIfNeeded() {
if (shouldNotifyAboutWrongToken()) {
client.invalidToken(new InvalidTokenParams(connectionId));
lastNotificationTime = ZonedDateTime.now();
lastWebApiErrorNotificationService.setLastWebApiErrorNotification(connectionId, lastNotificationTime);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,8 @@ private void showHotspotForScope(String connectionId, String configurationScopeI
}

private Optional<ServerHotspotDetails> tryFetchHotspot(String connectionId, String hotspotKey, SonarLintCancelMonitor cancelMonitor) {
var serverApi = serverApiProvider.getServerApi(connectionId);
if (serverApi.isEmpty()) {
// should not happen since we found the connection just before, improve the design ?
return Optional.empty();
}
return serverApi.get().hotspot().fetch(hotspotKey, cancelMonitor);
return serverApiProvider.tryGetConnection(connectionId)
.flatMap(connection -> connection.withClientApiAndReturn(api -> api.hotspot().fetch(hotspotKey, cancelMonitor)));
}

private static HotspotDetailsDto adapt(String hotspotKey, ServerHotspotDetails hotspot, FilePathTranslation translation) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,18 +188,14 @@ static boolean isIssueTaint(String ruleKey) {

private Optional<IssueApi.ServerIssueDetails> tryFetchIssue(String connectionId, String issueKey, String projectKey, String branch, @Nullable String pullRequest,
SonarLintCancelMonitor cancelMonitor) {
var serverApi = serverApiProvider.getServerApiOrThrow(connectionId);
return serverApi.issue().fetchServerIssue(issueKey, projectKey, branch, pullRequest, cancelMonitor);
return serverApiProvider.getConnectionOrThrow(connectionId)
.withClientApiAndReturn(serverApi -> serverApi.issue().fetchServerIssue(issueKey, projectKey, branch, pullRequest, cancelMonitor));
}

private Optional<String> tryFetchCodeSnippet(String connectionId, String fileKey, Common.TextRange textRange, String branch, @Nullable String pullRequest,
SonarLintCancelMonitor cancelMonitor) {
var serverApi = serverApiProvider.getServerApi(connectionId);
if (serverApi.isEmpty() || fileKey.isEmpty()) {
// should not happen since we found the connection just before, improve the design ?
return Optional.empty();
}
return serverApi.get().issue().getCodeSnippet(fileKey, textRange, branch, pullRequest, cancelMonitor);
return serverApiProvider.tryGetConnection(connectionId).flatMap(connection ->
connection.withClientApiAndReturn(api -> api.issue().getCodeSnippet(fileKey, textRange, branch, pullRequest, cancelMonitor)));
}

@VisibleForTesting
Expand Down
Loading

0 comments on commit 0483733

Please sign in to comment.