Example #1
0
        public HumanStrategy(Container container)
        {
            var randomCodeGenerator = container.GetInstance<IRandomCodeGenerator>();
            _verifier = container.GetInstance<IVerifier>();
            _guessHistory = new Queue<VerificationResult>();

            _randomCode = randomCodeGenerator.Generate();
        }
Example #2
0
        /// <summary>
        /// Asserts that two strings are equal, and prints a diff between the two if they are not.
        /// </summary>
        /// <param name="verifier">The verifier instance.</param>
        /// <param name="expected">The expected string. This is presented as the "baseline/before" side in the diff.</param>
        /// <param name="actual">The actual string. This is presented as the changed or "after" side in the diff.</param>
        /// <param name="message">The message to precede the diff, if the values are not equal.</param>
        public static void EqualOrDiff(this IVerifier verifier, string expected, string actual, string?message = null)
        {
            Requires.NotNull(verifier, nameof(verifier));

            if (expected != actual)
            {
                var diff           = s_diffBuilder.BuildDiffModel(expected, actual, ignoreWhitespace: false, ignoreCase: false, s_lineChunker);
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine(
                    string.IsNullOrEmpty(message)
                        ? "Actual and expected values differ. Expected shown in baseline of diff:"
                        : message);

                if (!diff.Lines.Any(line => line.Type == ChangeType.Inserted || line.Type == ChangeType.Deleted))
                {
                    // We have a failure only caused by line ending differences; recalculate with line endings visible
                    diff = s_diffBuilder.BuildDiffModel(expected, actual, ignoreWhitespace: false, ignoreCase: false, s_lineEndingsPreservingChunker);
                }

                foreach (var line in diff.Lines)
                {
                    switch (line.Type)
                    {
                    case ChangeType.Inserted:
                        messageBuilder.Append("+");
                        break;

                    case ChangeType.Deleted:
                        messageBuilder.Append("-");
                        break;

                    default:
                        messageBuilder.Append(" ");
                        break;
                    }

                    messageBuilder.AppendLine(line.Text.Replace("\r", "<CR>").Replace("\n", "<LF>"));
                }

                verifier.Fail(messageBuilder.ToString());
            }
        }
        /// <summary>
        /// Implements a workaround for issue #936, force re-parsing to get the same sort of syntax tree as the original document.
        /// </summary>
        /// <param name="project">The project to update.</param>
        /// <param name="verifier">The verifier to use for test assertions.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
        /// <returns>The updated <see cref="Project"/>.</returns>
        private async Task <Project> RecreateProjectDocumentsAsync(Project project, IVerifier verifier, CancellationToken cancellationToken)
        {
            foreach (var documentId in project.DocumentIds)
            {
                var document    = project.GetDocument(documentId);
                var initialTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                document = await RecreateDocumentAsync(document, cancellationToken).ConfigureAwait(false);

                var recreatedTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                if (CodeActionValidationMode != CodeActionValidationMode.None)
                {
                    try
                    {
                        // We expect the tree produced by the code fix (initialTree) to match the form of the tree produced
                        // by the compiler for the same text (recreatedTree).
                        TreeEqualityVisitor.AssertNodesEqual(
                            verifier,
                            SyntaxKindType,
                            await recreatedTree.GetRootAsync(cancellationToken).ConfigureAwait(false),
                            await initialTree.GetRootAsync(cancellationToken).ConfigureAwait(false),
                            checkTrivia: CodeActionValidationMode == CodeActionValidationMode.Full);
                    }
                    catch
                    {
                        // Try to revalidate the tree with a better message
                        var renderedInitialTree   = TreeToString(await initialTree.GetRootAsync(cancellationToken).ConfigureAwait(false), CodeActionValidationMode);
                        var renderedRecreatedTree = TreeToString(await recreatedTree.GetRootAsync(cancellationToken).ConfigureAwait(false), CodeActionValidationMode);
                        verifier.EqualOrDiff(renderedRecreatedTree, renderedInitialTree);

                        // This is not expected to be hit, but it will be hit if the validation failure occurred in a
                        // portion of the tree not captured by the rendered form from TreeToString.
                        throw;
                    }
                }

                project = document.Project;
            }

            return(project);
        }
