Skip to content

Commit

Permalink
Applying PR suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
sfc-gh-jmartinezramirez committed Oct 17, 2024
1 parent 0b2c250 commit 8dbab0f
Show file tree
Hide file tree
Showing 17 changed files with 152 additions and 181 deletions.
28 changes: 7 additions & 21 deletions Snowflake.Data.Tests/IntegrationTests/SFConnectionIT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2276,36 +2276,26 @@ public void TestUseMultiplePoolsConnectionPoolByDefault()
}

[Test]
//[Ignore("This test requires manual interaction and therefore cannot be run in CI")]
public void TestMFATokenCaching()
[Ignore("This test requires manual interaction and therefore cannot be run in CI")]
public void TestMFATokenCachingWithPasscodeFromConnectionString()
{
using (SnowflakeDbConnection conn = new SnowflakeDbConnection())
{
//conn.Passcode = SecureStringHelper.Encode("123456");
conn.ConnectionString
= ConnectionString
+ ";authenticator=username_password_mfa;minPoolSize=2;application=DuoTest;authenticator=username_password_mfa;";
+ ";authenticator=username_password_mfa;application=DuoTest;Passcode=123456;";


// Authenticate to retrieve and store the token if doesn't exist or invalid
Task connectTask = conn.OpenAsync(CancellationToken.None);
connectTask.Wait();
Assert.AreEqual(ConnectionState.Open, conn.State);

// Authenticate using the MFA token cache
connectTask = conn.OpenAsync(CancellationToken.None);
connectTask.Wait();
Assert.AreEqual(ConnectionState.Open, conn.State);

connectTask = conn.CloseAsync(CancellationToken.None);
connectTask.Wait();
Assert.AreEqual(ConnectionState.Closed, conn.State);
}
}

[Test]
//[Ignore("Requires manual steps and environment with mfa authentication enrolled")] // to enroll to mfa authentication edit your user profile
public void TestMfaWithPasswordConnection()
[Ignore("Requires manual steps and environment with mfa authentication enrolled")] // to enroll to mfa authentication edit your user profile
public void TestMfaWithPasswordConnectionUsingPasscodeWithSecureString()
{
// arrange
using (SnowflakeDbConnection conn = new SnowflakeDbConnection())
Expand All @@ -2315,15 +2305,11 @@ public void TestMfaWithPasswordConnection()
conn.ConnectionString = ConnectionString + "minPoolSize=2;application=DuoTest;";

// act
conn.Open();
Thread.Sleep(3000);
conn.Close();

conn.Open();
Task connectTask = conn.OpenAsync(CancellationToken.None);
connectTask.Wait();

// assert
Assert.AreEqual(ConnectionState.Open, conn.State);
// manual action: verify that you have received no push request for given connection
}
}

Expand Down
22 changes: 10 additions & 12 deletions Snowflake.Data.Tests/UnitTests/ConnectionPoolManagerMFATest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ namespace Snowflake.Data.Tests.UnitTests
using System;
using System.Linq;
using System.Security;
using System.Threading;
using Mock;
using NUnit.Framework;
using Snowflake.Data.Core;
Expand Down Expand Up @@ -66,21 +65,20 @@ public void TestPoolManagerReturnsSessionPoolForGivenConnectionStringUsingMFA()
authResponseSessionInfo = new SessionInfo()
});
// Act
var session = _connectionPoolManager.GetSession(ConnectionStringMFACache, null);
Thread.Sleep(3000);
var session = _connectionPoolManager.GetSession(ConnectionStringMFACache, null, null);

// Assert

Awaiter.WaitUntilConditionOrTimeout(() => s_restRequester.LoginRequests.Count == 2, TimeSpan.FromSeconds(15));
Assert.AreEqual(2, s_restRequester.LoginRequests.Count);
var loginRequest1 = s_restRequester.LoginRequests.Dequeue();
Assert.AreEqual(loginRequest1.data.Token, string.Empty);
Assert.AreEqual(SecureStringHelper.Decode(session._mfaToken), testToken);
Assert.AreEqual(string.Empty, loginRequest1.data.Token);
Assert.AreEqual(testToken, SecureStringHelper.Decode(session._mfaToken));
Assert.IsTrue(loginRequest1.data.SessionParameters.TryGetValue(SFSessionParameter.CLIENT_REQUEST_MFA_TOKEN, out var value) && (bool)value);
Assert.AreEqual("passcode", loginRequest1.data.extAuthnDuoMethod);
var loginRequest2 = s_restRequester.LoginRequests.Dequeue();
Assert.AreEqual(loginRequest2.data.Token, testToken);
Assert.AreEqual(testToken, loginRequest2.data.Token);
Assert.IsTrue(loginRequest2.data.SessionParameters.TryGetValue(SFSessionParameter.CLIENT_REQUEST_MFA_TOKEN, out var value1) && (bool)value1);
Assert.AreEqual("passcode", loginRequest1.data.extAuthnDuoMethod);
Assert.AreEqual("passcode", loginRequest2.data.extAuthnDuoMethod);
}

