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

SLVS-1694 Provide system proxy settings to the SlCore process #5898

Merged
merged 3 commits into from
Dec 17, 2024
Merged
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 @@ -22,6 +22,7 @@
using NSubstitute.ExceptionExtensions;
using SonarLint.VisualStudio.Core;
using SonarLint.VisualStudio.SLCore.Core;
using SonarLint.VisualStudio.SLCore.Listener.Http;
using SonarLint.VisualStudio.SLCore.Listener.Http.Model;
using SonarLint.VisualStudio.SLCore.Listeners.Implementation.Http;

Expand All @@ -30,44 +31,96 @@ namespace SonarLint.VisualStudio.SLCore.Listeners.UnitTests.Implementation.Http;
[TestClass]
public class HttpConfigurationListenerTests
{
private HttpConfigurationListener testSubject;
private TestLogger testLogger;
private const string SystemProxyHost = "mycompany.com";
private ICertificateChainValidator certificateChainValidator;
private ICertificateDtoConverter certificateDtoConverter;
private ISystemProxyDetector proxySettingsDetector;
private TestLogger testLogger;
private HttpConfigurationListener testSubject;

[TestInitialize]
public void TestInitialize()
{
testLogger = new TestLogger();
certificateChainValidator = Substitute.For<ICertificateChainValidator>();
certificateDtoConverter = Substitute.For<ICertificateDtoConverter>();
testSubject = new HttpConfigurationListener(testLogger, certificateChainValidator, certificateDtoConverter);
proxySettingsDetector = Substitute.For<ISystemProxyDetector>();
testSubject = new HttpConfigurationListener(testLogger, certificateChainValidator, certificateDtoConverter, proxySettingsDetector);
}

[TestMethod]
public void MefCtor_CheckIsExported()
{
public void MefCtor_CheckIsExported() =>
MefTestHelpers.CheckTypeCanBeImported<HttpConfigurationListener, ISLCoreListener>(
MefTestHelpers.CreateExport<ILogger>(),
MefTestHelpers.CreateExport<ICertificateDtoConverter>(),
MefTestHelpers.CreateExport<ICertificateChainValidator>());
MefTestHelpers.CreateExport<ICertificateChainValidator>(),
MefTestHelpers.CreateExport<ISystemProxyDetector>()
);

[TestMethod]
public void Mef_CheckIsSingleton() => MefTestHelpers.CheckIsSingletonMefComponent<HttpConfigurationListener>();

[TestMethod]
[DataRow("htpp://localhost")]
[DataRow("https://sonarcloud.io")]
public async Task SelectProxiesAsync_NoProxyConfigured_ReturnsListWithNoProxyDto(string uri)
{
var parameter = new SelectProxiesParams(new Uri(uri));
MockNoProxyConfigured(parameter.uri);

var result = await testSubject.SelectProxiesAsync(parameter);

result.proxies.Should().BeEquivalentTo([ProxyDto.NO_PROXY]);
}

[TestMethod]
public async Task SelectProxiesAsync_UriNull_ReturnsNoProxyDto()
{
var parameter = new SelectProxiesParams(null);
MockNoProxyConfigured(parameter.uri);

var result = await testSubject.SelectProxiesAsync(parameter);

result.proxies.Should().BeEquivalentTo([ProxyDto.NO_PROXY]);
}

[TestMethod]
[DataRow("http", "localhost:8080")]
[DataRow("https", "sonarcloud.io")]
public async Task SelectProxiesAsync_HttpProxyConfigured_ReturnsListWithHttpProxyDto(string scheme, string host)
{
var parameter = new SelectProxiesParams(new Uri(BuildUri(scheme, host)));
MockProxyConfigured(BuildUri(scheme, SystemProxyHost), 1328);

var result = await testSubject.SelectProxiesAsync(parameter);

result.proxies.Should().BeEquivalentTo([new ProxyDto(ProxyType.HTTP, SystemProxyHost, 1328)]);
}

[TestMethod]
public void Mef_CheckIsSingleton()
[DataRow("socks4", "localhost:8080")]
[DataRow("socks5", "sonarcloud.io")]
public async Task SelectProxiesAsync_SocksProxyConfigured_ReturnsListWithSocksProxyDto(string scheme, string host)
{
MefTestHelpers.CheckIsSingletonMefComponent<HttpConfigurationListener>();
var parameter = new SelectProxiesParams(new Uri(BuildUri(scheme, host)));
MockProxyConfigured(BuildUri(scheme, SystemProxyHost), 1328);

var result = await testSubject.SelectProxiesAsync(parameter);

result.proxies.Should().BeEquivalentTo([new ProxyDto(ProxyType.SOCKS, SystemProxyHost, 1328)]);
}

[TestMethod]
[DataRow(null)]
[DataRow(5)]
[DataRow("something")]
public async Task SelectProxiesAsync_ReturnsEmptyList(object parameter)
public async Task SelectProxiesAsync_UnknownProxyConfigured_ReturnsListWithHttpProxyDtoAndLogs()
{
var unknownScheme = "unknown";
var parameter = new SelectProxiesParams(new Uri(BuildUri(unknownScheme, "sonarcloud.io")));
MockProxyConfigured(BuildUri(unknownScheme, SystemProxyHost), 1328);

var result = await testSubject.SelectProxiesAsync(parameter);

result.proxies.Should().BeEmpty();
result.proxies.Should().BeEquivalentTo([new ProxyDto(ProxyType.HTTP, SystemProxyHost, 1328)]);
testLogger.AssertOutputStringExists(string.Format(SLCoreStrings.UnknowProxyType, unknownScheme));
}

[DataTestMethod]
Expand All @@ -78,7 +131,7 @@ public async Task CheckServerTrustedAsync_SingleCertificate_ConvertsAndValidates
var (primaryCertificateDto, primaryCertificate) = SetUpCertificate("some certificate");
certificateChainValidator.ValidateChain(primaryCertificate, Arg.Is<IEnumerable<X509Certificate2>>(x => !x.Any())).Returns(validationResult);

var response = await testSubject.CheckServerTrustedAsync(new([primaryCertificateDto], "ignored"));
var response = await testSubject.CheckServerTrustedAsync(new CheckServerTrustedParams([primaryCertificateDto], "ignored"));

response.trusted.Should().Be(validationResult);
}
Expand All @@ -98,28 +151,34 @@ public async Task CheckServerTrustedAsync_MultipleCertificates_ConvertsAndValida
Arg.Is<IEnumerable<X509Certificate2>>(x => x.SequenceEqual(additionalCertificates)))
.Returns(validationResult);