Example #4
0
        public VerificationResultDto Verify(int loanId)
        {
            VerificationResultDto result;
            // Move logic to _loanService

            // Step 1: Load loan data from Database (Moq data)
            Loan loan = MoqLoanData().FirstOrDefault(x => x.Id == loanId);

            if (loan != null)
            {
                // Step 2: Verify loan
                IVerifier verifier = GetVerifier(loan.Address.State);
                result = verifier.Verify(loan);
            }
            else
            {
                throw new System.Exception($"Requested Loan with id = {loanId} has been deleted or doesn't exist.");
            }

            return(result);
        }
Example #5
0
        public static void IncreaseErrorCount(IVerifier verifier, string errorCountKey, Exception ex = null)
        {
            var errorCountsStr = RedisHelper.StringGet(RedisDBIndex, errorCountKey);

            int.TryParse(errorCountsStr, out int errorCount);
            ++errorCount;
            int spInt = verifier.GetLockTime();

            RedisHelper.StringSet(RedisDBIndex, errorCountKey, errorCount.ToString(), TimeSpan.FromMinutes(spInt));
            if (errorCount >= Constant.VIRIFY_FAILD_TIMES_LIMIT)
            {
                var minCount = GetErrorLockTime(errorCountKey);
                verifier.FailedMoreTimes(minCount);
            }
            else
            {
                if (ex != null)
                {
                    throw ex;
                }
                verifier.VerifyFaild(Constant.VIRIFY_FAILD_TIMES_LIMIT - errorCount);
            }
        }
Example #6
0
        public Tuple <bool, string> VerifyPassword(string password, IVerifier verifier)
        {
            if (verifier == null)
            {
                throw new ArgumentNullException(nameof(verifier));
            }

            var result = new StringBuilder();

            foreach (var verification in verifier)
            {
                var temp = verification.VerifyPassword(password);
                if (!temp.Item1)
                {
                    return(new Tuple <bool, string>(false, temp.Item2));
                }

                result.Append(temp.Item2);
            }

            _repository.Create(password);
            return(new Tuple <bool, string>(true, result.ToString()));
        }
        /// <summary>
        /// Asserts that two strings are equal, and prints a diff between the two if they are not.
        /// </summary>
        /// <param name="verifier">The verifier instance.</param>
        /// <param name="expected">The expected string. This is presented as the "baseline/before" side in the diff.</param>
        /// <param name="actual">The actual string. This is presented as the changed or "after" side in the diff.</param>
        /// <param name="message">The message to precede the diff, if the values are not equal.</param>
        public static void EqualOrDiff(this IVerifier verifier, string expected, string actual, string?message = null)
        {
            Requires.NotNull(verifier, nameof(verifier));

            if (expected != actual)
            {
                var diffBuilder    = new InlineDiffBuilder(new Differ());
                var diff           = diffBuilder.BuildDiffModel(expected, actual, ignoreWhitespace: false);
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine(
                    string.IsNullOrEmpty(message)
                        ? "Actual and expected values differ. Expected shown in baseline of diff:"
                        : message);

                foreach (var line in diff.Lines)
                {
                    switch (line.Type)
                    {
                    case ChangeType.Inserted:
                        messageBuilder.Append("+");
                        break;

                    case ChangeType.Deleted:
                        messageBuilder.Append("-");
                        break;

                    default:
                        messageBuilder.Append(" ");
                        break;
                    }

                    messageBuilder.AppendLine(line.Text);
                }

                verifier.Fail(messageBuilder.ToString());
            }
        }
        public void VerificationPipelineMult_Critical_Failure_Test()
        {
            var mock1 = new Mock <IVerifier>();

            mock1.Setup(x => x.VerificationPriority).Returns(1);
            mock1.Setup(x => x.Verify(It.IsAny <InterceptionProcessingData>())).Returns(new List <VerificationFailure>()
            {
                new CriticalFailure()
            });

            var mock2 = new Mock <IVerifier>();

            mock2.Setup(x => x.VerificationPriority).Returns(2);
            mock2.Setup(x => x.Verify(It.IsAny <InterceptionProcessingData>())).Returns(_successfulVerification);

            var verifiers = new IVerifier[] { mock2.Object, mock1.Object };
            var pipeline  = new VerificationPipeline(verifiers);

            var res = pipeline.VerifyInterception(TestClass.Method1Entry);

            Assert.IsTrue(res.HasAnyFailure);
            Assert.IsTrue(res.HasCriticalFailure);
            mock2.Verify(x => x.Verify(It.IsAny <InterceptionProcessingData>()), Times.Never);
        }