[Test]
Expand All @@ -103,9 +101,9 @@ public void TestPoolManagerShouldOnlyUsePasscodeAsArgumentForFirstSessionWhenNot

// Act
_connectionPoolManager.GetSession(ConnectionStringMFABasicWithoutPasscode, null, SecureStringHelper.Encode(TestPasscode));
Thread.Sleep(10000);

// Assert
Awaiter.WaitUntilConditionOrTimeout(() => s_restRequester.LoginRequests.Count == 3, TimeSpan.FromSeconds(15));
Assert.AreEqual(3, s_restRequester.LoginRequests.Count);
var request = s_restRequester.LoginRequests.ToList();
Assert.AreEqual(1, request.Count(r => r.data.extAuthnDuoMethod == "passcode" && r.data.passcode == TestPasscode));
Expand All @@ -118,7 +116,7 @@ public void TestPoolManagerShouldThrowExceptionIfForcePoolingWithPasscodeNotUsin
// Arrange
var connectionString = "db=D1;warehouse=W1;account=A1;user=U1;password=P1;role=R1;minPoolSize=2;passcode=12345;POOLINGENABLED=true";
// Act and assert
var thrown = Assert.Throws<Exception>(() =>_connectionPoolManager.GetSession(connectionString, null));
var thrown = Assert.Throws<Exception>(() =>_connectionPoolManager.GetSession(connectionString, null,null));
Assert.That(thrown.Message, Does.Contain("Passcode with MinPoolSize feature of connection pool allowed only for username_password_mfa authentication"));
}

Expand All @@ -128,7 +126,7 @@ public void TestPoolManagerShouldNotThrowExceptionIfForcePoolingWithPasscodeNotU
// Arrange
var connectionString = "db=D1;warehouse=W1;account=A1;user=U1;password=P1;role=R1;minPoolSize=2;passcode=12345;POOLINGENABLED=false";
// Act and assert
Assert.DoesNotThrow(() =>_connectionPoolManager.GetSession(connectionString, null));
Assert.DoesNotThrow(() =>_connectionPoolManager.GetSession(connectionString, null, null));
}

[Test]
Expand All @@ -137,7 +135,7 @@ public void TestPoolManagerShouldNotThrowExceptionIfMinPoolSizeZeroNotUsingMFATo
// Arrange
var connectionString = "db=D1;warehouse=W1;account=A1;user=U1;password=P1;role=R1;minPoolSize=0;passcode=12345;POOLINGENABLED=true";
// Act and assert
Assert.DoesNotThrow(() =>_connectionPoolManager.GetSession(connectionString, null));
Assert.DoesNotThrow(() =>_connectionPoolManager.GetSession(connectionString, null, null));
}
}

