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

Hardening Sprint November 2023 #5016

Merged
merged 5 commits into from
Nov 6, 2023
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 @@ -52,8 +52,7 @@ public void ReadSharedBindingConfigFile_SQConfig_Reads()

var result = testSubject.ReadSharedBindingConfigFile(filePath);

result.Uri.Should().Be("https://127.0.0.1:9000");
result.ServerUri.Should().BeEquivalentTo(uri);
result.Uri.Should().BeEquivalentTo(uri);
result.ProjectKey.Should().Be("projectKey");
result.Organization.Should().BeNull();
}
Expand All @@ -63,7 +62,6 @@ public void ReadSharedBindingConfigFile_SCConfig_Reads()
{
string configFileContent = @"{""SonarCloudOrganization"":""Some Organisation"",""ProjectKey"":""projectKey""}";
string filePath = "Some Path";
var uri = new Uri(SharedBindingConfigFileProvider.SonarCloudUri);

var file = CreateFile(filePath, configFileContent);
var fileSystem = GetFileSystem(file.Object);
Expand All @@ -74,8 +72,7 @@ public void ReadSharedBindingConfigFile_SCConfig_Reads()

result.Organization.Should().Be("Some Organisation");
result.ProjectKey.Should().Be("projectKey");
result.Uri.Should().Be(SharedBindingConfigFileProvider.SonarCloudUri);
result.ServerUri.Should().BeEquivalentTo(uri);
result.Uri.Should().BeEquivalentTo(SharedBindingConfigFileProvider.SonarCloudUri);
}

[TestMethod]
Expand Down Expand Up @@ -125,6 +122,22 @@ public void ReadSharedBindingConfigFile_InvalidUri_ReturnsNull()

result.Should().BeNull();
}

[TestMethod]
public void ReadSharedBindingConfigFile_InvalidProjectKey_ReturnsNull()
{
var configFileContent = @"{""SonarQubeUri"":""http://localhost"",""ProjectKey"":"" ""}";
var filePath = "Some Path";

var file = CreateFile(filePath, configFileContent);
var fileSystem = GetFileSystem(file.Object);

var testSubject = CreateTestSubject(fileSystem.Object);

var result = testSubject.ReadSharedBindingConfigFile(filePath);

result.Should().BeNull();
}

[TestMethod]
public void WriteSharedBindingConfigFile_SQConfig_Writes()
Expand All @@ -133,7 +146,7 @@ public void WriteSharedBindingConfigFile_SQConfig_Writes()
""SonarQubeUri"": ""https://127.0.0.1:9000"",
""ProjectKey"": ""projectKey""
}";
var config = new SharedBindingConfigModel() { Uri = "https://127.0.0.1:9000", ProjectKey = "projectKey" };
var config = new SharedBindingConfigModel() { Uri = new Uri("https://127.0.0.1:9000"), ProjectKey = "projectKey" };
var filePath = "C:\\Solution\\.sonarlint\\Solution.json";

var file = CreateFile();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using System;
using SonarLint.VisualStudio.ConnectedMode.Shared;
using SonarQube.Client;