Example #9
0
        public static void Verify(DbContext dbContext, IEntity entity, int dmlType)
        {
            if (entity == null)
            {
                return;
            }

            Type entityType = entity.GetType();

            if (dmlType != GlobalConstants.DML_OPERATION_INSERT && dmlType != GlobalConstants.DML_OPERATION_UPDATE && dmlType != GlobalConstants.DML_OPERATION_DELETE)
            {
                throw new BusinessException(GlobalConstants.EXCEPTION_CODE_PARAMETER_INVALID, "错误的dmlType");
            }
            if (dmlType == GlobalConstants.DML_OPERATION_INSERT)
            {
                if (dbContext.Find(entityType, entity.RecordId) != null)
                {
                    throw new BusinessException(GlobalConstants.EXCEPTION_CODE_DATA_ALREADY_EXISTS, $"Id为{entity.RecordId}的{entityType}数据已存在!");
                }
            }
            else if (dmlType == GlobalConstants.DML_OPERATION_UPDATE || dmlType == GlobalConstants.DML_OPERATION_DELETE)
            {
                if (dbContext.Find(entityType, entity.RecordId) == null)
                {
                    throw new BusinessException(GlobalConstants.EXCEPTION_CODE_DATA_ALREADY_EXISTS, $"Id为{entity.RecordId}的{entityType}数据不存在!");
                }
            }

            IVerifier verify = GetVerifier(entityType);

            if (verify == null)
            {
                return;
            }
            verify.VerifyData(dbContext, entity, dmlType);
        }
Example #10
0
        public TenPayHttpClient(SenparcHttpClient httpClient, ISenparcWeixinSettingForTenpayV3 senparcWeixinSettingForTenpayV3 = null, CertType certType = CertType.RSA)
        {
            this._httpClient = httpClient;
            _tenpayV3Setting = senparcWeixinSettingForTenpayV3 ?? Senparc.Weixin.Config.SenparcWeixinSetting.TenpayV3Setting;

            //从工厂获得签名和验签的方法类
            _signer   = TenPayCertFactory.GetSigner(certType);
            _verifier = TenPayCertFactory.GetVerifier(certType);

            #region 配置UA

            //ACCEPT header
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

            //User-Agent header
            var userAgentValues = UserAgentValues.Instance;
            _client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Senparc.Weixin.TenPayV3-C#", userAgentValues.TenPayV3Version));
            _client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue($"(Senparc.Weixin {userAgentValues.SenparcWeixinVersion})"));
            _client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(".NET", userAgentValues.RuntimeVersion));
            _client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue($"({userAgentValues.OSVersion})"));

            #endregion
        }
Example #11
0
 public TestService(IVerifier verifier)
 => _verifier = verifier;
 public PasswordCheckerService(IVerifier verifier) : this(new SqlRepository(), verifier)
 {
 }
Example #13
0
        public static async Task <RotaryTestManager> CreateRotaryTest(IUnityContainer container, EvcCommunicationClient instrumentCommClient, string tachometerPortName, IVerifier verifier)
        {
            TachometerCommunicator tachComm = null;

            if (!string.IsNullOrEmpty(tachometerPortName))
            {
                tachComm = new TachometerCommunicator(tachometerPortName);
            }

            await instrumentCommClient.Connect();

            var itemValues = await instrumentCommClient.GetItemValues(instrumentCommClient.ItemDetails.GetAllItemNumbers());

            await instrumentCommClient.Disconnect();

            var instrument = new Instrument(InstrumentType.MiniMax, itemValues);
            var driveType  = new RotaryDrive(instrument);

            CreateVerificationTests(instrument, driveType);

            var volumeTest       = instrument.VolumeTest;
            var rotaryVolumeTest = new RotaryVolumeVerification(container.Resolve <IEventAggregator>(), volumeTest, instrumentCommClient, tachComm);

            var manager = new RotaryTestManager(container, instrument, instrumentCommClient, rotaryVolumeTest, verifier);

            container.RegisterInstance <TestManager>(manager);

            return(manager);
        }
Example #14
0
 private RotaryTestManager(IUnityContainer container, Instrument instrument,
                           EvcCommunicationClient instrumentCommunicator, VolumeVerificationManager volumeTestManager, IVerifier verifier)
     : base(container, instrument, instrumentCommunicator, verifier)
 {
     VolumeTestManager = volumeTestManager;
 }
Example #15
0
 public PackageVerifier(IVerifier verifier)
 {
     this._verifier = verifier;
 }