var response = await testSubject.CheckServerTrustedAsync(new([primaryCertificateDto, additionalCertificateDto1, additionalCertificateDto2], "ignored"));
var response = await testSubject.CheckServerTrustedAsync(new CheckServerTrustedParams([primaryCertificateDto, additionalCertificateDto1, additionalCertificateDto2], "ignored"));

response.trusted.Should().Be(validationResult);
}

[TestMethod]
public async Task CheckServerTrustedAsync_Exception_ReturnsFalse()
{
var primaryCertificateDto = new X509CertificateDto("some certificate");
var exceptionReason = "exception reason";
certificateDtoConverter.Convert(primaryCertificateDto).Throws(new ArgumentException(exceptionReason));
var response = await testSubject.CheckServerTrustedAsync(new([primaryCertificateDto], "ignored"));
var response = await testSubject.CheckServerTrustedAsync(new CheckServerTrustedParams([primaryCertificateDto], "ignored"));

response.trusted.Should().Be(false);
testLogger.AssertPartialOutputStringExists(exceptionReason);
}

private (X509CertificateDto certificateDto, X509Certificate2 certificate) SetUpCertificate(string certificateName)
{
var certificateDto = new X509CertificateDto(certificateName);
var certificate = new X509Certificate2();
certificateDtoConverter.Convert(certificateDto).Returns(certificate);
return (certificateDto, certificate);
}

private void MockNoProxyConfigured(Uri uri) => proxySettingsDetector.GetProxyUri(Arg.Any<Uri>()).Returns(uri);

private void MockProxyConfigured(string hostName, int port) => proxySettingsDetector.GetProxyUri(Arg.Any<Uri>()).Returns(new Uri($"{hostName}:{port}"));

private static string BuildUri(string scheme, string host) => $"{scheme}://{host}";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* SonarLint for Visual Studio
* 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.
*/

using SonarLint.VisualStudio.SLCore.Listeners.Implementation.Http;

