Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SLCORE-1032 Wrong token error during sync - [New design] #1187

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,25 @@
*/
package org.sonarsource.sonarlint.core;

import com.google.common.annotations.VisibleForTesting;
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 @@ -47,19 +53,21 @@

@Named
@Singleton
public class ServerApiProvider {
public class ServerApiProvider implements ConnectionManager {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see a strong reason to keep this interface and have a single implementation. Why about keeping only a ConnectionManager class?


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

public ServerApiProvider(ConnectionConfigurationRepository connectionRepository, ConnectionAwareHttpClientProvider awareHttpClientProvider, HttpClientProvider httpClientProvider,
SonarCloudActiveEnvironment sonarCloudActiveEnvironment) {
SonarCloudActiveEnvironment sonarCloudActiveEnvironment, SonarLintRpcClient client) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indentation issue?

this.connectionRepository = connectionRepository;
this.awareHttpClientProvider = awareHttpClientProvider;
this.httpClientProvider = httpClientProvider;
this.client = client;
this.sonarCloudUri = sonarCloudActiveEnvironment.getUri();
}

Expand Down Expand Up @@ -100,7 +108,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 +145,44 @@ private HttpClient getClientFor(EndpointParams params, Either<TokenDto, Username
userPass -> httpClientProvider.getHttpClientWithPreemptiveAuth(userPass.getUsername(), userPass.getPassword()));
}

@Override
public ServerConnection getConnectionOrThrow(String connectionId) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As shared earlier, I find the surface of methods quite large, so for people not familiar it might be complex to know which one to use. Do you think there is a way to simplify? Maybe we should at least document the different usages

var serverApi = getServerApiOrThrow(connectionId);
return new ServerConnection(connectionId, serverApi, client);
}

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

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

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

@Override
public void withValidConnection(String connectionId, Consumer<ServerApi> serverApiConsumer) {
getValidConnection(connectionId).ifPresent(connection -> connection.withClientApi(serverApiConsumer));
}

@Override
public <T> Optional<T> withValidConnectionAndReturn(String connectionId, Function<ServerApi, T> serverApiConsumer) {
return getValidConnection(connectionId).map(connection -> connection.withClientApiAndReturn(serverApiConsumer));
}

@Override
public <T> Optional<T> withValidConnectionFlatMapOptionalAndReturn(String connectionId, Function<ServerApi, Optional<T>> serverApiConsumer) {
return getValidConnection(connectionId).map(connection -> connection.withClientApiAndReturn(serverApiConsumer)).flatMap(Function.identity());
}

@VisibleForTesting
public Optional<ServerConnection> getValidConnection(String connectionId) {
return tryGetConnection(connectionId).filter(ServerConnection::isValid);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A last thing, should we log that the connection is invalid? Maybe too noisy?

}
Comment on lines +184 to +187
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is used only in a single test, couldn't we get rid of it and use another method? I mean at least to not have it public and remove the annotation

}
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.withValidConnectionAndReturn(connectionId,
s -> s.component().getProject(sonarProjectKey, cancelMonitor)).orElse(Optional.empty());
} 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.withValidConnectionAndReturn(connectionId,
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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked a bit more around this use case. In fact, the api/system/status call is not authenticated. So instead of having a method at the serverApiProvider level, I would find it more logical that the decision to not use authentication be made in SystemApi. But this has some impact in other places

.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,42 @@
/*
* SonarLint Core - Implementation
* Copyright (C) 2016-2025 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);
/**
* 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);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if this method should be located in ConnectionManager. As it's "transient" and by definition we won't keep state for it, and it's not (yet) a connection. I think it would simplify a bit the current ServerApiProvider which has a lot of entrypoints

void withValidConnection(String connectionId, Consumer<ServerApi> serverApiConsumer);
<T> Optional<T> withValidConnectionAndReturn(String connectionId, Function<ServerApi, T> serverApiConsumer);
<T> Optional<T> withValidConnectionFlatMapOptionalAndReturn(String connectionId, Function<ServerApi, Optional<T>> serverApiConsumer);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* SonarLint Core - Implementation
* Copyright (C) 2016-2025 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 {
ACTIVE, INVALID_CREDENTIALS, MISSING_PERMISSION
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* SonarLint Core - Implementation
* Copyright (C) 2016-2025 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.Instant;
import java.time.Period;
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;

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.ACTIVE;
@Nullable
private Instant lastNotificationTime;

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

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

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

public <T> T withClientApiAndReturn(Function<ServerApi, T> serverApiConsumer) {
try {
var result = serverApiConsumer.apply(serverApi);
state = ConnectionState.ACTIVE;
lastNotificationTime = null;
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;
lastNotificationTime = null;
} 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(Instant.now());
}

private void notifyClientAboutWrongTokenIfNeeded() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it's the responsibility of the ServerConnection to notify to the client. I would find it more logical to have it in the ConnectionManager.

if (shouldNotifyAboutWrongToken()) {
client.invalidToken(new InvalidTokenParams(connectionId));
lastNotificationTime = Instant.now();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,7 @@ 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.withValidConnectionFlatMapOptionalAndReturn(connectionId,api -> api.hotspot().fetch(hotspotKey, cancelMonitor));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name of this method is a bit long. In fact this makes me wonder if Api classes should return Optionals at all, maybe they should instead let the errors bubble up?

}

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.withValidConnectionFlatMapOptionalAndReturn(connectionId,
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.withValidConnectionFlatMapOptionalAndReturn(connectionId,
api -> api.issue().getCodeSnippet(fileKey, textRange, branch, pullRequest, cancelMonitor));
}

@VisibleForTesting
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,17 @@ private Optional<List<Path>> getPathsFromFileCache(Binding binding) {
}

private Optional<List<Path>> fetchPathsFromServer(Binding binding, SonarLintCancelMonitor cancelMonitor) {
var serverApiOpt = serverApiProvider.getServerApi(binding.getConnectionId());
if (serverApiOpt.isEmpty()) {
var connectionOpt = serverApiProvider.tryGetConnection(binding.getConnectionId());
if (connectionOpt.isEmpty()) {
LOG.debug("Connection '{}' does not exist", binding.getConnectionId());
return Optional.empty();
}
try {
List<Path> paths = fetchPathsFromServer(serverApiOpt.get(), binding.getSonarProjectKey(), cancelMonitor);
cacheServerPaths(binding, paths);
return Optional.of(paths);
return serverApiProvider.withValidConnectionFlatMapOptionalAndReturn(binding.getConnectionId(), serverApi -> {
List<Path> paths = fetchPathsFromServer(serverApi, binding.getSonarProjectKey(), cancelMonitor);
cacheServerPaths(binding, paths);
return Optional.of(paths);
});
} catch (CancellationException e) {
throw e;
} catch (Exception e) {
Expand Down
Loading