Example #16
0
        /// <summary>
        /// Called to test a C# code fix when applied on the input source as a string.
        /// </summary>
        /// <param name="testState">The effective input test state.</param>
        /// <param name="fixedState">The effective test state after incremental code fixes are applied.</param>
        /// <param name="batchFixedState">The effective test state after batch code fixes are applied.</param>
        /// <param name="verifier">The verifier to use for test assertions.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        protected async Task VerifyFixAsync(SolutionState testState, SolutionState fixedState, SolutionState batchFixedState, IVerifier verifier, CancellationToken cancellationToken)
        {
            int numberOfIncrementalIterations;
            int numberOfFixAllIterations;
            int numberOfFixAllInDocumentIterations;

            if (NumberOfIncrementalIterations != null)
            {
                numberOfIncrementalIterations = NumberOfIncrementalIterations.Value;
            }
            else
            {
                if (!HasAnyChange(testState, fixedState))
                {
                    numberOfIncrementalIterations = 0;
                }
                else
                {
                    // Expect at most one iteration per fixable diagnostic
                    var fixers = GetCodeFixProviders().ToArray();
                    var fixableExpectedDiagnostics = testState.ExpectedDiagnostics.Count(diagnostic => fixers.Any(fixer => fixer.FixableDiagnosticIds.Contains(diagnostic.Id)));
                    numberOfIncrementalIterations = -fixableExpectedDiagnostics;
                }
            }

            if (NumberOfFixAllIterations != null)
            {
                numberOfFixAllIterations = NumberOfFixAllIterations.Value;
            }
            else
            {
                if (!HasAnyChange(testState, batchFixedState))
                {
                    numberOfFixAllIterations = 0;
                }
                else
                {
                    numberOfFixAllIterations = 1;
                }
            }

            if (NumberOfFixAllInDocumentIterations != null)
            {
                numberOfFixAllInDocumentIterations = NumberOfFixAllInDocumentIterations.Value;
            }
            else
            {
                numberOfFixAllInDocumentIterations = numberOfFixAllIterations;
            }

            var t1 = VerifyFixAsync(Language, GetDiagnosticAnalyzers().ToImmutableArray(), GetCodeFixProviders().ToImmutableArray(), testState, fixedState, numberOfIncrementalIterations, FixEachAnalyzerDiagnosticAsync, verifier.PushContext("Iterative code fix application"), cancellationToken).ConfigureAwait(false);

            var fixAllProvider = GetCodeFixProviders().Select(codeFixProvider => codeFixProvider.GetFixAllProvider()).Where(codeFixProvider => codeFixProvider != null).ToImmutableArray();

            if (fixAllProvider.IsEmpty)
            {
                await t1;
            }
            else
            {
                if (Debugger.IsAttached)
                {
                    await t1;
                }

                var t2 = VerifyFixAsync(Language, GetDiagnosticAnalyzers().ToImmutableArray(), GetCodeFixProviders().ToImmutableArray(), testState, batchFixedState, numberOfFixAllInDocumentIterations, FixAllAnalyzerDiagnosticsInDocumentAsync, verifier.PushContext("Fix all in document"), cancellationToken).ConfigureAwait(false);
                if (Debugger.IsAttached)
                {
                    await t2;
                }

                var t3 = VerifyFixAsync(Language, GetDiagnosticAnalyzers().ToImmutableArray(), GetCodeFixProviders().ToImmutableArray(), testState, batchFixedState, numberOfFixAllIterations, FixAllAnalyzerDiagnosticsInProjectAsync, verifier.PushContext("Fix all in project"), cancellationToken).ConfigureAwait(false);
                if (Debugger.IsAttached)
                {
                    await t3;
                }

                var t4 = VerifyFixAsync(Language, GetDiagnosticAnalyzers().ToImmutableArray(), GetCodeFixProviders().ToImmutableArray(), testState, batchFixedState, numberOfFixAllIterations, FixAllAnalyzerDiagnosticsInSolutionAsync, verifier.PushContext("Fix all in solution"), cancellationToken).ConfigureAwait(false);
                if (Debugger.IsAttached)
                {
                    await t4;
                }

                if (!Debugger.IsAttached)
                {
                    // Allow the operations to run in parallel
                    await t1;
                    await t2;
                    await t3;
                    await t4;
                }
            }
        }
        /// <summary>
        /// Apply the inputted <see cref="CodeAction"/> to the inputted document.
        /// Meant to be used to apply code fixes.
        /// </summary>
        /// <param name="project">The <see cref="Project"/> to apply the code action on.</param>
        /// <param name="codeAction">A <see cref="CodeAction"/> that will be applied to the
        /// <paramref name="project"/>.</param>
        /// <param name="verifier">The verifier to use for test assertions.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
        /// <returns>A <see cref="Project"/> with the changes from the <see cref="CodeAction"/>.</returns>
        protected async Task <Project> ApplyCodeActionAsync(Project project, CodeAction codeAction, IVerifier verifier, CancellationToken cancellationToken)
        {
            var operations = await codeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false);

            var solution       = operations.OfType <ApplyChangesOperation>().Single().ChangedSolution;
            var changedProject = solution.GetProject(project.Id);

            if (changedProject != project)
            {
                project = await RecreateProjectDocumentsAsync(changedProject, verifier, cancellationToken).ConfigureAwait(false);
            }

            return(project);
        }
