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

fix: non-ascii characters in path #341

Merged
merged 15 commits into from
Jan 28, 2025
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
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ jobs:
- name: Create and push Git tag release
run: |
git tag ${{ needs.build-project.outputs.version }}
git push origin main
git push origin main --tags
git push origin ${{ github.ref_name }}
git push origin ${{ github.ref_name }} --tags

- name: Create GitHub Release
id: create_release
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Snyk Security Changelog

## [2.0.1]
### Changed
- Fix UI freezes when ignoring trust, downloading or triggering scans.
- Fix CLI release channel not being persisted.
- Fix showing scan results when path contains non-ascii characters.

## [2.0.0]
### Changed
- Visual Studio extension is now fully integrated with Snyk Language Server protocol.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public override async Task UpdateStateAsync()
protected override void Execute(object sender, EventArgs eventArgs)
{
base.Execute(sender, eventArgs);

ThreadHelper.JoinableTaskFactory.RunAsync(SnykTasksService.Instance.ScanAsync).FireAndForget();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ public static class UriExtensions
public static string UncAwareAbsolutePath(this Uri uri)
{
if (uri == null) return string.Empty;
return uri.IsUnc ? uri.LocalPath : uri.AbsolutePath;
return uri.LocalPath;
}
}
2 changes: 1 addition & 1 deletion Snyk.VisualStudio.Extension.2022/Language/LsSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public SnykLsInitializationOptions GetInitializationOptions()
ActivateSnykOpenSource = options.OssEnabled.ToString().ToLower(),
ActivateSnykIac = options.IacEnabled.ToString().ToLower(),
ManageBinariesAutomatically = options.BinariesAutoUpdate.ToString().ToLower(),
EnableTrustedFoldersFeature = "true",
EnableTrustedFoldersFeature = "false",
TrustedFolders = options.TrustedFolders.ToList(),
IntegrationName = this.GetIntegrationName(options),
IntegrationVersion = this.GetIntegrationVersion(options),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,6 @@ public async Task<Connection> ActivateAsync(CancellationToken token)
var options = serviceProvider.Options;
// ReSharper disable once RedundantAssignment
var lsDebugLevel = await GetLsDebugLevelAsync(serviceProvider.SnykOptionsManager);
#if DEBUG
lsDebugLevel = "debug";
#endif
var info = new ProcessStartInfo
{
FileName = SnykCli.GetCliFilePath(options.CliCustomPath),
Expand All @@ -94,9 +91,6 @@ public async Task<Connection> ActivateAsync(CancellationToken token)
UseShellExecute = false,
CreateNoWindow = true
};
#if DEBUG
info.CreateNoWindow = false;
#endif
var process = new Process
{
StartInfo = info
Expand All @@ -119,7 +113,7 @@ public async Task OnLoadedAsync()
//}
var isPackageInitialized = SnykVSPackage.Instance?.IsInitialized ?? false;
var shouldStart = isPackageInitialized && !SnykVSPackage.ServiceProvider.TasksService.ShouldDownloadCli();
Logger.Debug("OnLoadedAsync Called and shouldStart is: {ShouldStart}", shouldStart);
Logger.Information("OnLoadedAsync Called and shouldStart is: {ShouldStart}", shouldStart);

await StartServerAsync(shouldStart);
}
Expand Down Expand Up @@ -147,7 +141,7 @@ public async Task StartServerAsync(bool shouldStart = false)
}
else
{
Logger.Debug("Couldn't Start Language Server");
Logger.Information("Couldn't Start Language Server");
}
}
finally
Expand Down Expand Up @@ -196,7 +190,7 @@ public async Task StopServerAsync()
}
else
{
Logger.Debug("Could not stop Language Server because StopAsync is null");
Logger.Information("Could not stop Language Server because StopAsync is null");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public async Task OnHasAuthenticated(JToken arg)
serviceProvider.FeatureFlagService.RefreshAsync(SnykVSPackage.Instance.DisposalToken).FireAndForget();
if (serviceProvider.Options.AutoScan)
{
await serviceProvider.TasksService.ScanAsync();
serviceProvider.TasksService.ScanAsync().FireAndForget();
}
}

Expand All @@ -152,7 +152,7 @@ public async Task OnAddTrustedFolders(JToken arg)
if (trustedFolders == null) return;

serviceProvider.Options.TrustedFolders = new HashSet<string>(trustedFolders.TrustedFolders);
this.serviceProvider.SnykOptionsManager.Save(serviceProvider.Options);
this.serviceProvider.SnykOptionsManager.Save(serviceProvider.Options, false);
await serviceProvider.LanguageClientManager.DidChangeConfigurationAsync(SnykVSPackage.Instance.DisposalToken);
}