namespace SonarLint.VisualStudio.SLCore.Listeners.UnitTests.Implementation.Http;

[TestClass]
public class SystemProxyDetectorTests
{
private SystemProxyDetector testSubject;

[TestInitialize]
public void TestInitialize() => testSubject = new SystemProxyDetector();

[TestMethod]
public void MefCtor_CheckIsExported() => MefTestHelpers.CheckTypeCanBeImported<SystemProxyDetector, ISystemProxyDetector>();

[TestMethod]
public void Mef_CheckIsSingleton() => MefTestHelpers.CheckIsSingletonMefComponent<SystemProxyDetector>();

[TestMethod]
public void GetProxyUri_NullUri_ReturnsNull()
{
var result = testSubject.GetProxyUri(null);

result.Should().BeNull();
}

[TestMethod]
public void GetProxyUri_UriNotNull_ReturnsUri()
{
var result = testSubject.GetProxyUri(new Uri("https://sonarcloud.io"));

result.Should().NotBeNull();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@
*/

using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using SonarLint.VisualStudio.Core;
using SonarLint.VisualStudio.SLCore.Core;
using SonarLint.VisualStudio.SLCore.Listener.Http;
Expand All @@ -36,18 +33,51 @@ internal class HttpConfigurationListener : IHttpConfigurationListener
private readonly ILogger logger;
private readonly ICertificateChainValidator chainValidator;
private readonly ICertificateDtoConverter certificateDtoConverter;
private readonly ISystemProxyDetector proxySettingsDetector;
private static readonly List<string> socksHosts = ["socks4", "socks5"];

[ImportingConstructor]
public HttpConfigurationListener(ILogger logger, ICertificateChainValidator chainValidator, ICertificateDtoConverter certificateDtoConverter)
public HttpConfigurationListener(ILogger logger, ICertificateChainValidator chainValidator, ICertificateDtoConverter certificateDtoConverter, ISystemProxyDetector proxySettingsDetector)
{
this.logger = logger;
this.chainValidator = chainValidator;
this.certificateDtoConverter = certificateDtoConverter;
this.proxySettingsDetector = proxySettingsDetector;
}

public Task<SelectProxiesResponse> SelectProxiesAsync(object parameters)
public Task<SelectProxiesResponse> SelectProxiesAsync(SelectProxiesParams parameters)
{
return Task.FromResult(new SelectProxiesResponse());
List<ProxyDto> proxies = [GetSystemProxy(parameters.uri) ?? ProxyDto.NO_PROXY];
return Task.FromResult(new SelectProxiesResponse(proxies));
}

private ProxyDto GetSystemProxy(Uri uri)
{
var proxyUri = proxySettingsDetector.GetProxyUri(uri);
if (proxyUri == uri)
{
// when same Uri is returned, it means no proxy was configured at system level
return null;
}
return new ProxyDto(DetermineProxyType(proxyUri), proxyUri.Host, proxyUri.Port);
}

/// <summary>
/// If the URI scheme is one of the SOCKS schemes, returns SOCKS, otherwise returns HTTP (not NO_PROXY as this value means no proxy).
/// </summary>
private ProxyType DetermineProxyType(Uri uri)
{
if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
{
return ProxyType.HTTP;
}
if (socksHosts.Contains(uri.Scheme))
{
return ProxyType.SOCKS;
}

logger.WriteLine(SLCoreStrings.UnknowProxyType, uri.Scheme);
return ProxyType.HTTP;
}

public Task<CheckServerTrustedResponse> CheckServerTrustedAsync(CheckServerTrustedParams parameters)
Expand Down
37 changes: 37 additions & 0 deletions src/SLCore.Listeners/Implementation/Http/SystemProxyDetector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* SonarLint for Visual Studio
* 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.
*/

using System.ComponentModel.Composition;
using System.Net;
using SonarLint.VisualStudio.SLCore.Core;

namespace SonarLint.VisualStudio.SLCore.Listeners.Implementation.Http;

public interface ISystemProxyDetector
{
Uri GetProxyUri(Uri uri);
}

[Export(typeof(ISystemProxyDetector))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class SystemProxyDetector : ISystemProxyDetector
{
public Uri GetProxyUri(Uri uri) => uri == null ? null : WebRequest.GetSystemWebProxy().GetProxy(uri);
}
Loading
Loading