Example #18
0
        private async Task <Project> FixAllAnalyerDiagnosticsInScopeAsync(FixAllScope scope, ImmutableArray <DiagnosticAnalyzer> analyzers, ImmutableArray <CodeFixProvider> codeFixProviders, int?codeFixIndex, string codeFixEquivalenceKey, Project project, int numberOfIterations, IVerifier verifier, CancellationToken cancellationToken)
        {
            var expectedNumberOfIterations = numberOfIterations;

            if (numberOfIterations < 0)
            {
                numberOfIterations = -numberOfIterations;
            }

            var previousDiagnostics = ImmutableArray.Create <Diagnostic>();

            bool done;

            do
            {
                var analyzerDiagnostics = await GetSortedDiagnosticsAsync(project.Solution, analyzers, CompilerDiagnostics, cancellationToken).ConfigureAwait(false);

                if (analyzerDiagnostics.Length == 0)
                {
                    break;
                }

                if (!AreDiagnosticsDifferent(analyzerDiagnostics, previousDiagnostics))
                {
                    break;
                }

                verifier.False(--numberOfIterations < -1, "The upper limit for the number of fix all iterations was exceeded");

                Diagnostic      firstDiagnostic          = null;
                CodeFixProvider effectiveCodeFixProvider = null;
                string          equivalenceKey           = null;
                foreach (var diagnostic in analyzerDiagnostics)
                {
                    var actions = new List <(CodeAction, CodeFixProvider)>();

                    foreach (var codeFixProvider in codeFixProviders)
                    {
                        if (!codeFixProvider.FixableDiagnosticIds.Contains(diagnostic.Id))
                        {
                            // do not pass unsupported diagnostics to a code fix provider
                            continue;
                        }

                        var context = new CodeFixContext(project.GetDocument(diagnostic.Location.SourceTree), diagnostic, (a, d) => actions.Add((a, codeFixProvider)), cancellationToken);
                        await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(false);
                    }

                    var actionToApply = TryGetCodeActionToApply(actions.Select(a => a.Item1).ToList(), codeFixIndex, codeFixEquivalenceKey, verifier);
                    if (actionToApply != null)
                    {
                        firstDiagnostic          = diagnostic;
                        effectiveCodeFixProvider = actions.SingleOrDefault(a => a.Item1 == actionToApply).Item2;
                        equivalenceKey           = actionToApply.EquivalenceKey;
                        break;
                    }
                }

                var fixAllProvider = effectiveCodeFixProvider?.GetFixAllProvider();
                if (firstDiagnostic == null || fixAllProvider == null)
                {
                    numberOfIterations++;
                    break;
                }

                previousDiagnostics = analyzerDiagnostics;

                done = true;

                FixAllContext.DiagnosticProvider fixAllDiagnosticProvider = TestDiagnosticProvider.Create(analyzerDiagnostics);

                var analyzerDiagnosticIds = analyzers.SelectMany(x => x.SupportedDiagnostics).Select(x => x.Id);
                var compilerDiagnosticIds = codeFixProviders.SelectMany(codeFixProvider => codeFixProvider.FixableDiagnosticIds).Where(x => x.StartsWith("CS", StringComparison.Ordinal) || x.StartsWith("BC", StringComparison.Ordinal));
                var disabledDiagnosticIds = project.CompilationOptions.SpecificDiagnosticOptions.Where(x => x.Value == ReportDiagnostic.Suppress).Select(x => x.Key);
                var relevantIds           = analyzerDiagnosticIds.Concat(compilerDiagnosticIds).Except(disabledDiagnosticIds).Distinct();
                var fixAllContext         = new FixAllContext(project.GetDocument(firstDiagnostic.Location.SourceTree), effectiveCodeFixProvider, scope, equivalenceKey, relevantIds, fixAllDiagnosticProvider, cancellationToken);

                var action = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(false);

                if (action == null)
                {
                    return(project);
                }

                var fixedProject = await ApplyFixAsync(project, action, cancellationToken).ConfigureAwait(false);

                if (fixedProject != project)
                {
                    done = false;

                    project = await RecreateProjectDocumentsAsync(fixedProject, verifier, cancellationToken).ConfigureAwait(false);
                }
            }while (!done);

            if (expectedNumberOfIterations >= 0)
            {
                verifier.Equal(expectedNumberOfIterations, expectedNumberOfIterations - numberOfIterations, $"Expected '{expectedNumberOfIterations}' iterations but found '{expectedNumberOfIterations - numberOfIterations}' iterations.");
            }
            else
            {
                verifier.True(numberOfIterations >= 0, "The upper limit for the number of code fix iterations was exceeded");
            }

            return(project);
        }