Expand Down
6 changes: 3 additions & 3 deletions Snowflake.Data.Tests/UnitTests/ConnectionPoolManagerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public void TestDifferentPoolsAreReturnedForDifferentConnectionStrings()
public void TestGetSessionWorksForSpecifiedConnectionString()
{
// Act
var sfSession = _connectionPoolManager.GetSession(ConnectionString1, null);
var sfSession = _connectionPoolManager.GetSession(ConnectionString1, null, null);

// Assert
Assert.AreEqual(ConnectionString1, sfSession.ConnectionString);
Expand All @@ -133,7 +133,7 @@ public async Task TestGetSessionAsyncWorksForSpecifiedConnectionString()
public void TestCountingOfSessionProvidedByPool()
{
// Act
_connectionPoolManager.GetSession(ConnectionString1, null);
_connectionPoolManager.GetSession(ConnectionString1, null, null);

// Assert
var sessionPool = _connectionPoolManager.GetPool(ConnectionString1, null);
Expand All @@ -144,7 +144,7 @@ public void TestCountingOfSessionProvidedByPool()
public void TestCountingOfSessionReturnedBackToPool()
{
// Arrange
var sfSession = _connectionPoolManager.GetSession(ConnectionString1, null);
var sfSession = _connectionPoolManager.GetSession(ConnectionString1, null, null);

// Act
_connectionPoolManager.AddSession(sfSession);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
* Copyright (c) 2024 Snowflake Computing Inc. All rights reserved.
*/

using Snowflake.Data.Core;

namespace Snowflake.Data.Tests.UnitTests.CredentialManager
{
using Mono.Unix;
using Mono.Unix.Native;
using Moq;
using NUnit.Framework;
using Snowflake.Data.Client;
using Snowflake.Data.Core.CredentialManager;
using Snowflake.Data.Core.CredentialManager.Infrastructure;
using Snowflake.Data.Core.Tools;
using System;
Expand Down Expand Up @@ -48,31 +49,24 @@ public void TestSavingCredentialsForAnExistingKey()
var firstExpectedToken = "mockToken1";
var secondExpectedToken = "mockToken2";

try
{
// act
_credentialManager.SaveCredentials(key, firstExpectedToken);
// act
_credentialManager.SaveCredentials(key, firstExpectedToken);

// assert
Assert.AreEqual(firstExpectedToken, _credentialManager.GetCredentials(key));
// assert
Assert.AreEqual(firstExpectedToken, _credentialManager.GetCredentials(key));

// act
_credentialManager.SaveCredentials(key, secondExpectedToken);
// act
_credentialManager.SaveCredentials(key, secondExpectedToken);

// assert
Assert.AreEqual(secondExpectedToken, _credentialManager.GetCredentials(key));
// assert
Assert.AreEqual(secondExpectedToken, _credentialManager.GetCredentials(key));

// act
_credentialManager.RemoveCredentials(key);
// act
_credentialManager.RemoveCredentials(key);

// assert
Assert.IsTrue(string.IsNullOrEmpty(_credentialManager.GetCredentials(key)));

// assert
Assert.IsTrue(string.IsNullOrEmpty(_credentialManager.GetCredentials(key)));
}
catch (Exception ex)
{
// assert
Assert.Fail("Should not throw an exception: " + ex.Message);
}
}

[Test]
Expand All @@ -81,19 +75,11 @@ public void TestRemovingCredentialsForKeyThatDoesNotExist()
// arrange
var key = "mockKey";

try
{
// act
_credentialManager.RemoveCredentials(key);
// act
_credentialManager.RemoveCredentials(key);

// assert
Assert.IsTrue(string.IsNullOrEmpty(_credentialManager.GetCredentials(key)));
}
catch (Exception ex)
{
// assert
Assert.Fail("Should not throw an exception: " + ex.Message);
}
// assert
Assert.IsTrue(string.IsNullOrEmpty(_credentialManager.GetCredentials(key)));
}
}

Expand Down Expand Up @@ -124,11 +110,11 @@ public class SFFileCredentialManagerTest : SFBaseCredentialManagerTest
[SetUp]
public void SetUp()
{
_credentialManager = SFCredentialManagerFileImpl.Instance;
_credentialManager = SnowflakeCredentialManagerFileImpl.Instance;
}
}

[TestFixture]
[TestFixture, NonParallelizable]
class SFCredentialManagerTest
{
ISnowflakeCredentialManager _credentialManager;
Expand All @@ -147,30 +133,30 @@ class SFCredentialManagerTest

private const string CustomJsonDir = "testdirectory";

private static readonly string s_customJsonPath = Path.Combine(CustomJsonDir, SFCredentialManagerFileImpl.CredentialCacheFileName);
private static readonly string s_customJsonPath = Path.Combine(CustomJsonDir, SnowflakeCredentialManagerFileImpl.CredentialCacheFileName);

[SetUp] public void SetUp()
{
t_fileOperations = new Mock<FileOperations>();
t_directoryOperations = new Mock<DirectoryOperations>();
t_unixOperations = new Mock<UnixOperations>();
t_environmentOperations = new Mock<EnvironmentOperations>();
SFCredentialManagerFactory.SetCredentialManager(SFCredentialManagerInMemoryImpl.Instance);
SnowflakeCredentialManagerFactory.SetCredentialManager(SFCredentialManagerInMemoryImpl.Instance);
}

[TearDown] public void TearDown()
{
SFCredentialManagerFactory.UseDefaultCredentialManager();
SnowflakeCredentialManagerFactory.UseDefaultCredentialManager();
}

[Test]
public void TestUsingDefaultCredentialManager()
{
// arrange
SFCredentialManagerFactory.UseDefaultCredentialManager();
SnowflakeCredentialManagerFactory.UseDefaultCredentialManager();

// act
_credentialManager = SFCredentialManagerFactory.GetCredentialManager();
_credentialManager = SnowflakeCredentialManagerFactory.GetCredentialManager();

// assert
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
Expand All @@ -187,13 +173,13 @@ public void TestUsingDefaultCredentialManager()
public void TestSettingCustomCredentialManager()
{
// arrange
SFCredentialManagerFactory.SetCredentialManager(SFCredentialManagerFileImpl.Instance);
SnowflakeCredentialManagerFactory.SetCredentialManager(SnowflakeCredentialManagerFileImpl.Instance);

// act
_credentialManager = SFCredentialManagerFactory.GetCredentialManager();
_credentialManager = SnowflakeCredentialManagerFactory.GetCredentialManager();

// assert
Assert.IsInstanceOf<SFCredentialManagerFileImpl>(_credentialManager);
Assert.IsInstanceOf<SnowflakeCredentialManagerFileImpl>(_credentialManager);
}

[Test]
Expand All @@ -213,10 +199,10 @@ public void TestThatThrowsErrorWhenCacheFileIsNotCreated()
FilePermissions.S_IRUSR | FilePermissions.S_IWUSR | FilePermissions.S_IXUSR))
.Returns(-1);
t_environmentOperations
.Setup(e => e.GetEnvironmentVariable(SFCredentialManagerFileImpl.CredentialCacheDirectoryEnvironmentName))
.Setup(e => e.GetEnvironmentVariable(SnowflakeCredentialManagerFileImpl.CredentialCacheDirectoryEnvironmentName))
.Returns(CustomJsonDir);
SFCredentialManagerFactory.SetCredentialManager(new SFCredentialManagerFileImpl(t_fileOperations.Object, t_directoryOperations.Object, t_unixOperations.Object, t_environmentOperations.Object));
_credentialManager = SFCredentialManagerFactory.GetCredentialManager();
SnowflakeCredentialManagerFactory.SetCredentialManager(new SnowflakeCredentialManagerFileImpl(t_fileOperations.Object, t_directoryOperations.Object, t_unixOperations.Object, t_environmentOperations.Object));
_credentialManager = SnowflakeCredentialManagerFactory.GetCredentialManager();

