Fix a number of cred scan hits (#800)

Bunch of secrets in files, usually fixed by generating random password. The deleted script files didn't seem to be used anywhere.
This commit is contained in:
Charles Gagnon
2019-04-24 13:31:34 -07:00
committed by GitHub
parent e9bf57bc67
commit 85f34b65f1
9 changed files with 119 additions and 665 deletions

View File

@@ -16,6 +16,7 @@ using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Contracts;
using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes; using Microsoft.SqlTools.ServiceLayer.ObjectExplorer.Nodes;
using Microsoft.SqlTools.ServiceLayer.Test.Common; using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Common.Baselined; using Microsoft.SqlTools.ServiceLayer.Test.Common.Baselined;
using Microsoft.SqlTools.ServiceLayer.Test.Common.Extensions;
using Xunit; using Xunit;
using static Microsoft.SqlTools.ServiceLayer.ObjectExplorer.ObjectExplorerService; using static Microsoft.SqlTools.ServiceLayer.ObjectExplorer.ObjectExplorerService;
@@ -50,13 +51,13 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
[Fact] [Fact]
public async void VerifyServerLogins() public async void VerifyServerLogins()
{ {
var query = @"If Exists (select loginname from master.dbo.syslogins var query = $@"If Exists (select loginname from master.dbo.syslogins
where name = 'OEServerLogin') where name = 'OEServerLogin')
Begin Begin
Drop Login [OEServerLogin] Drop Login [OEServerLogin]
End End
CREATE LOGIN OEServerLogin WITH PASSWORD = 'SuperSecret52&&' CREATE LOGIN OEServerLogin WITH PASSWORD = '{Guid.NewGuid()}'
GO GO
ALTER LOGIN OEServerLogin DISABLE; "; ALTER LOGIN OEServerLogin DISABLE; ";
string databaseName = "tempdb"; string databaseName = "tempdb";
@@ -69,7 +70,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
var loginsChildren = (await _service.ExpandNode(session, loginsNode.NodePath)).Nodes; var loginsChildren = (await _service.ExpandNode(session, loginsNode.NodePath)).Nodes;
var login = loginsChildren.FirstOrDefault(x => x.Label == "OEServerLogin"); var login = loginsChildren.FirstOrDefault(x => x.Label == "OEServerLogin");
Assert.NotNull(login); Assert.NotNull(login);
Assert.True(login.NodeStatus == "Disabled"); Assert.True(login.NodeStatus == "Disabled");
await TestServiceProvider.Instance.RunQueryAsync(TestServerType.OnPrem, testDbName, "Drop Login OEServerLogin"); await TestServiceProvider.Instance.RunQueryAsync(TestServerType.OnPrem, testDbName, "Drop Login OEServerLogin");
@@ -80,19 +81,19 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
public async void VerifyServerTriggers() public async void VerifyServerTriggers()
{ {
var query = @"IF EXISTS (SELECT * FROM sys.server_triggers WHERE name = 'OE_ddl_trig_database') var query = @"IF EXISTS (SELECT * FROM sys.server_triggers WHERE name = 'OE_ddl_trig_database')
Begin Begin
DROP TRIGGER OE_ddl_trig_database ON ALL SERVER DROP TRIGGER OE_ddl_trig_database ON ALL SERVER
ENd ENd
GO GO
CREATE TRIGGER OE_ddl_trig_database CREATE TRIGGER OE_ddl_trig_database
ON ALL SERVER ON ALL SERVER
FOR CREATE_DATABASE FOR CREATE_DATABASE
AS AS
PRINT 'Database Created.' PRINT 'Database Created.'
GO GO
GO GO
Disable TRIGGER OE_ddl_trig_database ON ALL SERVER ;"; Disable TRIGGER OE_ddl_trig_database ON ALL SERVER ;";
string databaseName = "tempdb"; string databaseName = "tempdb";
@@ -152,7 +153,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
{ {
var query = "ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE"; var query = "ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE";
string databaseName = "master"; string databaseName = "master";
await RunTest(databaseName, query, "OfflineDb", async (testDbName, session) => await RunTest(databaseName, query, "OfflineDb", async (testDbName, session) =>
{ {
var databaseNode = await ExpandServerNodeAndVerifyDatabaseHierachy(testDbName, session); var databaseNode = await ExpandServerNodeAndVerifyDatabaseHierachy(testDbName, session);
@@ -191,7 +192,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
//Tables still includes t1 //Tables still includes t1
Assert.True(tableChildren.Nodes.Any(t => t.Label == "dbo.t1")); Assert.True(tableChildren.Nodes.Any(t => t.Label == "dbo.t1"));
//Verify the tables cache has items //Verify the tables cache has items
var rootChildrenCache = session.Root.GetChildren(); var rootChildrenCache = session.Root.GetChildren();
var tablesCache = rootChildrenCache.First(x => x.Label == SR.SchemaHierarchy_Tables).GetChildren(); var tablesCache = rootChildrenCache.First(x => x.Label == SR.SchemaHierarchy_Tables).GetChildren();
@@ -264,8 +265,9 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Failed to run OE test. uri:{uri} error:{ex.Message} {ex.StackTrace}"); string msg = ex.BuildRecursiveErrorMessage();
Assert.False(true, ex.Message); Console.WriteLine($"Failed to run OE test. uri:{uri} error:{msg} {ex.StackTrace}");
Assert.False(true, msg);
} }
finally finally
{ {
@@ -298,7 +300,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
Assert.NotNull(session.Root); Assert.NotNull(session.Root);
NodeInfo nodeInfo = session.Root.ToNodeInfo(); NodeInfo nodeInfo = session.Root.ToNodeInfo();
Assert.Equal(nodeInfo.IsLeaf, false); Assert.Equal(nodeInfo.IsLeaf, false);
NodeInfo databaseNode = null; NodeInfo databaseNode = null;
if (serverNode) if (serverNode)
@@ -460,7 +462,7 @@ namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.ObjectExplorer
BaselinedTest.CompareActualWithBaseline(actual, baseline); BaselinedTest.CompareActualWithBaseline(actual, baseline);
} }
}); });
return true; return true;
} }

View File

@@ -0,0 +1,25 @@
using System;
using System.Text;
namespace Microsoft.SqlTools.ServiceLayer.Test.Common.Extensions
{
public static class ExceptionExtensions
{
/// <summary>
/// Builds a string containing the exception messages and all messages of child InnerExceptions.
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public static string BuildRecursiveErrorMessage(this Exception e)
{
var msg = new StringBuilder();
while (e != null)
{
msg.AppendLine(e.Message);
e = e.InnerException;
}
return msg.ToString();
}
}
}

View File

@@ -1,275 +0,0 @@
ALTER DATABASE current SET COMPATIBILITY_LEVEL=130
GO
/* Dropping previous master key in master db that could have been created from other runs */
IF ( EXISTS(SELECT name FROM sys.symmetric_keys WHERE name = '##MS_DatabaseMasterKey##')) DROP MASTER KEY
CREATE MASTER KEY ENCRYPTION BY PASSWORD= 'Password01!';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'Password01!';
CREATE DATABASE SCOPED CREDENTIAL AlterEgo WITH IDENTITY = 'RettigB',
SECRET = 'sdrlk8$40-dksli87nNN8';
GO
-- Row-Level Security
CREATE TABLE [dbo].[Sales1]
(
OrderID INT,
SalesRep SYSNAME NOT NULL,
Product VARCHAR(10),
Qty INT
);
GO
CREATE TABLE [dbo].[Sales2]
(
OrderID INT,
SalesRep SYSNAME NOT NULL,
Product VARCHAR(10),
Qty INT
);
GO
CREATE FUNCTION [dbo].[fn_securitypredicate](@SalesRep AS SYSNAME)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS fn_securitypredicate_result
WHERE @SalesRep = USER_NAME() OR USER_NAME() = 'Manager';
GO
CREATE SECURITY POLICY [dbo].[SalesFilter]
ADD FILTER PREDICATE [dbo].[fn_securitypredicate]([SalesRep]) ON [dbo].[Sales1],
ADD FILTER PREDICATE [dbo].[fn_securitypredicate]([SalesRep]) ON [dbo].[Sales2],
ADD BLOCK PREDICATE [dbo].[fn_securitypredicate]([SalesRep]) ON [dbo].[Sales1],
ADD BLOCK PREDICATE [dbo].[fn_securitypredicate]([SalesRep]) ON [dbo].[Sales2] AFTER UPDATE
WITH (STATE = OFF)
NOT FOR REPLICATION
GO
CREATE COLUMN MASTER KEY CMK1
WITH (
KEY_STORE_PROVIDER_NAME = 'MSSQL_CERTIFICATE_STORE',
KEY_PATH = 'Current User/Personal/f2260f28d909d21c642a3d8e0b45a830e79a1420'
);
GO
CREATE COLUMN MASTER KEY CMK2
WITH (
KEY_STORE_PROVIDER_NAME = 'MSSQL_CERTIFICATE_STORE',
KEY_PATH = 'Current User/Personal/f2260f28d909d21c642a3d8e0b45a830e79a1420'
);
GO
CREATE COLUMN ENCRYPTION KEY TwoValueCEK
WITH VALUES
(
COLUMN_MASTER_KEY = CMK1,
ALGORITHM = 'RSA_OAEP',
ENCRYPTED_VALUE = 0x016E000001630075007200720065006E00740075007300650072002F006D0079002F0037006300380061003100310033003400320037003800620037003000630038003100390062003900630039003400360061006600340039006500610030003200650038006200650038003400340065006C33A82ECF04A7185824B4545457AC5244CD9C219E64067B9520C0081B8399B58C2863F7494ABE3694BD87D55FFD7576FFDC47C28F94ECC99577DF4FB8FA19AA95764FEF889CDE0F176DA5897B74382FBB22756CE2921050A09201A0EB6AF3D6091014C30146EA62635EE8CBF0A8074DEDFF125CEA80D1C0F5E8C58750A07D270E2A8BF824EE4C0C156366BF26D38CCE49EBDD5639A2DF029A7DBAE5A5D111F2F2FA3246DF8C2FA83C1E542C10570FADA98F6B29478DC58CE5CBDD407CCEFCDB97814525F6F32BECA266014AC346AC39C4F185C6C0F0A24FEC4DFA015649624692DE7865B9827BA22C3B574C9FD169F822B609F902288C5880EB25F14BD990D871B1BC4BA3A5B237AF76D26354773FA2A25CF4511AF58C911E601CFCB1905128C997844EED056C2AE7F0B48700AB41307E470FF9520997D0EB0D887DE11AFE574FFE845B7DC6C03FEEE8D467236368FC0CB2FDBD54DADC65B10B3DE6C80DF8B7B3F8F3CE5BE914713EE7B1FA5B7A578359592B8A5FDFDDE5FF9F392BC87C3CD02FBA94582AC063BBB9FFAC803FD489E16BEB28C4E3374A8478C737236A0B232F5A9DDE4D119573F1AEAE94B2192B81575AD6F57E670C1B2AB91045124DFDAEC2898F3F0112026DFC93BF9391D667D1AD7ED7D4E6BB119BBCEF1D1ADA589DD3E1082C3DAD13223BE438EB9574DA04E9D8A06320CAC6D3EC21D5D1C2A0AA484C7C
),
(
COLUMN_MASTER_KEY = CMK2,
ALGORITHM = 'RSA_OAEP',
ENCRYPTED_VALUE = 0x016E000001630075007200720065006E00740075007300650072002F006D0079002F0064006500650063006200660034006100340031003000380034006200350033003200360066003200630062006200350030003600380065003900620061003000320030003600610037003800310066001DDA6134C3B73A90D349C8905782DD819B428162CF5B051639BA46EC69A7C8C8F81591A92C395711493B25DCBCCC57836E5B9F17A0713E840721D098F3F8E023ABCDFE2F6D8CC4339FC8F88630ED9EBADA5CA8EEAFA84164C1095B12AE161EABC1DF778C07F07D413AF1ED900F578FC00894BEE705EAC60F4A5090BBE09885D2EFE1C915F7B4C581D9CE3FDAB78ACF4829F85752E9FC985DEB8773889EE4A1945BD554724803A6F5DC0A2CD5EFE001ABED8D61E8449E4FAA9E4DD392DA8D292ECC6EB149E843E395CDE0F98D04940A28C4B05F747149B34A0BAEC04FFF3E304C84AF1FF81225E615B5F94E334378A0A888EF88F4E79F66CB377E3C21964AACB5049C08435FE84EEEF39D20A665C17E04898914A85B3DE23D56575EBC682D154F4F15C37723E04974DB370180A9A579BC84F6BC9B5E7C223E5CBEE721E57EE07EFDCC0A3257BBEBF9ADFFB00DBF7EF682EC1C4C47451438F90B4CF8DA709940F72CFDC91C6EB4E37B4ED7E2385B1FF71B28A1D2669FBEB18EA89F9D391D2FDDEA0ED362E6A591AC64EF4AE31CA8766C259ECB77D01A7F5C36B8418F91C1BEADDD4491C80F0016B66421B4B788C55127135DA2FA625FB7FD195FB40D90A6C67328602ECAF3EC4F5894BFD84A99EB4753BE0D22E0D4DE6A0ADFEDC80EB1B556749B4A8AD00E73B329C95827AB91C0256347E85E3C5FD6726D0E1FE82C925D3DF4A9
);
GO
CREATE TABLE Customers (
CustName nvarchar(60),
SSN varchar(11)
COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = TwoValueCEK,
ENCRYPTION_TYPE = DETERMINISTIC ,
ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256'),
Age int NULL,
ACTNO varchar(11)
ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = TwoValueCEK,
ENCRYPTION_TYPE = RANDOMIZED,
ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256')
);
GO
USE [$(DatabaseName)]
GO
DBCC TRACEON(4631,-1)
GO
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'Password01!';
CREATE DATABASE SCOPED CREDENTIAL cred1 WITH IDENTITY = 'test_user', SECRET = '$(Secret)';
CREATE EXTERNAL DATA SOURCE eds1
WITH (
TYPE = HADOOP,
LOCATION = '$(DataSourceLocation)',
CREDENTIAL = cred1
);
CREATE EXTERNAL DATA SOURCE eds2
WITH (
TYPE = HADOOP,
LOCATION = '$(DataSourceLocation)'
);
CREATE EXTERNAL FILE FORMAT eff1
WITH (
FORMAT_TYPE = DELIMITEDTEXT
);
CREATE EXTERNAL FILE FORMAT eff2
WITH (
FORMAT_TYPE = ORC
);
CREATE EXTERNAL FILE FORMAT eff3
WITH (
FORMAT_TYPE = PARQUET
);
CREATE EXTERNAL FILE FORMAT eff4
WITH (
FORMAT_TYPE = RCFILE,
SERDE_METHOD = 'org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe'
);
CREATE EXTERNAL FILE FORMAT eff5
WITH (
FORMAT_TYPE = DELIMITEDTEXT,
FORMAT_OPTIONS (FIELD_TERMINATOR = '|', STRING_DELIMITER = ';', DATE_FORMAT = 'MM-dd-yyyy', USE_TYPE_DEFAULT = FALSE)
);
CREATE EXTERNAL FILE FORMAT eff6
WITH (
FORMAT_TYPE = DELIMITEDTEXT,
FORMAT_OPTIONS (FIELD_TERMINATOR = '|')
);
CREATE EXTERNAL FILE FORMAT eff7
WITH (
FORMAT_TYPE = DELIMITEDTEXT,
FORMAT_OPTIONS (DATE_FORMAT = 'MM-dd-yyyy', FIELD_TERMINATOR = '|')
);
CREATE EXTERNAL FILE FORMAT eff8
WITH (
FORMAT_TYPE = DELIMITEDTEXT,
FORMAT_OPTIONS (DATE_FORMAT = 'MM-dd-yyyy', FIELD_TERMINATOR = '|', STRING_DELIMITER = ';')
);
CREATE EXTERNAL FILE FORMAT eff9
WITH (
FORMAT_TYPE = DELIMITEDTEXT,
FORMAT_OPTIONS (DATE_FORMAT = 'MM-dd-yyyy', FIELD_TERMINATOR = '|', STRING_DELIMITER = ';'),
DATA_COMPRESSION = 'org.apache.hadoop.io.compress.GzipCodec'
);
CREATE EXTERNAL FILE FORMAT eff10
WITH (
FORMAT_TYPE = RCFILE,
SERDE_METHOD = 'org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe',
DATA_COMPRESSION = 'org.apache.hadoop.io.compress.DefaultCodec'
);
CREATE EXTERNAL FILE FORMAT eff11
WITH (
FORMAT_TYPE = ORC,
DATA_COMPRESSION = 'org.apache.hadoop.io.compress.SnappyCodec'
);
CREATE EXTERNAL FILE FORMAT eff12
WITH (
FORMAT_TYPE = PARQUET,
DATA_COMPRESSION = 'org.apache.hadoop.io.compress.SnappyCodec'
);
CREATE EXTERNAL TABLE bands1
(
id INTEGER NOT NULL,
name VARCHAR(50) NOT NULL,
origin CHAR(3),
rate FLOAT,
experience SMALLINT
)
WITH (
LOCATION = '/bands.dat',
DATA_SOURCE = eds1,
FILE_FORMAT = eff1
);
CREATE EXTERNAL TABLE bands2
(
id INTEGER NOT NULL,
name VARCHAR(50) NOT NULL,
origin CHAR(3),
rate FLOAT,
experience SMALLINT
)
WITH (
LOCATION = '/bands.dat',
DATA_SOURCE = eds2,
FILE_FORMAT = eff1
);
CREATE EXTERNAL TABLE bands3
(
id INTEGER NOT NULL,
name VARCHAR(50) NOT NULL,
origin CHAR(3),
rate FLOAT,
experience SMALLINT
)
WITH (
LOCATION = '/bands.dat',
DATA_SOURCE = eds2,
FILE_FORMAT = eff1,
REJECT_TYPE = VALUE,
REJECT_VALUE = 0
);
CREATE EXTERNAL TABLE bands4
(
id INTEGER NOT NULL,
name VARCHAR(50) NOT NULL,
origin CHAR(3),
rate FLOAT,
experience SMALLINT
)
WITH (
LOCATION = '/bands.dat',
DATA_SOURCE = eds1,
FILE_FORMAT = eff1,
REJECT_TYPE = PERCENTAGE,
REJECT_VALUE = 30.5,
REJECT_SAMPLE_VALUE = 10
);
CREATE EXTERNAL TABLE bands5
(
id INTEGER NOT NULL,
name VARCHAR(50) NOT NULL,
origin CHAR(3),
rate FLOAT,
experience SMALLINT
)
WITH (
LOCATION = '/bands.dat',
DATA_SOURCE = eds1,
FILE_FORMAT = eff1,
REJECT_TYPE = VALUE,
REJECT_VALUE = 30
);

View File

@@ -1,298 +0,0 @@
-- create signature
ADD SIGNATURE TO [Procedure1]
BY CERTIFICATE [Certificate1]
WITH PASSWORD = 'pGFD4bb925DGvbd2439587y' ;
GO
--Create a queue to receive messages.
CREATE QUEUE NotifyQueue ;
GO
--Create a service on the queue that references
--the event notifications contract.
CREATE SERVICE NotifyService
ON QUEUE NotifyQueue
([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification]);
GO
--Create the event notification on queue.
CREATE EVENT NOTIFICATION Notify_ALTER_T1
ON QUEUE notifyqueue
FOR QUEUE_ACTIVATION
TO SERVICE 'NotifyService',
'8140a771-3c4b-4479-8ac0-81008ab17984';
GO
--Create the event notification on database
CREATE EVENT NOTIFICATION Notify_ALTER_T1
ON DATABASE
FOR ALTER_TABLE
TO SERVICE 'NotifyService',
'8140a771-3c4b-4479-8ac0-81008ab17984';
GO
CREATE FUNCTION [dbo].[TableFunctionWithComputedColumns]
(
-- Add the parameters for the function here
@p1 int = 2,
@p2 nchar(10) = NUll
)
RETURNS
@Table_Var TABLE
(
-- Add the column definitions for the TABLE variable here
c1 int,
c2 nchar(10),
c3 AS 1 * 3
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
INSERT INTO @Table_Var
SELECT a.column_1, a.column_2
FROM Table_1 a
WHERE a.column_1 > 5
INSERT INTO @Table_Var
SELECT column_1, 'From 2'
FROM Table_2
WHERE @p1 > column_1
RETURN
END
GO
CREATE FUNCTION [dbo].[TableFunctionWithComputedColumnsEncrypted]
(
-- Add the parameters for the function here
@p1 int = 2,
@p2 nchar(10)
)
RETURNS
@Table_Var TABLE
(
-- Add the column definitions for the TABLE variable here
c1 int,
c2 nchar(10),
c3 AS 1 * 3
)
WITH ENCRYPTION
AS
BEGIN
-- Fill the table variable with the rows for your result set
INSERT INTO @Table_Var
SELECT a.column_1, a.column_2
FROM Table_1 a
WHERE a.column_1 > 5
INSERT INTO @Table_Var
SELECT column_1, 'From 2'
FROM Table_2
WHERE @p1 > column_1
RETURN
END
GO
Create table [dbo].[referenced_table] (C1 int, C2 int);
GO
CREATE PROCEDURE GetReferenedTable
AS
BEGIN
SELECT * from [dbo].[referenced_table];
END
GO
exec sp_addextendedproperty N'microsoft_database_tools_support', 'GetReferenedTable', N'SCHEMA', 'dbo', N'PROCEDURE' ,'GetReferenedTable'
GO
DISABLE TRIGGER [Trigger_1]
ON DATABASE;
GO
CREATE VIEW [dbo].[View_2] (c1)
AS
SELECT column_1 as c1
FROM dbo.Table_1
GO
exec sp_addextendedproperty 'prop_ex', 'Table_1', 'SCHEMA', 'dbo', 'TABLE', 'Table_1'
GO
exec sp_addextendedproperty 'prop_ex', 'column_1', 'SCHEMA', 'dbo', 'TABLE', 'Table_1', 'COLUMN', 'column_1'
GO
CREATE TABLE dbo.MultipleIndexTable
( [c1] INT NOT NULL CHECK (c1 > 0),
[c2] int default 10 null,
PRIMARY KEY NONCLUSTERED (c1 ASC),
UNIQUE CLUSTERED (c1 ASC, c2 DESC)
)
GO
CREATE TRIGGER [Trigger_2]
ON DATABASE
FOR DROP_TABLE
AS
SELECT COUNT(column_1) from dbo.Table_1
RAISERROR ('You must disable Trigger "Trigger_1" to drop synonyms!',10, 1)
ROLLBACK
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
DISABLE TRIGGER [Trigger_1] ON DATABASE
GO
GO
CREATE TABLE dbo.Table_3
(
c1 int,
c2 int,
) ON PartitionScheme(c1)
GO
CREATE TABLE [dbo].[Different_WithAppend_Table](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Col] [char](1) NULL
) ON [PRIMARY]
GO
CREATE FUNCTION [dbo].[EncryptedFunctionWithConstraints]
(@p1 INT)
RETURNS
@GeneratedTableName TABLE (
[c0] INT NOT NULL PRIMARY KEY,
[c1] INT DEFAULT ((1)) NULL,
[c2] NCHAR (10) NULL,
[c3] INT UNIQUE ,
CHECK ([c1]>(0)))
WITH ENCRYPTION
AS
BEGIN
insert into @GeneratedTableName values (1,1, 'abc',1);
RETURN
END
GO
CREATE TABLE [[] (c1 int)
GO
CREATE TABLE []]] (c1 int)
GO
CREATE TABLE [asdf'[] (c1 int)
GO
CREATE TABLE [5] (c1 int)
GO
-- Casing of NULL is explicit 'NUll'
CREATE PROC CasingOnDefaultValue @param1 int = NUll, @param2 nvarchar(123) = N'abc'
AS
BEGIN
select 1 as a
END
-- permissions
GO
CREATE USER nologon4 without login
GO
GRANT VIEW DEFINITION ON CasingOnDefaultValue to nologon4
GO
CREATE USER granter without login
GO
GRANT CONNECT TO granter WITH GRANT OPTION;
GO
DENY CONNECT TO nologon4 CASCADE AS granter;
GO
GRANT VIEW DEFINITION ON [5] to nologon4
GO
GRANT VIEW DEFINITION ON [[] TO nologon4
GO
GRANT VIEW DEFINITION ON []]] TO nologon4
GO
GRANT VIEW DEFINITION ON [asdf'[] TO nologon4
GO
GRANT SELECT ON dbo.Table_1 to nologon4
GO
GRANT SELECT ON dbo.Table_2 to nologon4
GO
REVOKE SELECT ON dbo.Table_2(column_2) TO nologon4
GO
GRANT SELECT ON dbo.View_1 to nologon4
GO
GRANT SELECT ON dbo.EncryptedView(A) to nologon4
GO
GRANT EXECUTE ON dbo.Procedure1 TO nologon4
GO
GRANT EXECUTE ON dbo.CLR_SimpleResultsetProcedure TO nologon4
GO
GRANT EXECUTE ON dbo.EncryptedProcedure TO nologon4
GO
GRANT VIEW DEFINITION ON CERTIFICATE :: Certificate1 TO nologon4
GO
GRANT EXECUTE ON dbo.ScalarFunction1 TO nologon4
GO
GRANT EXECUTE ON dbo.EncryptedFunction TO nologon4
GO
GRANT SELECT ON dbo.InlineFunction_1 TO nologon4
GO
GRANT SELECT ON dbo.TableFunction1 TO nologon4
GO
GRANT SELECT ON dbo.CLRTableValueFunction TO nologon4
GO
GRANT VIEW DEFINITION ON TYPE::dbo.dataType To nologon4
GO
GRANT VIEW DEFINITION ON FULLTEXT CATALOG ::FullTextCatalog1 To nologon4
GO
GRANT VIEW DEFINITION ON XML SCHEMA COLLECTION :: dbo.XmlSchemaCollection To nologon4
GO
GRANT VIEW DEFINITION ON ASSEMBLY :: [Geometry] To nologon4
GO
GRANT VIEW DEFINITION ON TYPE:: dbo.Angle To nologon4
GO
GRANT VIEW DEFINITION ON dbo.[Concat] To nologon4
GO
GRANT VIEW DEFINITION ON dbo.Synonym_1 To nologon4
GO
GRANT VIEW DEFINITION ON SCHEMA :: Schema1 To nologon4
GO
GRANT VIEW DEFINITION ON SYMMETRIC KEY :: SymKey1 To nologon4
GO
GRANT VIEW DEFINITION ON ASYMMETRIC KEY :: AsmKey1 To nologon4
GO
GRANT VIEW DEFINITION ON dbo.Queue1 To nologon4
GO
GRANT VIEW DEFINITION ON dbo.NotifyQueue To nologon4
GO
GRANT VIEW DEFINITION ON SERVICE :: Service1 To nologon4
GO
GRANT VIEW DEFINITION ON SERVICE :: NotifyService To nologon4
GO
GRANT VIEW DEFINITION ON CONTRACT :: Contract1 To nologon4
GO
GRANT VIEW DEFINITION ON MESSAGE TYPE :: MessageType1 To nologon4
GO
GRANT VIEW DEFINITION ON ROUTE :: AutoCreatedLocal To nologon4
GO
GRANT VIEW DEFINITION ON ROUTE :: Route1 To nologon4
GO
GRANT VIEW DEFINITION ON REMOTE SERVICE BINDING :: ServiceBinding1 To nologon4
GO
GRANT SELECT ON dbo.referenced_table To nologon4
GO
GRANT SELECT ON dbo.TableFunctionWithComputedColumns To nologon4
GO
GRANT SELECT ON dbo.TableFunctionWithComputedColumnsEncrypted To nologon4
GO
GRANT SELECT ON dbo.View_2 TO nologon4
GO
GRANT SELECT ON dbo.MultipleIndexTable TO nologon4
GO
GRANT SELECT ON dbo.Table_3 TO nologon4
GO
GRANT SELECT ON dbo.Different_WithAppend_Table TO nologon4
GO
GRANT SELECT ON dbo.[EncryptedFunctionWithConstraints] TO nologon4
GO

View File

@@ -90,9 +90,9 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
public async Task ScriptTable() public async Task ScriptTable()
{ {
using (TestServiceDriverProvider testService = new TestServiceDriverProvider()) using (TestServiceDriverProvider testService = new TestServiceDriverProvider())
{ {
ScriptingParams requestParams = new ScriptingParams ScriptingParams requestParams = new ScriptingParams
{ {
ScriptDestination = "ToEditor", ScriptDestination = "ToEditor",
ConnectionString = this.Northwind.ConnectionString, ConnectionString = this.Northwind.ConnectionString,
ScriptOptions = new ScriptOptions ScriptOptions = new ScriptOptions
@@ -269,8 +269,8 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
{ {
ScriptingParams requestParams = new ScriptingParams ScriptingParams requestParams = new ScriptingParams
{ {
FilePath = "This path doesn't event exist", FilePath = "This path doesn't even exist",
ConnectionString = "Server=Temp;Database=Temp;User Id=Temp;Password=Temp", ConnectionString = "Server=Temp;Database=Temp;User Id=Temp;",
ScriptOptions = new ScriptOptions ScriptOptions = new ScriptOptions
{ {
TypeOfDataToScript = "SchemaAndData", TypeOfDataToScript = "SchemaAndData",
@@ -298,7 +298,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TestDriver.Tests
ScriptOptions = new ScriptOptions ScriptOptions = new ScriptOptions
{ {
}, },
ScriptingObjects = new List<ScriptingObject> ScriptingObjects = new List<ScriptingObject>
{ {
new ScriptingObject new ScriptingObject
{ {

View File

@@ -64,7 +64,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
CancellationToken token; CancellationToken token;
bool ready = false; bool ready = false;
mockConnection.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>())) mockConnection.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>()))
.Callback<CancellationToken>(t => .Callback<CancellationToken>(t =>
{ {
// Pass the token to the return handler and signal the main thread to cancel // Pass the token to the return handler and signal the main thread to cancel
token = t; token = t;
@@ -107,7 +107,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
// Wait for the connection task to finish // Wait for the connection task to finish
connectTask.Wait(); connectTask.Wait();
// Verify that the connection was cancelled (no connection was created) // Verify that the connection was cancelled (no connection was created)
Assert.Null(connectTask.Result.ConnectionId); Assert.Null(connectTask.Result.ConnectionId);
@@ -125,7 +125,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
CancellationToken token; CancellationToken token;
bool ready = false; bool ready = false;
mockConnection.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>())) mockConnection.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>()))
.Callback<CancellationToken>(t => .Callback<CancellationToken>(t =>
{ {
// Pass the token to the return handler and signal the main thread to cancel // Pass the token to the return handler and signal the main thread to cancel
token = t; token = t;
@@ -139,7 +139,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
} }
return Task.FromResult(true); return Task.FromResult(true);
}); });
// Given a second connection that succeeds // Given a second connection that succeeds
var mockConnection2 = new Mock<DbConnection> { CallBase = true }; var mockConnection2 = new Mock<DbConnection> { CallBase = true };
mockConnection2.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>())) mockConnection2.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>()))
@@ -175,7 +175,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
// Wait for the first connection task to finish // Wait for the first connection task to finish
connectTask.Wait(); connectTask.Wait();
// Verify that the first connection was cancelled (no connection was created) // Verify that the first connection was cancelled (no connection was created)
Assert.Null(connectTask.Result.ConnectionId); Assert.Null(connectTask.Result.ConnectionId);
@@ -193,13 +193,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
CancellationToken token; CancellationToken token;
bool ready = false; bool ready = false;
mockConnection.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>())) mockConnection.Setup(x => x.OpenAsync(It.IsAny<CancellationToken>()))
.Callback<CancellationToken>(t => .Callback<CancellationToken>(t =>
{ {
// Pass the token to the return handler and signal the main thread to cancel // Pass the token to the return handler and signal the main thread to cancel
token = t; token = t;
ready = true; ready = true;
}) })
.Returns(() => .Returns(() =>
{ {
if (TestUtils.WaitFor(() => token.IsCancellationRequested)) if (TestUtils.WaitFor(() => token.IsCancellationRequested))
{ {
@@ -236,7 +236,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
// Wait for the first connection task to finish // Wait for the first connection task to finish
connectTask.Wait(); connectTask.Wait();
// Verify that the first connection was cancelled (no connection was created) // Verify that the first connection was cancelled (no connection was created)
Assert.Null(connectTask.Result.ConnectionId); Assert.Null(connectTask.Result.ConnectionId);
@@ -263,7 +263,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
OwnerUri = "file:///my/test/file.sql", OwnerUri = "file:///my/test/file.sql",
Connection = connectionDetails Connection = connectionDetails
}); });
// check that a connection was created // check that a connection was created
Assert.NotEmpty(connectionResult.ConnectionId); Assert.NotEmpty(connectionResult.ConnectionId);
} }
@@ -319,10 +319,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
const string otherDbName = "other"; const string otherDbName = "other";
// Given a connection that returns the database name // Given a connection that returns the database name
var dummySqlConnection = new TestSqlConnection(null); var dummySqlConnection = new TestSqlConnection(null);
var mockFactory = new Mock<ISqlConnectionFactory>(); var mockFactory = new Mock<ISqlConnectionFactory>();
mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>(), It.IsAny<string>())) mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>(), It.IsAny<string>()))
.Returns((string connString, string azureAccountToken) => .Returns((string connString, string azureAccountToken) =>
{ {
dummySqlConnection.ConnectionString = connString; dummySqlConnection.ConnectionString = connString;
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(connString); SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(connString);
@@ -388,7 +388,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
ServerName = testConnectionDetails.ServerName, ServerName = testConnectionDetails.ServerName,
DatabaseName = testConnectionDetails.DatabaseName, DatabaseName = testConnectionDetails.DatabaseName,
UserName = "invalidUsername", UserName = "invalidUsername",
Password = "invalidPassword" Password = Guid.NewGuid().ToString()
}; };
// triggers exception when opening mock connection // triggers exception when opening mock connection
@@ -438,7 +438,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
AuthenticationType = authType AuthenticationType = authType
} }
}); });
// check that an error was caught // check that an error was caught
Assert.NotNull(connectionResult.Messages); Assert.NotNull(connectionResult.Messages);
Assert.NotEqual(String.Empty, connectionResult.Messages); Assert.NotEqual(String.Empty, connectionResult.Messages);
@@ -472,7 +472,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
AuthenticationType = "Integrated" AuthenticationType = "Integrated"
} }
}); });
// check that the connection was successful // check that the connection was successful
Assert.NotEmpty(connectionResult.ConnectionId); Assert.NotEmpty(connectionResult.ConnectionId);
} }
@@ -487,7 +487,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
var connectionResult = await var connectionResult = await
TestObjects.GetTestConnectionService() TestObjects.GetTestConnectionService()
.Connect(null); .Connect(null);
// check that an error was caught // check that an error was caught
Assert.NotNull(connectionResult.Messages); Assert.NotNull(connectionResult.Messages);
Assert.NotEqual(String.Empty, connectionResult.Messages); Assert.NotEqual(String.Empty, connectionResult.Messages);
@@ -595,7 +595,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
[Fact] [Fact]
public async Task ConnectToDatabaseTest() public async Task ConnectToDatabaseTest()
{ {
// connect to a database instance // connect to a database instance
string ownerUri = "file://my/sample/file.sql"; string ownerUri = "file://my/sample/file.sql";
var connectionResult = await var connectionResult = await
TestObjects.GetTestConnectionService() TestObjects.GetTestConnectionService()
@@ -663,7 +663,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
// register disconnect callback // register disconnect callback
connectionService.RegisterOnDisconnectTask( connectionService.RegisterOnDisconnectTask(
(result, uri) => { (result, uri) => {
callbackInvoked = true; callbackInvoked = true;
Assert.True(uri.Equals(ownerUri)); Assert.True(uri.Equals(ownerUri));
return Task.FromResult(true); return Task.FromResult(true);
@@ -779,7 +779,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
.Returns(CreateMockDbConnection(new[] {data})); .Returns(CreateMockDbConnection(new[] {data}));
var connectionService = new ConnectionService(mockFactory.Object); var connectionService = new ConnectionService(mockFactory.Object);
// connect to a database instance // connect to a database instance
string ownerUri = "file://my/sample/file.sql"; string ownerUri = "file://my/sample/file.sql";
var connectionResult = await var connectionResult = await
connectionService connectionService
@@ -816,13 +816,13 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
// setup connection service with callback // setup connection service with callback
var connectionService = TestObjects.GetTestConnectionService(); var connectionService = TestObjects.GetTestConnectionService();
connectionService.RegisterOnConnectionTask( connectionService.RegisterOnConnectionTask(
(sqlConnection) => { (sqlConnection) => {
callbackInvoked = true; callbackInvoked = true;
return Task.FromResult(true); return Task.FromResult(true);
} }
); );
// connect to a database instance // connect to a database instance
await connectionService.Connect(TestObjects.GetTestConnectionParams()); await connectionService.Connect(TestObjects.GetTestConnectionParams());
// verify that a valid connection id was returned // verify that a valid connection id was returned
@@ -830,7 +830,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
} }
/// <summary> /// <summary>
/// Test ConnectionSummaryComparer /// Test ConnectionSummaryComparer
/// </summary> /// </summary>
[Fact] [Fact]
public void TestConnectionSummaryComparer() public void TestConnectionSummaryComparer()
@@ -869,14 +869,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
var service = TestObjects.GetTestConnectionService(); var service = TestObjects.GetTestConnectionService();
var connectParams = TestObjects.GetTestConnectionParams(); var connectParams = TestObjects.GetTestConnectionParams();
// connect to a database instance // connect to a database instance
var connectionResult = await service.Connect(connectParams); var connectionResult = await service.Connect(connectParams);
// verify that a valid connection id was returned // verify that a valid connection id was returned
Assert.NotNull(connectionResult.ConnectionId); Assert.NotNull(connectionResult.ConnectionId);
Assert.NotEqual(string.Empty, connectionResult.ConnectionId); Assert.NotEqual(string.Empty, connectionResult.ConnectionId);
Assert.NotNull(new Guid(connectionResult.ConnectionId)); Assert.NotNull(new Guid(connectionResult.ConnectionId));
// verify that the (URI -> connection) mapping was created // verify that the (URI -> connection) mapping was created
ConnectionInfo info; ConnectionInfo info;
Assert.True(service.TryFindConnection(connectParams.OwnerUri, out info)); Assert.True(service.TryFindConnection(connectParams.OwnerUri, out info));
@@ -892,8 +892,8 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
[Fact] [Fact]
public void TestThatLinuxAndOsxSqlExceptionHasNoErrorCode() public void TestThatLinuxAndOsxSqlExceptionHasNoErrorCode()
{ {
RunIfWrapper.RunIfLinuxOrOSX(() => RunIfWrapper.RunIfLinuxOrOSX(() =>
{ {
try try
{ {
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
@@ -931,7 +931,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
public void TestListDatabasesInvalidParams() public void TestListDatabasesInvalidParams()
{ {
var service = TestObjects.GetTestConnectionService(); var service = TestObjects.GetTestConnectionService();
var listParams = new ListDatabasesParams(); var listParams = new ListDatabasesParams();
Assert.Throws<ArgumentException>(() => service.ListDatabases(listParams)); Assert.Throws<ArgumentException>(() => service.ListDatabases(listParams));
listParams.OwnerUri = "file://notmyfile.sql"; listParams.OwnerUri = "file://notmyfile.sql";
Assert.Throws<Exception>(() => service.ListDatabases(listParams)); Assert.Throws<Exception>(() => service.ListDatabases(listParams));
@@ -973,7 +973,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
}; };
} }
ConnectionSummaryComparer comparer = new ConnectionSummaryComparer(); ConnectionSummaryComparer comparer = new ConnectionSummaryComparer();
// If I compute a hash code // If I compute a hash code
int hashCode = comparer.GetHashCode(summary); int hashCode = comparer.GetHashCode(summary);
if (summary == null || (serverName == null && databaseName == null && userName == null)) if (summary == null || (serverName == null && databaseName == null && userName == null))
@@ -1086,7 +1086,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
await service.Connect(connectParamsDefault); await service.Connect(connectParamsDefault);
await service.Connect(connectParamsQuery); await service.Connect(connectParamsQuery);
// We should have one ConnectionInfo and 2 DbConnections // We should have one ConnectionInfo and 2 DbConnections
ConnectionInfo connectionInfo = service.OwnerToConnectionMap[connectParamsDefault.OwnerUri]; ConnectionInfo connectionInfo = service.OwnerToConnectionMap[connectParamsDefault.OwnerUri];
Assert.Equal(2, connectionInfo.CountConnections); Assert.Equal(2, connectionInfo.CountConnections);
Assert.Equal(1, service.OwnerToConnectionMap.Count); Assert.Equal(1, service.OwnerToConnectionMap.Count);
@@ -1111,7 +1111,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
}); });
connectionInfo.ConnectionTypeToConnectionMap[ConnectionType.Query] = mockQueryConnection.Object; connectionInfo.ConnectionTypeToConnectionMap[ConnectionType.Query] = mockQueryConnection.Object;
// If we disconnect all open connections with the same URI as used above // If we disconnect all open connections with the same URI as used above
service.Disconnect(disconnectParams); service.Disconnect(disconnectParams);
// Close() should have gotten called for both DbConnections // Close() should have gotten called for both DbConnections
@@ -1210,7 +1210,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
await Assert.ThrowsAsync<InvalidOperationException>( await Assert.ThrowsAsync<InvalidOperationException>(
() => service.GetOrOpenConnection(TestObjects.ScriptUri, ConnectionType.Query)); () => service.GetOrOpenConnection(TestObjects.ScriptUri, ConnectionType.Query));
} }
[Fact] [Fact]
public async Task GetOrOpenAdminDefaultConnection() public async Task GetOrOpenAdminDefaultConnection()
{ {
@@ -1238,7 +1238,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
// Connect // Connect
ConnectionService service = TestObjects.GetTestConnectionService(); ConnectionService service = TestObjects.GetTestConnectionService();
var connectionResult = await service.Connect(connectionParameters); var connectionResult = await service.Connect(connectionParameters);
// Verify you can get the connection for default // Verify you can get the connection for default
DbConnection defaultConn = await service.GetOrOpenConnection(connectionParameters.OwnerUri, ConnectionType.Default); DbConnection defaultConn = await service.GetOrOpenConnection(connectionParameters.OwnerUri, ConnectionType.Default);
ConnectionInfo connInfo = service.OwnerToConnectionMap[connectionParameters.OwnerUri]; ConnectionInfo connInfo = service.OwnerToConnectionMap[connectionParameters.OwnerUri];
@@ -1322,10 +1322,10 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
const string otherDbName = "other"; const string otherDbName = "other";
// Given a connection that returns the database name // Given a connection that returns the database name
var connection = new TestSqlConnection(null); var connection = new TestSqlConnection(null);
var mockFactory = new Mock<ISqlConnectionFactory>(); var mockFactory = new Mock<ISqlConnectionFactory>();
mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>(), It.IsAny<string>())) mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>(), It.IsAny<string>()))
.Returns((string connString, string azureAccountToken) => .Returns((string connString, string azureAccountToken) =>
{ {
connection.ConnectionString = connString; connection.ConnectionString = connString;
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(connString); SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(connString);
@@ -1370,12 +1370,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
mockConnection.SetupGet(conn => conn.State).Returns(ConnectionState.Open); mockConnection.SetupGet(conn => conn.State).Returns(ConnectionState.Open);
mockConnection.Setup(conn => conn.Close()); mockConnection.Setup(conn => conn.Close());
mockConnection.Setup(conn => conn.Open()); mockConnection.Setup(conn => conn.Open());
var connection = mockConnection.Object; var connection = mockConnection.Object;
var mockFactory = new Mock<ISqlConnectionFactory>(); var mockFactory = new Mock<ISqlConnectionFactory>();
mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>(), It.IsAny<string>())) mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>(), It.IsAny<string>()))
.Returns((string connString, string azureAccountToken) => .Returns((string connString, string azureAccountToken) =>
{ {
connection.ConnectionString = connString; connection.ConnectionString = connString;
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(connString); SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(connString);
@@ -1395,7 +1395,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
OwnerUri = ownerUri, OwnerUri = ownerUri,
Connection = TestObjects.GetTestConnectionDetails() Connection = TestObjects.GetTestConnectionDetails()
}); });
ConnectionInfo testInfo; ConnectionInfo testInfo;
connectionService.TryFindConnection(ownerUri, out testInfo); connectionService.TryFindConnection(ownerUri, out testInfo);
@@ -1423,12 +1423,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
mockConnection.SetupGet(conn => conn.State).Returns(ConnectionState.Open); mockConnection.SetupGet(conn => conn.State).Returns(ConnectionState.Open);
mockConnection.Setup(conn => conn.Close()); mockConnection.Setup(conn => conn.Close());
mockConnection.Setup(conn => conn.Open()); mockConnection.Setup(conn => conn.Open());
var connection = mockConnection.Object; var connection = mockConnection.Object;
var mockFactory = new Mock<ISqlConnectionFactory>(); var mockFactory = new Mock<ISqlConnectionFactory>();
mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>(), It.IsAny<string>())) mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny<string>(), It.IsAny<string>()))
.Returns((string connString, string azureAccountToken) => .Returns((string connString, string azureAccountToken) =>
{ {
connection.ConnectionString = connString; connection.ConnectionString = connString;
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(connString); SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(connString);
@@ -1448,7 +1448,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
OwnerUri = ownerUri, OwnerUri = ownerUri,
Connection = TestObjects.GetTestConnectionDetails() Connection = TestObjects.GetTestConnectionDetails()
}); });
ConnectionInfo testInfo; ConnectionInfo testInfo;
connectionService.TryFindConnection(ownerUri, out testInfo); connectionService.TryFindConnection(ownerUri, out testInfo);
@@ -1467,9 +1467,9 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Connection
[Fact] [Fact]
public void ParseConnectionStringTest() public void ParseConnectionStringTest()
{ {
// If we make a connection to a live database // If we make a connection to a live database
ConnectionService service = ConnectionService.Instance; ConnectionService service = ConnectionService.Instance;
var connectionString = "Server=tcp:{servername},1433;Initial Catalog={databasename};Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"; var connectionString = "Server=tcp:{servername},1433;Initial Catalog={databasename};Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
var details = service.ParseConnectionString(connectionString); var details = service.ParseConnectionString(connectionString);

View File

@@ -25,19 +25,19 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
{ {
private static readonly StoreConfig Config = new StoreConfig private static readonly StoreConfig Config = new StoreConfig
{ {
CredentialFolder = ".testsecrets", CredentialFolder = ".testsecrets",
CredentialFile = "sqltestsecrets.json", CredentialFile = "sqltestsecrets.json",
IsRelativeToUserHomeDir = true IsRelativeToUserHomeDir = true
}; };
private const string CredentialId = "Microsoft_SqlToolsTest_TestId"; private const string CredentialId = "Microsoft_SqlToolsTest_TestId";
private const string Password1 = "P@ssw0rd1"; private readonly string Password1 = Guid.NewGuid().ToString();
private const string Password2 = "2Pass2Furious"; private readonly string Password2 = Guid.NewGuid().ToString();
private const string OtherCredId = CredentialId + "2345"; private const string OtherCredId = CredentialId + "2345";
private const string OtherPassword = CredentialId + "2345"; private const string OtherPassword = CredentialId + "2345";
// Test-owned credential store used to clean up before/after tests to ensure code works as expected // Test-owned credential store used to clean up before/after tests to ensure code works as expected
// even if previous runs stopped midway through // even if previous runs stopped midway through
private readonly ICredentialStore credStore; private readonly ICredentialStore credStore;
private readonly CredentialService service; private readonly CredentialService service;
@@ -50,7 +50,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
service = new CredentialService(credStore, Config); service = new CredentialService(credStore, Config);
DeleteDefaultCreds(); DeleteDefaultCreds();
} }
public void Dispose() public void Dispose()
{ {
DeleteDefaultCreds(); DeleteDefaultCreds();
@@ -89,7 +89,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
{ {
string errorResponse = null; string errorResponse = null;
var contextMock = RequestContextMocks.Create<bool>(null).AddErrorHandling((msg, code) => errorResponse = msg); var contextMock = RequestContextMocks.Create<bool>(null).AddErrorHandling((msg, code) => errorResponse = msg);
await service.HandleSaveCredentialRequest(new Credential(CredentialId), contextMock.Object); await service.HandleSaveCredentialRequest(new Credential(CredentialId), contextMock.Object);
TestUtils.VerifyErrorSent(contextMock); TestUtils.VerifyErrorSent(contextMock);
Assert.True(errorResponse.Contains("ArgumentException") || errorResponse.Contains("ArgumentNullException")); Assert.True(errorResponse.Contains("ArgumentException") || errorResponse.Contains("ArgumentNullException"));
@@ -202,7 +202,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
TestUtils.VerifyErrorSent(contextMock); TestUtils.VerifyErrorSent(contextMock);
Assert.Contains("ArgumentNullException", errorResponse); Assert.Contains("ArgumentNullException", errorResponse);
} }
[Fact] [Fact]
public async Task ReadCredentialThrowsIfIdMissing() public async Task ReadCredentialThrowsIfIdMissing()
{ {
@@ -232,7 +232,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials
Assert.Null(actual.Password); Assert.Null(actual.Password);
})); }));
} }
[Fact] [Fact]
public async Task DeleteCredentialThrowsIfIdMissing() public async Task DeleteCredentialThrowsIfIdMissing()
{ {

View File

@@ -1,6 +1,6 @@
// //
// Code originally from http://credentialmanagement.codeplex.com/, // Code originally from http://credentialmanagement.codeplex.com/,
// Licensed under the Apache License 2.0 // Licensed under the Apache License 2.0
// //
using System; using System;
@@ -15,7 +15,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
[Fact] [Fact]
public void CredentialSetCreate() public void CredentialSetCreate()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
{ {
Assert.NotNull(new CredentialSet()); Assert.NotNull(new CredentialSet());
}); });
@@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
[Fact] [Fact]
public void CredentialSetCreateWithTarget() public void CredentialSetCreateWithTarget()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
{ {
Assert.NotNull(new CredentialSet("target")); Assert.NotNull(new CredentialSet("target"));
}); });
@@ -33,7 +33,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
[Fact] [Fact]
public void CredentialSetShouldBeIDisposable() public void CredentialSetShouldBeIDisposable()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
{ {
Assert.True(new CredentialSet() is IDisposable, "CredentialSet needs to implement IDisposable Interface."); Assert.True(new CredentialSet() is IDisposable, "CredentialSet needs to implement IDisposable Interface.");
}); });
@@ -42,7 +42,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
[Fact] [Fact]
public void CredentialSetLoad() public void CredentialSetLoad()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
{ {
Win32Credential credential = new Win32Credential Win32Credential credential = new Win32Credential
{ {
@@ -67,7 +67,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
[Fact] [Fact]
public void CredentialSetLoadShouldReturnSelf() public void CredentialSetLoadShouldReturnSelf()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
{ {
CredentialSet set = new CredentialSet(); CredentialSet set = new CredentialSet();
Assert.IsType<CredentialSet>(set.Load()); Assert.IsType<CredentialSet>(set.Load());
@@ -79,12 +79,12 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Credentials.Win32
[Fact] [Fact]
public void CredentialSetLoadWithTargetFilter() public void CredentialSetLoadWithTargetFilter()
{ {
RunIfWrapper.RunIfWindows(() => RunIfWrapper.RunIfWindows(() =>
{ {
Win32Credential credential = new Win32Credential Win32Credential credential = new Win32Credential
{ {
Username = "filteruser", Username = "filteruser",
Password = "filterpassword", Password = Guid.NewGuid().ToString(),
Target = "filtertarget" Target = "filtertarget"
}; };
credential.Save(); credential.Save();

View File

@@ -23,7 +23,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
/// </summary> /// </summary>
public class TestObjects public class TestObjects
{ {
public const string ScriptUri = "file://some/file.sql"; public const string ScriptUri = "file://some/file.sql";
/// <summary> /// <summary>
@@ -48,7 +48,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
public static ConnectParams GetTestConnectionParams(bool useConnectionString = false) public static ConnectParams GetTestConnectionParams(bool useConnectionString = false)
{ {
return new ConnectParams() return new ConnectParams()
{ {
OwnerUri = ScriptUri, OwnerUri = ScriptUri,
Connection = GetTestConnectionDetails(useConnectionString) Connection = GetTestConnectionDetails(useConnectionString)
@@ -88,14 +88,14 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{ {
return new ConnectionDetails() return new ConnectionDetails()
{ {
ConnectionString = "User ID=user;PWD=password;Database=databaseName;Server=serverName" ConnectionString = $"User ID=user;PWD={Guid.NewGuid().ToString()};Database=databaseName;Server=serverName"
}; };
} }
return new ConnectionDetails() return new ConnectionDetails()
{ {
UserName = "user", UserName = "user",
Password = "password", Password = Guid.NewGuid().ToString(),
DatabaseName = "databaseName", DatabaseName = "databaseName",
ServerName = "serverName" ServerName = "serverName"
}; };
@@ -198,7 +198,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
private string _database; private string _database;
private ConnectionState _state; private ConnectionState _state;
public TestSqlConnection() public TestSqlConnection()
{ {
} }
@@ -207,7 +207,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
{ {
Data = data; Data = data;
} }
internal TestResultSet[] Data { get; set; } internal TestResultSet[] Data { get; set; }
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
@@ -233,7 +233,7 @@ namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Utility
public override string ConnectionString { get; set; } public override string ConnectionString { get; set; }
public override string Database public override string Database
{ {
get { return _database; } get { return _database; }
} }