Example #19
0
 public static bool VerifySignedMessage(this IVerifier sig, IDigest digest, byte[] message, int offset, int length) =>
 VerifySignedMessage(sig, digest, new ArraySegment <byte>(message, offset, length));
Example #20
0
 public static bool VerifySignedMessage(this IVerifier sig, IDigest digest, byte[] message) =>
 VerifySignedMessage(sig, digest, new ArraySegment <byte>(message));
Example #21
0
 public static bool Verify(this IVerifier sig, byte[] data, int offset, int count, ArraySegment <byte> signature) =>
 sig.Verify(new ArraySegment <byte>(data, offset, count), signature);
Example #22
0
 public static bool Verify(this IVerifier sig, byte[] data, ArraySegment <byte> signature) =>
 sig.Verify(new ArraySegment <byte>(data), signature);
Example #23
0
        private void ReceiveInitializationResponse(State state, byte[] data)
        {
            if (!(state is ClientState clientState))
            {
                throw new InvalidOperationException("Only the client can receive an init response.");
            }

            var messageSize    = data.Length;
            var macOffset      = messageSize - MacSize;
            var headerIvOffset = macOffset - HeaderIVSize;
            var headerSize     = InitializationNonceSize + EcNumSize;
            var payloadSize    = messageSize - headerSize - MacSize;

            // decrypt header
            var cipher          = new AesCtrMode(AesFactory.GetAes(true, Configuration.ApplicationKey), data, headerIvOffset, HeaderIVSize);
            var decryptedHeader = cipher.Process(data, 0, headerSize);

            Array.Copy(decryptedHeader, 0, data, 0, headerSize);

            // new nonce(16), ecdh pubkey(32), <nonce(16), server pubkey(32),
            // new ecdh pubkey(32) x2, signature(64)>, mac(12)
            var nonce            = new ArraySegment <byte>(data, 0, InitializationNonceSize);
            var rootEcdhKey      = new ArraySegment <byte>(data, InitializationNonceSize, EcNumSize);
            var encryptedPayload = new ArraySegment <byte>(data, headerSize, payloadSize);

            CheckNonce(nonce);

            // decrypt payload
            IKeyAgreement rootEcdh   = clientState.LocalEcdhForInit;
            var           rootPreKey = rootEcdh.DeriveKey(rootEcdhKey);

            rootPreKey = Digest.ComputeDigest(rootPreKey);
            cipher     = new AesCtrMode(AesFactory.GetAes(true, rootPreKey), nonce);
            var decryptedPayload = cipher.Process(encryptedPayload);

            Array.Copy(decryptedPayload, 0, data, headerSize, payloadSize);

            // extract some goodies
            var oldNonce           = new ArraySegment <byte>(data, headerSize, InitializationNonceSize);
            var serverPubKey       = new ArraySegment <byte>(data, headerSize + InitializationNonceSize, EcNumSize);
            var remoteRatchetEcdh0 = new ArraySegment <byte>(data, headerSize + InitializationNonceSize + EcNumSize, EcNumSize);
            var remoteRatchetEcdh1 = new ArraySegment <byte>(data, headerSize + InitializationNonceSize + EcNumSize * 2, EcNumSize);

            // make sure the nonce sent back by the server (which is encrypted and signed)
            // matches the nonce we sent previously
            if (!oldNonce.Matches(clientState.InitializationNonce))
            {
                throw new InvalidOperationException("Nonce did not match");
            }

            // verify that the signature matches
            IVerifier verifier = VerifierFactory.Create(serverPubKey);

            if (!verifier.VerifySignedMessage(Digest, new ArraySegment <byte>(data, 0, payloadSize + headerSize)))
            {
                throw new InvalidOperationException("The signature was invalid");
            }

            // keep the server public key around
            clientState.ServerPublicKey = serverPubKey.ToArray();

            // store the new nonce we got from the server
            clientState.InitializationNonce = nonce.ToArray();
            Log.Verbose($"storing iniitlizaionta nonce: {Log.ShowBytes(nonce)}");

            // we now have enough information to construct our double ratchet
            IKeyAgreement localStep0EcdhRatchet = KeyAgreementFactory.GenerateNew();
            IKeyAgreement localStep1EcdhRatchet = KeyAgreementFactory.GenerateNew();

            // initialize client root key and ecdh ratchet
            var genKeys          = KeyDerivation.GenerateKeys(rootPreKey, clientState.InitializationNonce, 3, 32);
            var rootKey          = genKeys[0];
            var receiveHeaderKey = genKeys[1];
            var sendHeaderKey    = genKeys[2];

            clientState.Ratchets.Add(EcdhRatchetStep.InitializeClient(KeyDerivation, Digest, rootKey,
                                                                      remoteRatchetEcdh0, remoteRatchetEcdh1, localStep0EcdhRatchet,
                                                                      receiveHeaderKey, sendHeaderKey,
                                                                      localStep1EcdhRatchet));

            clientState.LocalEcdhForInit = null;
        }