Expand Down Expand Up @@ -51,7 +52,7 @@ public void GetServerType_Null_ReturnsNull()
[TestMethod]
public void GetServerType_NoOrganization_ReturnsQube()
{
SharedBindingConfigModel model = new SharedBindingConfigModel{ProjectKey = "abc", Uri = "https://next.sonarqube.com"};
SharedBindingConfigModel model = new SharedBindingConfigModel{ProjectKey = "abc", Uri = new Uri("https://next.sonarqube.com")};

model.GetServerType().Should().Be(ServerType.SonarQube);
}
Expand Down
2 changes: 1 addition & 1 deletion src/ConnectedMode/Migration/ConnectedModeMigration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ private async Task MigrateImplAsync(BoundSonarQubeProject oldBinding, IProgress<

private bool SaveSharedBinding(BoundSonarQubeProject binding)
{
var sharedBindingConfigModel = new SharedBindingConfigModel { Organization = binding.Organization?.Key, ProjectKey = binding.ProjectKey, Uri = binding.ServerUri.ToString() };
var sharedBindingConfigModel = new SharedBindingConfigModel { Organization = binding.Organization?.Key, ProjectKey = binding.ProjectKey, Uri = binding.ServerUri };
return sharedBindingConfigProvider.SaveSharedBinding(sharedBindingConfigModel) != null;
}

Expand Down
16 changes: 11 additions & 5 deletions src/ConnectedMode/Shared/SharedBindingConfigFileProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal class SharedBindingConfigFileProvider : ISharedBindingConfigFileProvide

private readonly ILogger logger;
private readonly IFileSystem fileSystem;
internal /*for testing*/ const string SonarCloudUri = "https://sonarcloud.io";
internal /*for testing*/ static readonly Uri SonarCloudUri = new Uri("https://sonarcloud.io");

[ImportingConstructor]
public SharedBindingConfigFileProvider(ILogger logger) : this(logger, new FileSystem())
Expand All @@ -59,22 +59,28 @@ internal SharedBindingConfigFileProvider(ILogger logger, IFileSystem fileSystem)

public SharedBindingConfigModel ReadSharedBindingConfigFile(string filePath)
{
SharedBindingConfigModel result = null;

try
{
result = JsonConvert.DeserializeObject<SharedBindingConfigModel>(fileSystem.File.ReadAllText(filePath));
var result = JsonConvert.DeserializeObject<SharedBindingConfigModel>(fileSystem.File.ReadAllText(filePath));

if (result.IsSonarCloud())
{
result.Uri = SonarCloudUri;
}

if (!string.IsNullOrWhiteSpace(result.ProjectKey)
&& result.Uri != null
&& (result.Uri.Scheme == Uri.UriSchemeHttp || result.Uri.Scheme == Uri.UriSchemeHttps))
{
return result;
}
}
catch (Exception ex)
{
logger.LogVerbose($"[SharedBindingConfigFileProvider] Unable to read shared sonarlint config file: {ex.Message}");
}

return result;
return null;
}

public bool WriteSharedBindingConfigFile(string filePath, SharedBindingConfigModel sharedBindingConfigModel)
Expand Down
16 changes: 1 addition & 15 deletions src/ConnectedMode/Shared/SharedBindingConfigModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,29 +26,15 @@ namespace SonarLint.VisualStudio.ConnectedMode.Shared
{
public class SharedBindingConfigModel
{
private string uri;

[JsonProperty("SonarQubeUri", NullValueHandling = NullValueHandling.Ignore)]
public string Uri
{
get => uri;
set
{
uri = value;

ServerUri = uri != null ? new Uri(uri) : null;
}
}
public Uri Uri { get; set; }

[JsonProperty("SonarCloudOrganization", NullValueHandling = NullValueHandling.Ignore)]
public string Organization { get; set; }

[JsonProperty("ProjectKey")]
public string ProjectKey { get; set; }

[JsonIgnore]
public Uri ServerUri { get; private set; }

public bool IsSonarCloud() => !string.IsNullOrWhiteSpace(Organization);
}

Expand Down
124 changes: 124 additions & 0 deletions src/Education.UnitTests/XamlGenerator/RuleXamlBuilderSmokeTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* SonarLint for Visual Studio
* Copyright (C) 2016-2023 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;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Documents;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SonarLint.VisualStudio.Education.Layout.Logical;
using SonarLint.VisualStudio.Education.XamlGenerator;
using SonarLint.VisualStudio.Rules;
using SonarLint.VisualStudio.TestInfrastructure;

namespace SonarLint.VisualStudio.Education.UnitTests.XamlGenerator;

[TestClass]
public class RuleXamlBuilderSmokeTest
{
private static readonly Assembly ResourceAssembly = typeof(LocalRuleMetadataProvider).Assembly;

[TestMethod]
public void Create_CheckAllEmbedded()
{
// Performance: this test is loading nearly 2000 files and creating
// XAML document for them, but it still only takes a around 3 seconds
// to run.
var resourceNames = ResourceAssembly.GetManifestResourceNames()
.Where(x => x.EndsWith(".json"));

// Sanity check - should have checked at least 1500 rules
resourceNames.Count().Should().BeGreaterThan(1500);

Console.WriteLine("Checking xaml creation. Count = " + resourceNames.Count());

string[] failures;
using (new AssertIgnoreScope()) // the product code can assert if it encounters an unrecognised tag
{
failures = resourceNames.Where(x => !ProcessResource(x))
.ToArray();
}

failures.Should().BeEquivalentTo(new[]
{
// introduced in sonar-cpp 6.48
"SonarLint.VisualStudio.Rules.Embedded.cpp.S1232.json",
// some issue with diff highlighting
"SonarLint.VisualStudio.Rules.Embedded.csharpsquid.S6640.json",
});
}

private static bool ProcessResource(string fullResourceName)
{
var xamlWriterFactory = new XamlWriterFactory();
var ruleHelpXamlTranslatorFactory = new RuleHelpXamlTranslatorFactory(xamlWriterFactory, new DiffTranslator(xamlWriterFactory));
var xamlGeneratorHelperFactory = new XamlGeneratorHelperFactory(ruleHelpXamlTranslatorFactory);
var ruleInfoTranslator = new RuleInfoTranslator(ruleHelpXamlTranslatorFactory, new TestLogger());
var staticXamlStorage = new StaticXamlStorage(ruleHelpXamlTranslatorFactory);

var simpleXamlBuilder = new SimpleRuleHelpXamlBuilder(ruleHelpXamlTranslatorFactory, xamlGeneratorHelperFactory, xamlWriterFactory);
var richXamlBuilder = new RichRuleHelpXamlBuilder(ruleInfoTranslator, xamlGeneratorHelperFactory, staticXamlStorage, xamlWriterFactory);

try
{
bool res = false;

var data = ReadResource(fullResourceName);
var jsonRuleInfo = LocalRuleMetadataProvider.RuleInfoJsonDeserializer.Deserialize(data);

if (!string.IsNullOrWhiteSpace(jsonRuleInfo.Description))
{
Res(simpleXamlBuilder.Create(jsonRuleInfo));
res = true;
}

if (jsonRuleInfo.DescriptionSections.Any())
{
Res(richXamlBuilder.Create(jsonRuleInfo, null));
res = true;
}

return res; // simple || rich should be true
}
catch (Exception ex)
{
Console.WriteLine("Failed: " + fullResourceName);
Console.WriteLine(" " + ex.Message);
return false;
}
}

private static void Res(FlowDocument doc)
{
// Quick sanity check that something was produced
// Note: this is a quick way of getting the size of the document. Serializing the doc to a string
// and checking the length takes much longer (around 25 seconds)
var docLength = doc.ContentStart.DocumentStart.GetOffsetToPosition(doc.ContentEnd.DocumentEnd);
docLength.Should().BeGreaterThan(30);
}

private static string ReadResource(string fullResourceName)
{
using var stream = new StreamReader(ResourceAssembly.GetManifestResourceStream(fullResourceName));
return stream.ReadToEnd();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
Expand Down Expand Up @@ -102,71 +100,5 @@ public void Create_FormsCorrectStructure()

flowDocument.Blocks.Single().Should().BeOfType<Paragraph>().Which.Inlines.Single().Should().BeOfType<Run>().Which.Text.Should().Be("Hi");
}

[TestMethod]
public void Create_CheckAllEmbedded()
{
// Performance: this test is loading nearly 2000 files and creating
// XAML document for them, but it still only takes a around 3 seconds
// to run.
var resourceNames = ResourceAssembly.GetManifestResourceNames()
.Where(x => x.EndsWith(".json"));

// Sanity check - should have checked at least 1500 rules
resourceNames.Count().Should().BeGreaterThan(1500);

Console.WriteLine("Checking xaml creation. Count = " + resourceNames.Count());

string[] failures;
using(new AssertIgnoreScope()) // the product code can assert if it encounters an unrecognised tag
{
failures = resourceNames.Where(x => !ProcessResource(x))
.ToArray();
}

// see https://github.com/SonarSource/sonarlint-visualstudio/issues/4471
failures.Should().BeEquivalentTo(new[]
{
// introduced in sonar-cpp 6.48
"SonarLint.VisualStudio.Rules.Embedded.cpp.S1232.json",
// introduced in dotnet analyzer 9.5
"SonarLint.VisualStudio.Rules.Embedded.csharpsquid.S4433.json",
});
}

private static bool ProcessResource(string fullResourceName)
{
var testSubject = new SimpleRuleHelpXamlBuilder(new RuleHelpXamlTranslatorFactory(new XamlWriterFactory(), new DiffTranslator(new XamlWriterFactory())), new XamlGeneratorHelperFactory(new RuleHelpXamlTranslatorFactory(new XamlWriterFactory(), new DiffTranslator(new XamlWriterFactory()))), new XamlWriterFactory());

try
{
var data = ReadResource(fullResourceName);
var jsonRuleInfo = LocalRuleMetadataProvider.RuleInfoJsonDeserializer.Deserialize(data);

if (!string.IsNullOrWhiteSpace(jsonRuleInfo.Description))
{
var doc = testSubject.Create(jsonRuleInfo);

// Quick sanity check that something was produced
// Note: this is a quick way of getting the size of the document. Serializing the doc to a string
// and checking the length takes much longer (around 25 seconds)
var docLength = doc.ContentStart.DocumentStart.GetOffsetToPosition(doc.ContentEnd.DocumentEnd);
docLength.Should().BeGreaterThan(30);
}
return true;
}
catch (Exception ex)
{
Console.WriteLine("Failed: " + fullResourceName);
Console.WriteLine(" " + ex.Message);
return false;
}
}

private static string ReadResource(string fullResourceName)
{
using var stream = new StreamReader(ResourceAssembly.GetManifestResourceStream(fullResourceName));
return stream.ReadToEnd();
}
}
}
Loading