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

Adding call for getting the sessionID of a connection #2443

Merged
merged 6 commits into from
Feb 13, 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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Workspace;
using System.Threading;
using System.Linq;

namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
{
Expand Down Expand Up @@ -87,7 +88,7 @@ internal void SetConnectionOpener(SqlConnectionOpener opener)
}

/// <summary>
/// Generate a unique key based on the ConnectionInfo object
/// Generate a unique key based on the ConnectionDetails object
/// </summary>
/// <param name="connInfo"></param>
internal static string GetConnectionContextKey(ConnectionDetails details)
Expand Down Expand Up @@ -116,7 +117,7 @@ internal static string GetConnectionContextKey(ConnectionDetails details)

// Additional properties that are used to distinguish the connection (besides password)
// These are so that multiple connections can connect to the same target, with different settings.
foreach (KeyValuePair<string, object> entry in details.Options)
foreach (KeyValuePair<string, object> entry in details.Options.OrderBy(entry => entry.Key))
{
// Filter out properties we already have or don't want (password)
if (entry.Key != "server" && entry.Key != "database" && entry.Key != "user"
Expand All @@ -142,7 +143,9 @@ internal static string GetConnectionContextKey(ConnectionDetails details)
}
}

#pragma warning disable SYSLIB0013 // we don't want to escape the ":" characters in our key-value options pairs because it's more readable
return Uri.EscapeUriString(key);
#pragma warning restore SYSLIB0013
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;

namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Contracts
{
public class GetSessionIdResponse
{
/// <summary>
/// Unique ID to use when sending any requests for objects in the
/// tree under the node
/// </summary>
public string SessionId { get; set; }
}

public class GetSessionIdRequest
{
public static readonly
RequestType<ConnectionDetails, GetSessionIdResponse> Type =
RequestType<ConnectionDetails, GetSessionIdResponse>.Create("objectexplorer/getsessionid");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ public override void InitializeService(IProtocolEndpoint serviceHost)
serviceHost.SetRequestHandler(RefreshRequest.Type, HandleRefreshRequest, true);
serviceHost.SetRequestHandler(CloseSessionRequest.Type, HandleCloseSessionRequest, true);
serviceHost.SetRequestHandler(FindNodesRequest.Type, HandleFindNodesRequest, true);
serviceHost.SetRequestHandler(GetSessionIdRequest.Type, HandleGetSessionIdRequest, true);

WorkspaceService<SqlToolsSettings> workspaceService = WorkspaceService;
if (workspaceService != null)
{
Expand Down Expand Up @@ -158,6 +160,21 @@ public Task HandleDidChangeConfigurationNotification(
return Task.FromResult(true);
}

internal async Task HandleGetSessionIdRequest(ConnectionDetails connectionDetails, RequestContext<GetSessionIdResponse> context)
{
Logger.Verbose(nameof(HandleGetSessionIdRequest));
Func<Task<GetSessionIdResponse>> getConnectionKey = async () =>
{
Validate.IsNotNull(nameof(connectionDetails), connectionDetails);
Validate.IsNotNull(nameof(context), context);
return await Task.Run(() =>
{
string key = ConnectedBindingQueue.GetConnectionContextKey(connectionDetails);
return new GetSessionIdResponse { SessionId = key };
});
};
GetSessionIdResponse response = await HandleRequestAsync(getConnectionKey, context, nameof(HandleGetSessionIdRequest));
}

internal async Task HandleCreateSessionRequest(ConnectionDetails connectionDetails, RequestContext<CreateSessionResponse> context)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
{
public class StatelessObjectExplorerServiceTests
{

string databaseName = "tempdb";

ObjectExplorerServerInfo serverInfo = new ObjectExplorerServerInfo()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
using Microsoft.SqlTools.ServiceLayer.LanguageServices;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Common.RequestContextMocking;
using Microsoft.SqlTools.Utility;

namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ObjectExplorer
{
Expand Down Expand Up @@ -309,6 +310,43 @@ public void FindNodeCanExpandParentNodes()
mockTreeNode.Protected().Verify("PopulateChildren", Times.Once(), populateChildrenArguments);
}

[Test]
public async Task VerifyGeneratesSessionId()
{
GetSessionIdResponse result = null;
string error = null;

var requestContext = RequestContextMocks.Create<GetSessionIdResponse>(r => result = r);
requestContext.AddErrorHandling((string e, int i, string s2) => error = e);

ObjectExplorerService oeService = new();

await oeService.HandleGetSessionIdRequest(new()
{
ServerName = "serverName",
DatabaseName = "msdb",
AuthenticationType = SqlConstants.ActiveDirectoryPassword,
UserName = "TestUser",
Password = "test_password",
SecureEnclaves = "fakeEnclave"

}, requestContext.Object);

Assert.That(error, Is.Null, "No error should have been sent for an invalid input");
Assert.That(result.SessionId, Does.Not.Contain("test_password"), "Password should not appear in SessionId");
Assert.That(result.SessionId, Is.EqualTo("serverName_msdb_TestUser_ActiveDirectoryPassword_secureEnclaves:fakeEnclave"), "SessionId not as expected");

// reset
result = null;
error = null;

await oeService.HandleGetSessionIdRequest(null, requestContext.Object);

Assert.That(result, Is.Null, "No result should have been sent for an invalid input");
Assert.That(error, Does.Contain("System.ArgumentNullException: Value cannot be null. (Parameter 'connectionDetails')"), "Error message about connectionDetails being null should have been sent for an invalid input");
}

#region Helper methods
private async Task<SessionCreatedParameters> CreateSession()
{
SessionCreatedParameters sessionResult = null;
Expand Down Expand Up @@ -495,5 +533,6 @@ private static ConnectionCompleteParams GetCompleteParamsForConnection(string ur
ServerInfo = TestObjects.GetTestServerInfo()
};
}
#endregion
}
}