Example #24
0
 public Handler(IExecutor <T> executor, IValidator <T, TResult> validator, IVerifier <T, TResult> verifier = null)
 {
     this.executor  = executor;
     this.validator = validator;
     this.verifier  = verifier;
 }
Example #25
0
 public PasswordCheckerService(IRepository repository, IVerifier verifier)
 {
     this.repository = repository;
     this.verifier   = verifier;
 }
Example #26
0
        private static CodeAction TryGetCodeActionToApply(List <CodeAction> actions, int?codeFixIndex, string codeFixEquivalenceKey, IVerifier verifier)
        {
            if (codeFixIndex.HasValue && codeFixEquivalenceKey != null)
            {
                if (actions.Count <= codeFixIndex)
                {
                    return(null);
                }

                verifier.Equal(
                    codeFixEquivalenceKey,
                    actions[codeFixIndex.Value].EquivalenceKey,
                    "The code action equivalence key and index must be consistent when both are specified.");

                return(actions[codeFixIndex.Value]);
            }
            else if (codeFixEquivalenceKey != null)
            {
                return(actions.Find(x => x.EquivalenceKey == codeFixEquivalenceKey));
            }
            else if (actions.Count > (codeFixIndex ?? 0))
            {
                return(actions[codeFixIndex ?? 0]);
            }
            else
            {
                return(null);
            }
        }
        protected static CodeAction?TryGetCodeActionToApply(ImmutableArray <CodeAction> actions, int?codeActionIndex, string?codeActionEquivalenceKey, Action <CodeAction, IVerifier>?codeActionVerifier, IVerifier verifier)
        {
            CodeAction?result;

            if (codeActionIndex.HasValue && codeActionEquivalenceKey != null)
            {
                if (actions.Length <= codeActionIndex)
                {
                    return(null);
                }

                verifier.Equal(
                    codeActionEquivalenceKey,
                    actions[codeActionIndex.Value].EquivalenceKey,
                    "The code action equivalence key and index must be consistent when both are specified.");

                result = actions[codeActionIndex.Value];
            }
            else if (codeActionEquivalenceKey != null)
            {
                result = actions.FirstOrDefault(x => x.EquivalenceKey == codeActionEquivalenceKey);
            }
            else if (actions.Length > (codeActionIndex ?? 0))
            {
                result = actions[codeActionIndex ?? 0];
            }
            else
            {
                return(null);
            }

            if (result is object)
            {
                codeActionVerifier?.Invoke(result, verifier);
            }

            return(result);
        }
Example #28
0
 public void AddRule(IVerifier verifier)
 {
     _verifierList.Add(verifier);
 }