// act
var thrown = Assert.Throws<Exception>(() => _credentialManager.SaveCredentials("key", "token"));
Expand All @@ -242,10 +228,10 @@ public void TestThatThrowsErrorWhenCacheFileCanBeAccessedByOthers()
.Setup(u => u.GetFilePermissions(s_customJsonPath))
.Returns(FileAccessPermissions.AllPermissions);
t_environmentOperations
.Setup(e => e.GetEnvironmentVariable(SFCredentialManagerFileImpl.CredentialCacheDirectoryEnvironmentName))
.Setup(e => e.GetEnvironmentVariable(SnowflakeCredentialManagerFileImpl.CredentialCacheDirectoryEnvironmentName))
.Returns(CustomJsonDir);
SFCredentialManagerFactory.SetCredentialManager(new SFCredentialManagerFileImpl(t_fileOperations.Object, t_directoryOperations.Object, t_unixOperations.Object, t_environmentOperations.Object));
_credentialManager = SFCredentialManagerFactory.GetCredentialManager();
SnowflakeCredentialManagerFactory.SetCredentialManager(new SnowflakeCredentialManagerFileImpl(t_fileOperations.Object, t_directoryOperations.Object, t_unixOperations.Object, t_environmentOperations.Object));
_credentialManager = SnowflakeCredentialManagerFactory.GetCredentialManager();

// act
var thrown = Assert.Throws<Exception>(() => _credentialManager.SaveCredentials("key", "token"));
Expand All @@ -271,15 +257,15 @@ public void TestThatJsonFileIsCheckedIfAlreadyExists()
.Setup(u => u.GetFilePermissions(s_customJsonPath))
.Returns(FileAccessPermissions.UserReadWriteExecute);
t_environmentOperations
.Setup(e => e.GetEnvironmentVariable(SFCredentialManagerFileImpl.CredentialCacheDirectoryEnvironmentName))
.Setup(e => e.GetEnvironmentVariable(SnowflakeCredentialManagerFileImpl.CredentialCacheDirectoryEnvironmentName))
.Returns(CustomJsonDir);
t_fileOperations
.SetupSequence(f => f.Exists(s_customJsonPath))
.Returns(false)
.Returns(true);

SFCredentialManagerFactory.SetCredentialManager(new SFCredentialManagerFileImpl(t_fileOperations.Object, t_directoryOperations.Object, t_unixOperations.Object, t_environmentOperations.Object));
_credentialManager = SFCredentialManagerFactory.GetCredentialManager();
SnowflakeCredentialManagerFactory.SetCredentialManager(new SnowflakeCredentialManagerFileImpl(t_fileOperations.Object, t_directoryOperations.Object, t_unixOperations.Object, t_environmentOperations.Object));
_credentialManager = SnowflakeCredentialManagerFactory.GetCredentialManager();

// act
_credentialManager.SaveCredentials("key", "token");
Expand Down
1 change: 0 additions & 1 deletion Snowflake.Data.Tests/UnitTests/SFSessionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using NUnit.Framework;
using Snowflake.Data.Core.Tools;
using Snowflake.Data.Tests.Mock;
using System;

namespace Snowflake.Data.Tests.UnitTests
{
Expand Down
Loading

0 comments on commit 8dbab0f

Please sign in to comment.