Expand Down Expand Up @@ -225,6 +225,12 @@ private string LspSourceToProduct(string source)
_ => ""
};
}

// Only used in tests
public ConcurrentDictionary<string, IEnumerable<Issue>> GetCodeDictionary()
{
return snykCodeIssueDictionary;
}
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ private void LogLspMessage(JToken methodParams)
Logger.Information(msgTemplate, logMsg.Message);
break;
case LSP.MessageType.Log:
Logger.Debug(msgTemplate, logMsg.Message);
Logger.Information(msgTemplate, logMsg.Message);
break;
}
}
Expand Down
29 changes: 20 additions & 9 deletions Snyk.VisualStudio.Extension.2022/LogManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using Microsoft.VisualStudio.Shell;
using Serilog;
using Serilog.Core;
using Serilog.Events;
Expand All @@ -13,20 +14,14 @@ namespace Snyk.VisualStudio.Extension
public static class LogManager
{
private const string OutputTemplate =
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{ProcessId:00000}] {Level:u4} [{ThreadId:00}] {ShortSourceContext,-25} {Message:lj}{NewLine}{Exception}";
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{ProcessId:00000}] {Level:u4} [{ThreadId:00}] {ThreadContext,-15} {ShortSourceContext,-25} {Message:lj}{NewLine}{Exception}";

/// <summary>
/// 10 Mb.
/// </summary>
private const int LogFileSize = 10485760;

#if DEBUG
private static LogEventLevel defaultLoggingLevel = LogEventLevel.Debug;
#else
private static LogEventLevel defaultLoggingLevel = LogEventLevel.Information;
#endif

private static LoggingLevelSwitch loggingLevelSwitch = new LoggingLevelSwitch(defaultLoggingLevel);
private static LoggingLevelSwitch loggingLevelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);

private static Lazy<Logger> Logger { get; } = new Lazy<Logger>(CreateLogger);

Expand All @@ -41,14 +36,30 @@ public static class LogManager
.Enrich.WithProcessId()
.Enrich.WithThreadId()
.Enrich.WithExceptionDetails()
.Enrich.With<ThreadContextEnricher>() // Dynamically determine the thread context
.MinimumLevel.ControlledBy(loggingLevelSwitch)
.WriteTo.File(
Path.Combine(SnykDirectory.GetSnykAppDataDirectoryPath(), "snyk-extension.log"),
fileSizeLimitBytes: LogFileSize,
rollOnFileSizeLimit:true,
outputTemplate: OutputTemplate,
shared: true)
.CreateLogger();

private static ILogger ForContext(Type type) => Logger.Value.ForContext(type).ForContext("ShortSourceContext", type.Name);
private static ILogger ForContext(Type type) => Logger.Value.ForContext(type)
.ForContext("ShortSourceContext", type.Name);
}

/// <summary>
/// Custom thread context enricher to dynamically determine if the thread is a UI thread or a background thread.
/// </summary>
public class ThreadContextEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var threadContext = ThreadHelper.CheckAccess() ? "UI Thread" : "Background Thread";
var threadContextProperty = propertyFactory.CreateProperty("ThreadContext", threadContext);
logEvent.AddPropertyIfAbsent(threadContextProperty);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,6 @@ public interface ISolutionService
/// <param name="paths">All paths.</param>
/// <returns>Root directory for all paths.</returns>
string FindRootDirectoryForSolutionProjects(string rootDir, IList<string> paths);
string SolutionFolderCache { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,20 @@ public async System.Threading.Tasks.Task<string> GetFileFullPathAsync(string fil
/// </summary>
/// <returns>Return Ok constant.</returns>
public int OnDisconnect() => VSConstants.S_OK;

public string SolutionFolderCache { get; set; }
/// <summary>
/// Get solution path. First try to get path by VS solution (solution with projects or folder).
/// If no success, try to get path for flat project (without solution) or web site (in case VS2015).
/// </summary>
/// <returns>Solution path string.</returns>
public async System.Threading.Tasks.Task<string> GetSolutionFolderAsync()
{
string solutionFolder = await this.FindRootDirectoryForSolutionAsync();
if (!string.IsNullOrEmpty(SolutionFolderCache))
{
Logger.Information("Using cached solution folder {SolutionFolder}", SolutionFolderCache);
return SolutionFolderCache;
}
var solutionFolder = await this.FindRootDirectoryForSolutionAsync();

Logger.Information("Solution folder from is {SolutionFolder}", solutionFolder);

Expand All @@ -136,7 +141,7 @@ public async System.Threading.Tasks.Task<string> GetSolutionFolderAsync()
}

Logger.Information("Result solution folder from is {SolutionFolder}", solutionFolder);

SolutionFolderCache = solutionFolder;
return solutionFolder;
}

Expand Down
33 changes: 14 additions & 19 deletions Snyk.VisualStudio.Extension.2022/Service/SnykTasksService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,16 +228,6 @@ public async Task ScanAsync()
try
{
var selectedFeatures = await this.GetFeaturesSettingsAsync();
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

if (!this.serviceProvider.SolutionService.IsSolutionOpen())
{
this.FireOssError("No open solution", selectedFeatures);

Logger.Information("Solution not opened");

return;
}

var isFolderTrusted = await this.IsFolderTrustedAsync();
if (!isFolderTrusted)
Expand All @@ -261,10 +251,11 @@ public async Task ScanAsync()
FireSnykIacDisabledError(selectedFeatures.IacEnabled);
}

var componentModel = Package.GetGlobalService(typeof(SComponentModel)) as IComponentModel;

Assumes.Present(componentModel);
var languageServerClientManager = componentModel.GetService<ILanguageClientManager>();
if (!LanguageClientHelper.IsLanguageServerReady())
{
Logger.Error("Attempting to scan and language server is not ready yet");
return;
}
this.SnykScanTokenSource = new CancellationTokenSource();

var progressWorker = new SnykProgressWorker
Expand All @@ -273,7 +264,7 @@ public async Task ScanAsync()
TokenSource = this.SnykScanTokenSource,
};