Example #29
0
        private async Task <Project> FixEachAnalyzerDiagnosticAsync(ImmutableArray <DiagnosticAnalyzer> analyzers, ImmutableArray <CodeFixProvider> codeFixProviders, int?codeFixIndex, string codeFixEquivalenceKey, Project project, int numberOfIterations, IVerifier verifier, CancellationToken cancellationToken)
        {
            var expectedNumberOfIterations = numberOfIterations;

            if (numberOfIterations < 0)
            {
                numberOfIterations = -numberOfIterations;
            }

            var previousDiagnostics = ImmutableArray.Create <Diagnostic>();

            bool done;

            do
            {
                var analyzerDiagnostics = await GetSortedDiagnosticsAsync(project.Solution, analyzers, CompilerDiagnostics, cancellationToken).ConfigureAwait(false);

                if (analyzerDiagnostics.Length == 0)
                {
                    break;
                }

                if (!AreDiagnosticsDifferent(analyzerDiagnostics, previousDiagnostics))
                {
                    break;
                }

                verifier.True(--numberOfIterations >= -1, "The upper limit for the number of code fix iterations was exceeded");

                previousDiagnostics = analyzerDiagnostics;

                done = true;
                var anyActions = false;
                foreach (var diagnostic in analyzerDiagnostics)
                {
                    var actions = new List <CodeAction>();

                    foreach (var codeFixProvider in codeFixProviders)
                    {
                        if (!codeFixProvider.FixableDiagnosticIds.Contains(diagnostic.Id))
                        {
                            // do not pass unsupported diagnostics to a code fix provider
                            continue;
                        }

                        var context = new CodeFixContext(project.GetDocument(diagnostic.Location.SourceTree), diagnostic, (a, d) => actions.Add(a), cancellationToken);
                        await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(false);
                    }

                    var actionToApply = TryGetCodeActionToApply(actions, codeFixIndex, codeFixEquivalenceKey, verifier);
                    if (actionToApply != null)
                    {
                        anyActions = true;

                        var fixedProject = await ApplyFixAsync(project, actionToApply, cancellationToken).ConfigureAwait(false);

                        if (fixedProject != project)
                        {
                            done = false;

                            project = await RecreateProjectDocumentsAsync(fixedProject, verifier, cancellationToken).ConfigureAwait(false);

                            break;
                        }
                    }
                }

                if (!anyActions)
                {
                    verifier.True(done, "Expected to be done executing actions.");

                    // Avoid counting iterations that do not provide any code actions
                    numberOfIterations++;
                }
            }while (!done);

            if (expectedNumberOfIterations >= 0)
            {
                verifier.Equal(expectedNumberOfIterations, expectedNumberOfIterations - numberOfIterations, $"Expected '{expectedNumberOfIterations}' iterations but found '{expectedNumberOfIterations - numberOfIterations}' iterations.");
            }
            else
            {
                verifier.True(numberOfIterations >= 0, "The upper limit for the number of code fix iterations was exceeded");
            }

            return(project);
        }
Example #30
0
 public FirstFitAlgorithm(IVerifier verifier)
 {
     this.verifier = verifier;
 }
Example #31
0
 private Task <Project> FixAllAnalyzerDiagnosticsInSolutionAsync(ImmutableArray <DiagnosticAnalyzer> analyzers, ImmutableArray <CodeFixProvider> codeFixProviders, int?codeFixIndex, string codeFixEquivalenceKey, Project project, int numberOfIterations, IVerifier verifier, CancellationToken cancellationToken)
 {
     return(FixAllAnalyerDiagnosticsInScopeAsync(FixAllScope.Solution, analyzers, codeFixProviders, codeFixIndex, codeFixEquivalenceKey, project, numberOfIterations, verifier, cancellationToken));
 }
 public CorrectSupportCaseProcessor(IMessagingService messagingService, IVerifier verifier, ISystemClock systemClock)
     : base(messagingService, verifier, systemClock)
 {
 }
 /// <summary>
 /// Called to test a C# source generator when applied on the input source as a string.
 /// </summary>
 /// <param name="testState">The effective input test state.</param>
 /// <param name="fixedState">The effective test state after the source generators are applied.</param>
 /// <param name="verifier">The verifier to use for test assertions.</param>
 /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
 protected async Task <ImmutableArray <Diagnostic> > VerifySourceGeneratorAsync(SolutionState testState, SolutionState fixedState, IVerifier verifier, CancellationToken cancellationToken)
 {
     return(await VerifySourceGeneratorAsync(Language, GetSourceGenerators().ToImmutableArray(), testState, fixedState, ApplySourceGeneratorAsync, verifier.PushContext("Source generator application"), cancellationToken));
 }
 public SupportCaseProcessor(IMessagingService messagingService, IVerifier verifier, ISystemClock systemClock)
 {
     _messagingService = messagingService;
     _verifier = verifier;
     _systemClock = systemClock;
 }