public void EncryptDecryptFailsIfAlreadyPerformedTest() { //------------Setup for test-------------------------- //------------Execute Test--------------------------- string encrypted = DpapiWrapper.Encrypt(message); char x = encrypted.Where(o => encrypted.Where(u => u == o).Count() > 1).First(); // find first char that appears more than once char y = encrypted.Where(o => o != x).First(); // find the first char not equal to x string tamperedEncrypted = encrypted.Replace(x, y); try { string decrypted = DpapiWrapper.Decrypt(tamperedEncrypted); } catch (Exception e) { e.GetType().Should().Be(typeof(System.Security.Cryptography.CryptographicException)); } try { DpapiWrapper.Decrypt(message); } catch (Exception e) { e.GetType().Should().Be(typeof(ArgumentException)); } }
public override XElement ToXml() { var result = base.ToXml(); var connectionString = string.Join(";", $"AppServerUri={Address}", $"WebServerPort={WebServerPort}", $"AuthenticationType={AuthenticationType}" ); if (AuthenticationType == AuthenticationType.User) { connectionString = string.Join(";", connectionString, $"UserName={UserName}", $"Password={Password}" ); } result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString)), new XAttribute("Type", GetType().Name), new XElement("TypeOf", enSourceType.Dev2Server) ); return(result); }
/// <summary> /// Gets the XML representation of this resource. /// </summary> /// <returns> /// The XML representation of this resource. /// </returns> public override XElement ToXml() { var result = base.ToXml(); var connectionString = string.Join(";", string.Format("Server={0}", Server), string.Format("AuthenticationType={0}", AuthenticationType) ); if (AuthenticationType == AuthenticationType.User) { connectionString = string.Join(";", connectionString, string.Format("UserName={0}", UserName), string.Format("Password={0}", Password) ); } result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString)), new XAttribute("Type", ResourceType), new XElement("TypeOf", ResourceType) ); return(result); }
public override XElement ToXml() { var result = base.ToXml(); var connectionString = string.Join(";", $"Address={Address}", $"DefaultQuery={DefaultQuery}", $"AuthenticationType={AuthenticationType}" ); if (AuthenticationType == AuthenticationType.User) { connectionString = string.Join(";", connectionString, $"UserName={UserName}", $"Password={Password}" ); } result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString.EscapeString())), new XAttribute("Type", GetType().Name), new XElement("TypeOf", ResourceType) ); return(result); }
public void TriggersCatalog_FileSystemWatcher_Error() { var directory = "some path"; var fileName = Guid.NewGuid().ToString() + ".bite"; var oldName = Guid.NewGuid().ToString() + ".bite"; var files = new string[] { fileName }; var mockDirectoryWrapper = new Mock <IDirectory>(); mockDirectoryWrapper.Setup(directoryWrapper => directoryWrapper.GetFiles("some path")).Returns(files); var mockFileWrapper = new Mock <IFile>(); var mockSerializer = new Mock <ISerializer>(); var mockFileSystemWatcher = new Mock <IFileSystemWatcher>(); var triggerId = Guid.NewGuid(); var decryptedTrigger = "serialized queue data"; var expected = DpapiWrapper.Encrypt(decryptedTrigger); mockFileWrapper.Setup(o => o.ReadAllText(fileName)).Returns(expected); var expectedTrigger = new TriggerQueue { TriggerId = triggerId }; mockSerializer.Setup(o => o.Deserialize <ITriggerQueue>(decryptedTrigger)).Returns(expectedTrigger); var catalog = GetTriggersCatalog(mockDirectoryWrapper.Object, mockFileWrapper.Object, directory, mockSerializer.Object, mockFileSystemWatcher.Object); mockFileSystemWatcher.Raise(fileWatcher => fileWatcher.Error += null, null, new ErrorEventArgs(new Exception())); mockDirectoryWrapper.Verify(directoryWrapper => directoryWrapper.GetFiles(directory), Times.Exactly(1)); Assert.AreEqual(1, catalog.Queues.Count); Assert.AreEqual(triggerId, catalog.Queues[0].TriggerId); }
public void DsfPathCreate_TryExecuteConcreteAction_Credential_Variable() { //------------Setup for test-------------------------- var env = new ExecutionEnvironment(); env.Assign("[[val1]]", "demo", false, 0); env.Assign("[[val2]]", "password", false, 0); var newGuid = Guid.NewGuid(); var outputPath = string.Concat(TestContext.TestRunDirectory, "\\", newGuid + "test.txt"); var act = new TestDsfPathCreate { OutputPath = outputPath, Result = "CompanyName" }; act.Username = "******"; act.Password = DpapiWrapper.Encrypt("[[val2]]"); var mockDataObject = new Mock <IDSFDataObject>(); mockDataObject.Setup(o => o.Environment).Returns(env); mockDataObject.Setup(o => o.IsDebugMode()).Returns(true); //------------Execute Test--------------------------- ErrorResultTO to; act.TestTryExecuteConcreteAction(mockDataObject.Object, out to, 0); var errors = to.FetchErrors(); Assert.IsTrue(errors.FirstOrDefault()?.Contains("Failed to authenticate with user [ demo ]") ?? false); }
public override XElement ToXml() { var result = base.ToXml(); var connectionString = string.Join(";", $"HostName={HostName}", $"Port={Port}", $"SearchIndex={SearchIndex}", $"AuthenticationType={AuthenticationType}" ); if (AuthenticationType == AuthenticationType.Password) { connectionString = string.Join(";", connectionString, $"Username={Username}", $"Password={Password}" ); } result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString.EscapeString())), new XAttribute("Type", ResourceType), new XElement("TypeOf", ResourceType) ); return(result); }
public void TriggersCatalog_LoadQueuesByResourceId_ExpectQueue() { var mockDirectoryWrapper = new Mock <IDirectory>(); const string fileName = "somefile.bite"; mockDirectoryWrapper.Setup(o => o.GetFiles(It.IsAny <string>())).Returns(new[] { fileName }); var mockFileWrapper = new Mock <IFile>(); var mockSerializer = new Mock <ISerializer>(); var mockFileSystemWatcher = new Mock <IFileSystemWatcher>(); var expectedResourceId = Guid.NewGuid(); var decryptedTrigger = "serialized queue data"; var expected = DpapiWrapper.Encrypt(decryptedTrigger); mockFileWrapper.Setup(o => o.ReadAllText("somefile.bite")).Returns(expected); var expectedTrigger = new TriggerQueue { ResourceId = expectedResourceId }; mockSerializer.Setup(o => o.Deserialize <ITriggerQueue>(decryptedTrigger)).Returns(expectedTrigger); var catalog = GetTriggersCatalog(mockDirectoryWrapper.Object, mockFileWrapper.Object, "some path", mockSerializer.Object, mockFileSystemWatcher.Object); var triggerQueue = catalog.LoadQueueTriggerFromFile("somefile.bite"); mockSerializer.Verify(o => o.Deserialize <ITriggerQueue>(decryptedTrigger), Times.Exactly(2)); Assert.AreEqual(expectedTrigger, triggerQueue); var triggerQueues = catalog.LoadQueuesByResourceId(expectedResourceId); Assert.AreEqual(1, triggerQueues.Count); }
/// <summary> /// Gets the XML representation of this resource. /// </summary> /// <returns> /// The XML representation of this resource. /// </returns> public override XElement ToXml() { var result = base.ToXml(); var connectionString = string.Join(";", $"Server={Server}", $"AuthenticationType={AuthenticationType}" ); if (AuthenticationType == AuthenticationType.User) { connectionString = string.Join(";", connectionString, $"UserName={UserName}", $"Password={Password}" ); } result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString)), new XAttribute("IsSharepointOnline", IsSharepointOnline), new XAttribute("Type", GetType().Name), new XElement("TypeOf", ResourceType) ); return(result); }
public void WorkflowResume_Execute_WithEncryptedValues_Returns_Execution_Completed() { //------------Setup for test-------------------------- var newexecutionEnvironment = CreateExecutionEnvironment(); newexecutionEnvironment.Assign("[[UUID]]", "public", 0); newexecutionEnvironment.Assign("[[JourneyName]]", "whatever", 0); var resourceId = Guid.NewGuid(); var serializer = new Dev2JsonSerializer(); var identity = new MockPrincipal(WindowsIdentity.GetCurrent().Name); var currentPrincipal = new GenericPrincipal(identity, new[] { "Role1", "Roll2" }); Thread.CurrentPrincipal = currentPrincipal; var user = DpapiWrapper.Encrypt(currentPrincipal.Identity.Name); var env = DpapiWrapper.Encrypt(newexecutionEnvironment.ToJson()); var values = new Dictionary <string, StringBuilder> { { "resourceID", new StringBuilder(resourceId.ToString()) }, { "environment", new StringBuilder(env) }, { "startActivityId", new StringBuilder("4032a11e-4fb3-4208-af48-b92a0602ab4b") }, { "versionNumber", new StringBuilder("1") }, { "currentuserprincipal", new StringBuilder(user) } }; var resourceCatalog = new Mock <IResourceCatalog>(); var newDs = new DynamicService { Name = HandlesType(), ID = resourceId }; var sa = new ServiceAction { Name = HandlesType(), ActionType = enActionType.InvokeManagementDynamicService, SourceMethod = HandlesType() }; newDs.Actions.Add(sa); resourceCatalog.Setup(catalog => catalog.GetService(GlobalConstants.ServerWorkspaceID, It.IsAny <Guid>(), "")).Returns(newDs); var errors = new ErrorResultTO(); var mockResumableExecutionContainer = new Mock <IResumableExecutionContainer>(); mockResumableExecutionContainer.Setup(o => o.Execute(out errors, 0)).Verifiable(); var mockResumableExecutionContainerFactory = new Mock <IResumableExecutionContainerFactory>(); mockResumableExecutionContainerFactory.Setup(o => o.New(It.IsAny <Guid>(), It.IsAny <ServiceAction>(), It.IsAny <DsfDataObject>())) .Returns(mockResumableExecutionContainer.Object); CustomContainer.Register(mockResumableExecutionContainerFactory.Object); //------------Execute Test--------------------------- var workflowResume = new WorkflowResume(); workflowResume.ResourceCatalogInstance = resourceCatalog.Object; var jsonResult = workflowResume.Execute(values, null); //------------Assert Results------------------------- var result = serializer.Deserialize <ExecuteMessage>(jsonResult); Assert.IsFalse(result.HasError); Assert.AreEqual("Execution Completed.", result.Message.ToString()); }
public override XElement ToXml() { var result = base.ToXml(); var connectionString = GetConnectionString(); result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString)), new XAttribute("Type", GetType().Name), new XElement("TypeOf", ResourceType) ); return(result); }
public void EncryptDecryptTest() { //------------Setup for test-------------------------- //------------Execute Test--------------------------- string encrypted = DpapiWrapper.Encrypt(message); encrypted.Should().NotBeNullOrEmpty(); encrypted.Should().NotBeNullOrWhiteSpace(); encrypted.Should().NotBeSameAs(message); encrypted.Should().NotContain(message); DpapiWrapper.Decrypt(encrypted).Should().Be(message); }
public void SaveTriggerQueue(ITriggerQueue triggerQueue) { if (triggerQueue.TriggerId == Guid.Empty) { triggerQueue.TriggerId = Guid.NewGuid(); } var serializedData = _serializer.Serialize(triggerQueue); var saveData = DpapiWrapper.Encrypt(serializedData); var queueFilePath = GetQueueFilePath(triggerQueue); _fileWrapper.WriteAllText(queueFilePath, saveData); }
public override XElement ToXml() { var result = base.ToXml(); var connectionString = string.Join(";", string.Format("EndpointUrl={0}", EndpointUrl) ); result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString)), new XAttribute("Type", ResourceType), new XElement("TypeOf", ResourceType) ); return(result); }
public void DsfAbstractFileActivity_DecryptForShowPassword_ShouldShowDecryptedType() { //------------Setup for test-------------------------- const string password = "******"; var encrypt = DpapiWrapper.Encrypt(password); var act = new TestActivity("TestActivity") { Password = encrypt }; var privateObject = new Warewolf.Testing.PrivateObject(act); var decryptedPassword = privateObject.GetProperty("DecryptedPassword"); //------------Execute Test--------------------------- //------------Assert Results------------------------- Assert.AreEqual(password, decryptedPassword); }
public override XElement ToXml() { var result = base.ToXml(); result.Add(new XAttribute("ServerType", ServerType)); result.Add(new XAttribute("Type", GetType().Name)); result.Add(new XAttribute("ConnectionString", DpapiWrapper.Encrypt(ConnectionString) ?? string.Empty)); result.Add(new XElement("AuthorRoles", string.Empty)); result.Add(new XElement("Comment", string.Empty)); result.Add(new XElement("HelpLink", string.Empty)); result.Add(new XElement("Tags", string.Empty)); result.Add(new XElement("UnitTestTargetWorkflowService", string.Empty)); result.Add(new XElement("BizRule", string.Empty)); result.Add(new XElement("WorkflowActivityDef", string.Empty)); return(result); }
public override XElement ToXml() { var result = base.ToXml(); var connectionString = string.Join(";", string.Format("AutoDiscoverUrl={0}", AutoDiscoverUrl), string.Format("UserName={0}", UserName), string.Format("Password={0}", Password), string.Format("Timeout={0}", Timeout) ); result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString)), new XAttribute("Type", GetType().Name), new XElement("TypeOf", ResourceType) ); return(result); }
public int Run() { var sourceFileName = _options.FileName; var sourceData = File.ReadAllText(sourceFileName); var destinationFileName = _options.OutputFileName; if (_options.ShouldEncrypt) { var data = DpapiWrapper.Encrypt(sourceData); File.WriteAllText(destinationFileName, data); } else { var data = DpapiWrapper.Decrypt(sourceData); File.WriteAllText(destinationFileName, data); } return(0); }
public override XElement ToXml() { var result = base.ToXml(); var connectionString = string.Join(";", $"HostName={HostName}", $"Port={Port}", $"UserName={UserName}", $"Password={Password}", $"VirtualHost={VirtualHost}" ); result.Add( new XAttribute("ConnectionString", DpapiWrapper.Encrypt(connectionString)), new XAttribute("Type", ResourceType), new XElement("TypeOf", ResourceType) ); return(result); }
public void TriggersCatalog_LoadQueueTriggerFromFile() { var directoryWrapper = new Mock <IDirectory>().Object; var mockFileWrapper = new Mock <IFile>(); var mockSerializer = new Mock <ISerializer>(); var mockFileSystemWatcher = new Mock <IFileSystemWatcher>(); var decryptedTrigger = "serialized queue data"; var expected = DpapiWrapper.Encrypt(decryptedTrigger); mockFileWrapper.Setup(o => o.ReadAllText("somefile.bite")).Returns(expected); var expectedTrigger = new TriggerQueue(); mockSerializer.Setup(o => o.Deserialize <ITriggerQueue>(decryptedTrigger)).Returns(expectedTrigger); var catalog = GetTriggersCatalog(directoryWrapper, mockFileWrapper.Object, "some path", mockSerializer.Object, mockFileSystemWatcher.Object); var actual = catalog.LoadQueueTriggerFromFile("somefile.bite"); mockSerializer.Verify(o => o.Deserialize <ITriggerQueue>(decryptedTrigger), Times.Once); Assert.AreEqual(expectedTrigger, actual); }
public void AbstractMultipleFiles_DecryptForShowPassword_ShouldShowDecryptedType() { //------------Setup for test-------------------------- const string password = "******"; const string destPassword = "******"; var encrypt = DpapiWrapper.Encrypt(password); var destEncrypt = DpapiWrapper.Encrypt(destPassword); var act = new MockAbstractMultipleFilesActivity("MockActivity") { Password = encrypt, DestinationPassword = destEncrypt }; var privateObject = new Warewolf.Testing.PrivateObject(act); var decryptedPassword = privateObject.GetProperty("DecryptedPassword"); var decryptedDestinationPassword = privateObject.GetProperty("DecryptedDestinationPassword"); //------------Execute Test--------------------------- //------------Assert Results------------------------- Assert.AreEqual(password, decryptedPassword); Assert.AreEqual(destPassword, decryptedDestinationPassword); }
private static ILoggerContext ConstructLoggerContext(IArgs args, out ElasticsearchSource elasticsearchSource) { var mockArgs = new Mock <IArgs>(); mockArgs.Setup(o => o.ServerEndpoint).Returns(args.ServerEndpoint); mockArgs.Setup(o => o.Verbose).Returns(args.Verbose); var dependency = new Depends(Depends.ContainerType.AnonymousElasticsearch); var hostName = "http://" + dependency.Container.IP; elasticsearchSource = new ElasticsearchSource { ResourceID = Guid.Empty, ResourceType = "ElasticsearchSource", AuthenticationType = AuthenticationType.Anonymous, Port = dependency.Container.Port, HostName = hostName, SearchIndex = "warewolflogstests" }; var serializer = new Dev2JsonSerializer(); var payload = serializer.Serialize(elasticsearchSource); var encryptedPayload = DpapiWrapper.Encrypt(payload); var data = new AuditingSettingsData { EncryptDataSource = true, LoggingDataSource = new NamedGuidWithEncryptedPayload { Name = "Testing Elastic Data Source", Value = Guid.Empty, Payload = encryptedPayload } }; Config.Auditing.LoggingDataSource = data.LoggingDataSource; Config.Auditing.EncryptDataSource = data.EncryptDataSource; Config.Server.Sink = nameof(AuditingSettingsData); return(new LoggerContext(mockArgs.Object)); }
static LogSettingsViewModel CreateLogSettingViewModel(string sink, Mock <IResourceRepository> _resourceRepo = null) { XmlConfigurator.ConfigureAndWatch(new FileInfo("Settings.config")); var loggingSettingsTo = new LoggingSettingsTo { FileLoggerLogSize = 50, FileLoggerLogLevel = "TRACE", EventLogLoggerLogLevel = "DEBUG" }; var env = new Mock <IServer>(); if (_resourceRepo is null) { _resourceRepo = new Mock <IResourceRepository>(); } var expectedServerSettingsData = new ServerSettingsData { Sink = sink, ExecutionLogLevel = LogLevel.DEBUG.ToString() }; _resourceRepo.Setup(res => res.GetServerSettings(env.Object)).Returns(expectedServerSettingsData); var selectedAuditingSourceId = Guid.NewGuid(); if (sink == "LegacySettingsData") { var legacySettingsData = new LegacySettingsData() { AuditFilePath = "somePath" }; _resourceRepo.Setup(res => res.GetAuditingSettings <LegacySettingsData>(env.Object)).Returns(legacySettingsData); _resourceRepo.Setup(res => res.SaveAuditingSettings(env.Object, legacySettingsData)).Verifiable(); } else { var dependency = new Depends(Depends.ContainerType.AnonymousElasticsearch); var hostName = "http://" + dependency.Container.IP; var elasticsearchSource = new ElasticsearchSource { AuthenticationType = AuthenticationType.Anonymous, Port = dependency.Container.Port, HostName = hostName, SearchIndex = "warewolflogstests" }; var serializer = new Dev2JsonSerializer(); var payload = serializer.Serialize(elasticsearchSource); var encryptedPayload = DpapiWrapper.Encrypt(payload); var auditingSettingsData = new AuditingSettingsData { Endpoint = "ws://127.0.0.1:5000/ws", EncryptDataSource = true, LoggingDataSource = new NamedGuidWithEncryptedPayload { Name = "Auditing Data Source", Value = selectedAuditingSourceId, Payload = encryptedPayload }, }; _resourceRepo.Setup(res => res.GetAuditingSettings <AuditingSettingsData>(env.Object)).Returns(auditingSettingsData); _resourceRepo.Setup(res => res.SaveAuditingSettings(env.Object, auditingSettingsData)).Verifiable(); } IResource mockAuditingSource = new ElasticsearchSource { ResourceID = selectedAuditingSourceId, ResourceName = "Auditing Data Source" }; var expectedList = new List <IResource>(); expectedList.Add(mockAuditingSource); _resourceRepo.Setup(resourceRepository => resourceRepository.FindResourcesByType <IAuditingSource>(env.Object)).Returns(expectedList); env.Setup(a => a.ResourceRepository).Returns(_resourceRepo.Object); var logSettingsViewModel = new LogSettingsViewModel(loggingSettingsTo, env.Object); return(logSettingsViewModel); }
public override IDev2Activity Execute(IDSFDataObject data, int update) { _previousParentId = data.ParentInstanceID; _debugInputs?.Clear(); _debugOutputs?.Clear(); _dataObject = data; _update = update; _originalExecutionEnvironment = data.Environment.Snapshot(); _suspensionId = ""; var allErrors = new ErrorResultTO(); try { _dataObject.ForEachNestingLevel++; if (!_persistenceEnabled) { throw new Exception(ErrorResource.PersistenceSettingsNoConfigured); } if (NextNodes is null) { throw new Exception(ErrorResource.NextNodeRequiredForSuspendExecution); } var persistScheduleValue = PersistSchedulePersistValue(); if (string.IsNullOrEmpty(persistScheduleValue)) { throw new Exception(string.Format(ErrorResource.SuspendOptionValueNotSet, GetSuspendValidationMessageType(SuspendOption))); } var currentEnvironment = _originalExecutionEnvironment.ToJson(); var currentuserprincipal = _dataObject.ExecutingUser.Identity.Name; var versionNumber = _dataObject.VersionNumber.ToString(); var resourceId = _dataObject.ResourceID; if (EncryptData) { currentEnvironment = DpapiWrapper.Encrypt(currentEnvironment); currentuserprincipal = DpapiWrapper.Encrypt(currentuserprincipal); } var firstActivity = NextNodes.First(); var activityId = Guid.Parse(firstActivity?.UniqueID ?? throw new Exception(GlobalConstants.NextNodeIDNotFound)); var values = new Dictionary <string, StringBuilder> { { "resourceID", new StringBuilder(resourceId.ToString()) }, { "environment", new StringBuilder(currentEnvironment) }, { "startActivityId", new StringBuilder(activityId.ToString()) }, { nameof(versionNumber), new StringBuilder(versionNumber) }, { nameof(currentuserprincipal), new StringBuilder(currentuserprincipal) } }; if (_dataObject.IsDebugMode()) { var debugItemStaticDataParams = new DebugItemStaticDataParams("Allow Manual Resumption: " + AllowManualResumption, "", true); AddDebugInputItem(debugItemStaticDataParams); } DispatchDebug(_dataObject, StateType.Before, _update); _suspensionId = _scheduler.CreateAndScheduleJob(SuspendOption, persistScheduleValue, values); _dataObject.ParentInstanceID = UniqueID; _dataObject.IsDebugNested = true; DispatchDebug(_dataObject, StateType.After, _update); Response = _suspensionId; _dataObject.Environment.Assign(Result, Response, 0); _dataObject.Environment.CommitAssign(); _stateNotifier?.LogActivityExecuteState(this); Dev2Logger.Debug($"{_dataObject.ServiceName} execution suspended: SuspensionId {_suspensionId} scheduled", GlobalConstants.WarewolfDebug); if (AllowManualResumption) { ExecuteSaveDataFunc(); } if (_dataObject.IsServiceTestExecution && _originalUniqueID == Guid.Empty) { _originalUniqueID = Guid.Parse(UniqueID); } } catch (Hangfire.BackgroundJobClientException) { LogException(new Exception(ErrorResource.BackgroundJobClientCreateFailed), allErrors); } catch (Exception ex) { _stateNotifier?.LogExecuteException(ex, this); LogException(ex, allErrors); } finally { var serviceTestStep = HandleServiceTestExecution(_dataObject); _dataObject.ParentInstanceID = _previousParentId; _dataObject.ForEachNestingLevel--; _dataObject.IsDebugNested = false; HandleDebug(_dataObject, serviceTestStep); HandleErrors(_dataObject, allErrors); } return(null); //fire once the rest should be done on resumption service }
public void CommonEqualityOps_PassWordsCompare_ReturnTrue() { var areConditionsEqual = CommonEqualityOps.PassWordsCompare(DpapiWrapper.Encrypt("123"), DpapiWrapper.Encrypt("123")); Assert.IsTrue(areConditionsEqual); }
protected override List <string> PerformExecution(Dictionary <string, string> evaluatedValues) { _errorsTo = new ErrorResultTO(); _suspensionId = ""; var allErrors = new ErrorResultTO(); var dataObject = _dataObject; try { dataObject.ForEachNestingLevel++; if (!_persistenceEnabled) { throw new Exception(ErrorResource.PersistenceSettingsNoConfigured); } if (NextNodes is null) { throw new Exception(ErrorResource.NextNodeRequiredForSuspendExecution); } var activityId = Guid.Parse(NextNodes.First()?.UniqueID ?? throw new Exception(GlobalConstants.NextNodeIDNotFound)); var currentEnvironment = _dataObject.Environment.ToJson(); var currentuserprincipal = _dataObject.ExecutingUser.Identity.Name; var versionNumber = _dataObject.VersionNumber.ToString(); if (EncryptData) { currentEnvironment = DpapiWrapper.Encrypt(currentEnvironment); currentuserprincipal = DpapiWrapper.Encrypt(currentuserprincipal); } var values = new Dictionary <string, StringBuilder> { { "resourceID", new StringBuilder(_dataObject.ResourceID.ToString()) }, { "environment", new StringBuilder(currentEnvironment) }, { "startActivityId", new StringBuilder(activityId.ToString()) }, { nameof(versionNumber), new StringBuilder(_dataObject.VersionNumber.ToString()) }, { nameof(currentuserprincipal), new StringBuilder(currentuserprincipal) } }; var persistScheduleValue = PersistSchedulePersistValue(); if (_dataObject.IsDebugMode()) { var debugItemStaticDataParams = new DebugItemStaticDataParams("Allow Manual Resumption: " + AllowManualResumption, "", true); AddDebugInputItem(debugItemStaticDataParams); } DispatchDebug(dataObject, StateType.Before, _update); _suspensionId = _scheduler.CreateAndScheduleJob(SuspendOption, persistScheduleValue, values); dataObject.ParentInstanceID = UniqueID; dataObject.IsDebugNested = true; DispatchDebug(dataObject, StateType.After, _update); Response = _suspensionId; _dataObject.Environment.Assign(Result, _suspensionId, 0); _dataObject.Environment.CommitAssign(); _stateNotifier?.LogActivityExecuteState(this); Dev2Logger.Debug($"{_dataObject.ServiceName} execution suspended: SuspensionId {_suspensionId} scheduled", GlobalConstants.WarewolfDebug); if (AllowManualResumption) { ExecuteSaveDataFunc(); } if (_dataObject.IsServiceTestExecution && _originalUniqueID == Guid.Empty) { _originalUniqueID = Guid.Parse(UniqueID); } _dataObject.StopExecution = true; return(new List <string> { _suspensionId }); } catch (Exception ex) { _stateNotifier?.LogExecuteException(ex, this); Dev2Logger.Error(nameof(SuspendExecutionActivity), ex, GlobalConstants.WarewolfError); _dataObject.StopExecution = true; allErrors.AddError(ex.GetAllMessages()); throw; } finally { var serviceTestStep = HandleServiceTestExecution(dataObject); dataObject.ParentInstanceID = _previousParentId; dataObject.ForEachNestingLevel--; dataObject.IsDebugNested = false; HandleDebug(dataObject, serviceTestStep); HandleErrors(dataObject, allErrors); } }
public void SuspendExecutionActivity_Execute_EncryptData_True() { //------------Setup for test-------------------------- var workflowName = "workflowName"; var url = "http://localhost:3142/secure/WorkflowResume"; var resourceId = Guid.NewGuid(); var nextNodeId = Guid.NewGuid(); var workflowInstanceId = Guid.NewGuid(); var env = CreateExecutionEnvironment(); env.Assign("[[UUID]]", "public", 0); env.Assign("[[JourneyName]]", "whatever", 0); var mockStateNotifier = new Mock<IStateNotifier>(); mockStateNotifier.Setup(stateNotifier => stateNotifier.LogActivityExecuteState(It.IsAny<IDev2Activity>())); var environmentId = Guid.Empty; var mockPrincipal = new Mock<ClaimsPrincipal>(); mockPrincipal.Setup(o => o.Identity).Returns(WindowsIdentity.GetCurrent()); var dataObject = new DsfDataObject(CurrentDl, ExecutionId) { ServiceName = workflowName, ResourceID = resourceId, WorkflowInstanceId = workflowInstanceId, WebUrl = url, ServerID = Guid.NewGuid(), ExecutingUser = mockPrincipal.Object, IsDebug = true, EnvironmentID = environmentId, Environment = env, IsRemoteInvokeOverridden = false, DataList = new StringBuilder(CurrentDl), IsServiceTestExecution = true }; var mockActivity = new Mock<IDev2Activity>(); mockActivity.Setup(o => o.UniqueID).Returns(nextNodeId.ToString()); var dev2Activities = new List<IDev2Activity> {mockActivity.Object}; var activity = CreateWorkflow(); var activityFunction = new ActivityFunc<string, bool> { DisplayName = activity.DisplayName, Handler = activity, }; var suspendUntil = DateTime.Now.AddDays(1); var config = new PersistenceSettings { Enable = true }; var currentEnvironment = dataObject.Environment.ToJson(); var values = new Dictionary<string, StringBuilder> { {"resourceID", new StringBuilder(dataObject.ResourceID.ToString())}, {"environment", new StringBuilder(DpapiWrapper.Encrypt(currentEnvironment))}, {"startActivityId", new StringBuilder(nextNodeId.ToString())}, {"versionNumber", new StringBuilder(dataObject.VersionNumber.ToString())}, {"currentuserprincipal", new StringBuilder(WindowsIdentity.GetCurrent().Name)} }; var mockSuspendExecution = new Mock<IPersistenceExecution>(); mockSuspendExecution.Setup(o => o.CreateAndScheduleJob(enSuspendOption.SuspendUntil, suspendUntil.ToString(), values)).Verifiable(); var suspendExecutionActivity = new SuspendExecutionActivity(config, mockSuspendExecution.Object) { SuspendOption = enSuspendOption.SuspendUntil, PersistValue = suspendUntil.ToString(), AllowManualResumption = true, EncryptData = true, SaveDataFunc = activityFunction, //Result = "[[SuspendID]]", NextNodes = dev2Activities }; suspendExecutionActivity.SetStateNotifier(mockStateNotifier.Object); //------------Execute Test--------------------------- suspendExecutionActivity.Execute(dataObject, 0); //------------Assert Results------------------------- Assert.AreEqual(0, env.Errors.Count); GetScalarValueFromEnvironment(env, "SuspendID", out string suspendId, out string error); Assert.AreEqual(suspendId, suspendExecutionActivity.Response); //TODO: We need to improve on this verify to validate that the environment is encrypted. Verify fails for unknown mismatch mockSuspendExecution.Verify(o => o.CreateAndScheduleJob(enSuspendOption.SuspendUntil, suspendUntil.ToString(), It.IsAny<Dictionary<string, StringBuilder>>()), Times.Once); }