await languageServerClientManager.InvokeWorkspaceScanAsync(progressWorker.TokenSource.Token);
await LanguageClientHelper.LanguageClientManager().InvokeWorkspaceScanAsync(progressWorker.TokenSource.Token);
}
catch (Exception ex)
{
Expand All @@ -294,7 +285,7 @@ public async Task<bool> IsFolderTrustedAsync()
{
return true;
}

await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var trustDialog = new TrustDialogWindow(solutionFolderPath);
var trusted = trustDialog.ShowModal();

Expand All @@ -305,9 +296,13 @@ public async Task<bool> IsFolderTrustedAsync()

try
{
this.serviceProvider.WorkspaceTrustService.AddFolderToTrusted(solutionFolderPath);
this.serviceProvider.Options.InvokeSettingsChangedEvent();
Logger.Information("Workspace folder was trusted: {SolutionFolderPath}", solutionFolderPath);
ThreadHelper.JoinableTaskFactory.RunAsync(async () =>
{
this.serviceProvider.WorkspaceTrustService.AddFolderToTrusted(solutionFolderPath);
Logger.Information("Workspace folder was trusted: {SolutionFolderPath}", solutionFolderPath);
await this.serviceProvider.LanguageClientManager.DidChangeConfigurationAsync(SnykVSPackage
.Instance.DisposalToken);
}).FireAndForget();
return true;
}
catch (ArgumentException e)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ public void OnAfterOpenFolder(string folderPath)
/// <returns>VSConstants.S_OK.</returns>
public int OnAfterOpenProject(IVsHierarchy vsHierarchy, int fAdded)
{
if (SnykVSPackage.Instance == null || SnykVSPackage.ServiceProvider?.SolutionService == null)
{
return VSConstants.S_OK;
}
// Reset solution folder cache to force loading Solution Folder from VS API
SnykVSPackage.ServiceProvider.SolutionService.SolutionFolderCache = "";

return VSConstants.S_OK;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public void AddFolderToTrusted(string absoluteFolderPath)
var trustedFolders = this.serviceProvider.Options.TrustedFolders;
trustedFolders.Add(absoluteFolderPath);
this.serviceProvider.Options.TrustedFolders = trustedFolders;
this.serviceProvider.SnykOptionsManager.Save(this.serviceProvider.Options);
this.serviceProvider.SnykOptionsManager.Save(this.serviceProvider.Options, false);
}
catch (Exception e)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public interface ISnykOptionsManager
void LoadSettingsFromFile();
void SaveSettingsToFile();
ISnykOptions Load();
void Save(IPersistableOptions options);
void Save(IPersistableOptions options, bool triggerSettingsChangedEvent = true);

/// <summary>
/// Get CLI additional options string.
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,13 @@ private void manageBinariesAutomaticallyCheckbox_CheckedChanged(object sender, S
{
OptionsMemento.BinariesAutoUpdate = manageBinariesAutomaticallyCheckbox.Checked;
}

private void releaseChannel_SelectionChangeCommitted(object sender, System.EventArgs e)
{
var selectedItem = this.releaseChannel.SelectedItem?.ToString() ?? "";
if (string.IsNullOrEmpty(selectedItem))
return;
OptionsMemento.CliReleaseChannel = selectedItem;
}
}
}
Loading
Loading