public void CreateSessionShouldSucceed()
        {
            string clientSessionToken    = "e8b1c85f-f9e7-405b-88eb-f1c318371f16";
            int    clientSessionTokenTtl = 500;
            string sessionId             = "4edd81c4-c612-4b0c-b385-7c90f0de6845";

            CreateSessionResult createSessionResult = new CreateSessionResult
            {
                ClientSessionToken    = clientSessionToken,
                ClientSessionTokenTtl = clientSessionTokenTtl,
                SessionId             = sessionId
            };

            string jsonResponse = JsonConvert.SerializeObject(createSessionResult);

            var successResponse = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(jsonResponse),
            };

            Mock <HttpMessageHandler> handlerMock = Auth.Tests.Common.Http.SetupMockMessageHandler(successResponse);
            var httpClient = new HttpClient(handlerMock.Object);

            DocScanClient docScanClient = new DocScanClient(_sdkId, _keyPair, httpClient);

            CreateSessionResult result = docScanClient.CreateSession(
                new SessionSpecificationBuilder().Build());

            Assert.AreEqual(clientSessionToken, result.ClientSessionToken);
            Assert.AreEqual(clientSessionTokenTtl, result.ClientSessionTokenTtl);
            Assert.AreEqual(sessionId, result.SessionId);
        }
Beispiel #2
0
        public void EqualsTrueForInvalidSessions()
        {
            var v1 = new CreateSessionResult <IReadOnlyCacheSession>("error1");
            var v2 = new CreateSessionResult <IReadOnlyCacheSession>("error1");

            Assert.True(v1.Equals(v2));
        }
Beispiel #3
0
 public void CreateSessionStop(Context context, CreateSessionResult <IContentSession> result)
 {
     if (context.IsEnabled)
     {
         TracerOperationFinished(context, result, $"{Name}.CreateSession() stop {result.DurationMs}ms result=[{result}]");
     }
 }
Beispiel #4
0
 public void CreateSessionStop(Context context, CreateSessionResult <ICacheSession> result)
 {
     if (context.IsEnabled)
     {
         Debug(context, $"{Name}.CreateSession() stop {result.DurationMs}ms result=[{result}]");
     }
 }
Beispiel #5
0
 public void ToStringSuccess()
 {
     using (var session = new ThrowingCacheSession())
     {
         var result = new CreateSessionResult <IReadOnlyCacheSession>(session);
         Assert.Contains("Success", result.ToString(), StringComparison.OrdinalIgnoreCase);
     }
 }
Beispiel #6
0
 public void CreateSessionStop(Context context, CreateSessionResult <ICacheSession> result)
 {
     _sessionCounter.Completed(result.Duration.Ticks);
     if (context.IsEnabled)
     {
         Debug(context, $"{Name}.CreateSession() stop {result.DurationMs}ms result=[{result}]");
     }
 }
Beispiel #7
0
 public void EqualsFalseCodeMismatch()
 {
     using (var session1 = new ThrowingCacheSession())
     {
         var v1 = new CreateSessionResult <IReadOnlyCacheSession>(session1);
         var v2 = new CreateSessionResult <IReadOnlyCacheSession>("error");
         Assert.False(v1.Equals(v2));
     }
 }
Beispiel #8
0
 public void EqualsObjectFalse()
 {
     using (var session = new ThrowingCacheSession())
     {
         var v1 = new CreateSessionResult <IReadOnlyCacheSession>(session);
         var v2 = new object();
         Assert.False(v1.Equals(v2));
     }
 }
Beispiel #9
0
 public void EqualsFalseSessionMismatch()
 {
     using (var session1 = new ThrowingCacheSession("session1"))
         using (var session2 = new ThrowingCacheSession("session2"))
         {
             var v1 = new CreateSessionResult <IReadOnlyCacheSession>(session1);
             var v2 = new CreateSessionResult <IReadOnlyCacheSession>(session2);
             Assert.False(v1.Equals(v2));
         }
 }
Beispiel #10
0
 public void EqualsTrueNotReferenceEqualSession()
 {
     using (var session1 = new ThrowingCacheSession())
         using (var session2 = new ThrowingCacheSession())
         {
             var v1 = new CreateSessionResult <IReadOnlyCacheSession>(session1);
             var v2 = new CreateSessionResult <IReadOnlyCacheSession>(session2);
             Assert.True(v1.Equals(v2));
         }
 }
Beispiel #11
0
 public void GetHashCodeNotSameWhenNotEqual()
 {
     using (var session1 = new ThrowingCacheSession("session1"))
         using (var session2 = new ThrowingCacheSession("session2"))
         {
             var v1 = new CreateSessionResult <IReadOnlyCacheSession>(session1);
             var v2 = new CreateSessionResult <IReadOnlyCacheSession>(session2);
             Assert.NotEqual(v1.GetHashCode(), v2.GetHashCode());
         }
 }
        public void CreateSessionShouldThrowForNonSuccessStatusCode(HttpStatusCode httpStatusCode)
        {
            DocScanClient docScanClient = SetupDocScanClientResponse(httpStatusCode);

            var aggregateException = Assert.ThrowsException <AggregateException>(() =>
            {
                CreateSessionResult result = docScanClient.CreateSession(
                    new SessionSpecificationBuilder().Build());
            });

            Assert.IsTrue(TestTools.Exceptions.IsExceptionInAggregateException <DocScanException>(aggregateException));
        }
Beispiel #13
0
        protected override async Task <BoolResult> StartupCoreAsync(OperationContext context)
        {
            await _store.StartupAsync(context).ThrowIfFailure();

            if (_fileSystem.DirectoryExists(_rootPath / "temp"))
            {
                _fileSystem.DeleteDirectory(_rootPath / "temp", DeleteOptions.All);
            }

            await _copier.StartupAsync(context).ThrowIfFailure();

            CreateSessionResult <IContentSession> sessionResult = _store.CreateSession(context, SessionName, ImplicitPin.None).ThrowIfFailure();

            _session = sessionResult.Session !;

            return(await _session.StartupAsync(context));
        }
        /// <inheritdoc />
        public CreateSessionResult <IContentSession> CreateSession(Context context, string name, ImplicitPin implicitPin)
        {
            return(CreateSessionCall.Run(_tracer, OperationContext(context), name, () =>
            {
                CreateSessionResult <IContentSession> innerSessionResult = InnerContentStore.CreateSession(context, name, implicitPin);

                if (innerSessionResult.Succeeded)
                {
                    var session = new DistributedContentSession <T>(
                        name,
                        innerSessionResult.Session,
                        _contentLocationStore,
                        _distributedCopier,
                        LocalMachineLocation,
                        pinCache: _pinCache,
                        contentTrackerUpdater: _contentTrackerUpdater,
                        settings: _settings);
                    return new CreateSessionResult <IContentSession>(session);
                }

                return new CreateSessionResult <IContentSession>(innerSessionResult, "Could not initialize inner content session with error");
            }));
        }
        public IActionResult Index()
        {
            //Build Session Spec
            var sessionSpec = new SessionSpecificationBuilder()
                              .WithClientSessionTokenTtl(600)
                              .WithResourcesTtl(90000)
                              .WithUserTrackingId("some-user-tracking-id")
                              //Add Checks (using builders)
                              .WithRequestedCheck(
                new RequestedDocumentAuthenticityCheckBuilder()
                .WithManualCheckAlways()
                .Build()
                )
                              .WithRequestedCheck(
                new RequestedLivenessCheckBuilder()
                .ForZoomLiveness()
                .Build()
                )
                              .WithRequestedCheck(
                new RequestedFaceMatchCheckBuilder()
                .WithManualCheckAlways()
                .Build()
                )
                              .WithRequestedCheck(
                new RequestedIdDocumentComparisonCheckBuilder()
                .Build())
                              .WithRequestedCheck(
                new RequestedThirdPartyIdentityCheckBuilder()
                .Build())
                              .WithRequestedCheck(
                new RequestedWatchlistScreeningCheckBuilder()
                .ForAdverseMedia()
                .ForSanctions()
                .Build()
                )
                              //Add Tasks (using builders)
                              .WithRequestedTask(
                new RequestedTextExtractionTaskBuilder()
                .WithManualCheckAlways()
                .WithChipDataDesired()
                .Build()
                )
                              .WithRequestedTask(
                new RequestedSupplementaryDocTextExtractionTaskBuilder()
                .WithManualCheckAlways()
                .Build()
                )
                              //Add Sdk Config (with builder)
                              .WithSdkConfig(
                new SdkConfigBuilder()
                .WithAllowsCameraAndUpload()
                .WithPrimaryColour("#2d9fff")
                .WithSecondaryColour("#FFFFFF")
                .WithFontColour("#FFFFFF")
                .WithLocale("en-GB")
                .WithPresetIssuingCountry("GBR")
                .WithSuccessUrl($"{_baseUrl}/idverify/success")
                .WithErrorUrl($"{_baseUrl}/idverify/error")
                .WithPrivacyPolicyUrl($"{_baseUrl}/privacy-policy")
                .WithAllowHandoff(false)
                .Build()
                )
                              //Add Required Documents (with builders)
                              .WithRequiredDocument(
                new RequiredIdDocumentBuilder()
                .WithFilter(
                    (new OrthogonalRestrictionsFilterBuilder())
                    .WithIncludedDocumentTypes(new List <string> {
                "PASSPORT"
            })
                    .Build()
                    )
                .Build()
                )
                              .WithRequiredDocument(
                new RequiredIdDocumentBuilder()
                .WithFilter(
                    (new OrthogonalRestrictionsFilterBuilder())
                    .WithIncludedDocumentTypes(new List <string> {
                "DRIVING_LICENCE"
            })
                    .Build()
                    )
                .Build()
                )
                              .WithRequiredDocument(
                new RequiredSupplementaryDocumentBuilder()
                .WithObjective(
                    new ProofOfAddressObjectiveBuilder().Build())
                .Build()
                )
                              .Build();

            CreateSessionResult createSessionResult = _client.CreateSession(sessionSpec);
            string sessionId = createSessionResult.SessionId;

            string path = $"web/index.html?sessionID={sessionId}&sessionToken={createSessionResult.ClientSessionToken}";
            Uri    uri  = new Uri(_apiUrl, path);

            ViewBag.iframeUrl = uri.ToString();

            TempData["sessionId"] = sessionId;
            return(View());
        }
        internal void IncorporateStrongFingerprints(
            [Required, Description("Path to log containing the strong fingerpints")] string log,
            [Required, Description("BuildCache url to which to incorporate the fingerprints")] string buildCacheUrl,
            [Required, Description("BlobStore url associated to the buildCache url")] string blobStoreUrl,
            [Required, Description("Cache namespace to target within BuildCache")] string cacheNamespace,
            [Required, Description("Whether or not to use the newer Blob implementation of BuildCache")] bool useBlobContentHashLists,
            [DefaultValue(false), Description("Whether or not to use aad authentication")] bool useAad,
            [DefaultValue(null), Description("Maximum number of fingerprint batches sent in parallel within a set. Default: System.Environment.ProcessorCount")] int?maxDegreeOfParallelism,
            [DefaultValue(null), Description("Maximum number of fingerprints per batch within a set. Default: 500")] int?maxFingerprintsPerRequest,
            [DefaultValue(1), Description("How many times to incorporate the set of fingerprints")] int iterationCount,
            [DefaultValue(1), Description("How many sets of fingerprints to incorporate in parallel")] int iterationDegreeOfParallelism)
        {
            Initialize();

            Stopwatch    stopwatch = Stopwatch.StartNew();
            int          count     = 0;
            AbsolutePath logPath   = new AbsolutePath(log);

            if (!_fileSystem.FileExists(logPath))
            {
                throw new ArgumentException($"Log file {log} does not exist.", nameof(log));
            }

            BuildCacheServiceConfiguration config = new BuildCacheServiceConfiguration(buildCacheUrl, blobStoreUrl)
            {
                CacheNamespace                  = cacheNamespace,
                UseAad                          = useAad,
                UseBlobContentHashLists         = useBlobContentHashLists,
                FingerprintIncorporationEnabled = true
            };

            if (maxDegreeOfParallelism.HasValue)
            {
                config.MaxDegreeOfParallelismForIncorporateRequests = maxDegreeOfParallelism.Value;
            }

            if (maxFingerprintsPerRequest.HasValue)
            {
                config.MaxFingerprintsPerIncorporateRequest = maxFingerprintsPerRequest.Value;
            }

            using (var logStream = _fileSystem.OpenReadOnlySafeAsync(logPath, FileShare.Read | FileShare.Delete).Result)
                using (StreamReader reader = new StreamReader(logStream))
                {
                    Context context = new Context(_logger);
                    RunBuildCacheAsync(
                        context,
                        config,
                        async cache =>
                    {
                        const string sessionName      = "CommandLineSessionName";
                        const ImplicitPin implicitPin = ImplicitPin.None;

                        List <StrongFingerprint> strongFingerprints = EnumerateUniqueStrongFingerprints(reader).ToList();
                        count = strongFingerprints.Count;
                        _logger.Always($"Incorporating {count} strong fingerprints {iterationCount} times");

                        ActionBlock <List <StrongFingerprint> > incorporateBlock =
                            new ActionBlock <List <StrongFingerprint> >(
                                async fingerprints =>
                        {
                            var iterationStopwatch = Stopwatch.StartNew();
                            var iterationContext   = context.CreateNested(nameof(IncorporateStrongFingerprints));
                            CreateSessionResult <ICacheSession> createSessionResult = cache.CreateSession(
                                iterationContext, sessionName, implicitPin);
                            if (!createSessionResult.Succeeded)
                            {
                                _tracer.Error(iterationContext, $"Failed to create BuildCache session. Result=[{createSessionResult}]");
                                return;
                            }

                            using (ICacheSession session = createSessionResult.Session)
                            {
                                BoolResult r = await session.StartupAsync(iterationContext);
                                if (!r.Succeeded)
                                {
                                    _tracer.Error(iterationContext, $"Failed to start up BuildCache client session. Result=[{r}]");
                                    return;
                                }

                                try
                                {
                                    await session.IncorporateStrongFingerprintsAsync(
                                        iterationContext, strongFingerprints.AsTasks(), CancellationToken.None).IgnoreFailure();
                                }
                                finally
                                {
                                    iterationStopwatch.Stop();
                                    r = await session.ShutdownAsync(iterationContext);
                                    if (r.Succeeded)
                                    {
                                        _tracer.Always(context,
                                                       $"Incorporated {count} fingerprints in {iterationStopwatch.ElapsedMilliseconds / 1000} seconds.");
                                    }
                                    else
                                    {
                                        _tracer.Error(iterationContext, $"Failed to shut down BuildCache client Session. Result=[{r}]");
                                    }
                                }
                            }
                        },
                                new ExecutionDataflowBlockOptions {
                            MaxDegreeOfParallelism = iterationDegreeOfParallelism
                        });

                        for (int i = 0; i < iterationCount; i++)
                        {
                            await incorporateBlock.SendAsync(strongFingerprints);
                        }

                        incorporateBlock.Complete();

                        await incorporateBlock.Completion;
                    }).Wait();
                }

            stopwatch.Stop();
            _logger.Always($"Incorporated {count} unique strong fingerprints {iterationCount} times in {stopwatch.ElapsedMilliseconds / 1000} seconds.");
        }
Beispiel #17
0
        public async Task UploadFileIsSuccessful()
        {
            // arrange
            var    fileName = "foo.txt";
            string filePath = Path.Combine(Path.GetTempPath(), fileName);

            File.WriteAllText(filePath, "123");
            long fullFileSize = new FileInfo(filePath).Length;
            var  hashForFile  = new MD5FileHasher().CalculateHashForFile(filePath);

            int resourceId      = 1;
            var checkFileResult = new CheckFileResult
            {
                StatusCode          = HttpStatusCode.NoContent,
                LastModified        = DateTimeOffset.UtcNow,
                FileNameOnServer    = fileName,
                HashForFileOnServer = "MyHash"
            };

            mockFileService.Setup(
                service => service.CheckFileAsync(resourceId))
            .ReturnsAsync(checkFileResult);

            var sessionId     = Guid.NewGuid();
            var uploadSession = new UploadSession
            {
                SessionId = sessionId,
                FileUploadChunkSizeInBytes       = 1,
                FileUploadMaxFileSizeInMegabytes = 10
            };
            var createSessionResult = new CreateSessionResult
            {
                StatusCode = HttpStatusCode.OK,
                Session    = uploadSession
            };

            mockFileService.Setup(
                service => service.CreateNewUploadSessionAsync(resourceId))
            .ReturnsAsync(createSessionResult);

            var fileSplitter     = new FileSplitter();
            var countOfFileParts = fileSplitter.GetCountOfFileParts(createSessionResult.Session.FileUploadChunkSizeInBytes, fullFileSize);

            var uploadStreamResult = new UploadStreamResult
            {
                StatusCode    = HttpStatusCode.OK,
                PartsUploaded = 1
            };

            mockFileService.Setup(
                service => service.UploadStreamAsync(resourceId, sessionId,
                                                     It.IsAny <Stream>(), It.IsAny <FilePart>(), fileName, fullFileSize, countOfFileParts))
            .ReturnsAsync(uploadStreamResult);

            var commitResult = new CommitResult
            {
                StatusCode = HttpStatusCode.OK,
                Session    = uploadSession
            };

            mockFileService.Setup(
                service => service.CommitAsync(resourceId, sessionId, fileName, hashForFile, fullFileSize,
                                               It.IsAny <IList <FilePart> >()))
            .ReturnsAsync(commitResult);

            // act
            await this.classUnderTest.UploadFileAsync(resourceId, filePath, this.cancellationToken);

            // assert
            mockFileService.Verify(
                service => service.CheckFileAsync(1),
                Times.Once);

            mockFileService.Verify(
                service => service.CreateNewUploadSessionAsync(resourceId),
                Times.Once);

            mockFileService.Verify(
                service => service.UploadStreamAsync(resourceId, sessionId,
                                                     It.IsAny <Stream>(), It.IsAny <FilePart>(), fileName, fullFileSize, countOfFileParts),
                Times.Exactly(countOfFileParts));

            mockFileService.Verify(
                service => service.CommitAsync(resourceId, sessionId, fileName, hashForFile, fullFileSize,
                                               It.IsAny <IList <FilePart> >()),
                Times.Once);
        }
        /// <inheritdoc />
        /// <summary>
        /// This calls POST Files({resourceId})/UploadSessions
        /// </summary>
        /// <param name="resourceId"></param>
        /// <returns></returns>
        public async Task <CreateSessionResult> CreateNewUploadSessionAsync(int resourceId)
        {
            if (resourceId <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(resourceId));
            }

            var fullUri = new Uri(this.mdsBaseUrl, $"Files({resourceId})/UploadSessions");

            var method = Convert.ToString(HttpMethod.Post);

            await this.SetAuthorizationHeaderInHttpClientAsync(resourceId);

            OnNavigating(new NavigatingEventArgs(resourceId, method, fullUri));

            var form = new
            {
            };

            var policy = GetRetryPolicy(resourceId, method, fullUri);

            var httpResponse = await policy
                               .ExecuteAsync(() => _httpClient.PostAsync(
                                                 fullUri,
                                                 new StringContent(JsonConvert.SerializeObject(form),
                                                                   Encoding.UTF8,
                                                                   ApplicationJsonMediaType),
                                                 this.cancellationToken));

            var content = await httpResponse.Content.ReadAsStringAsync();

            OnNavigated(new NavigatedEventArgs(resourceId, method, fullUri, httpResponse.StatusCode.ToString(), content));

            switch (httpResponse.StatusCode)
            {
            case HttpStatusCode.OK:
            {
                var clientResponse = JsonConvert.DeserializeObject <UploadSession>(content);

                var result = new CreateSessionResult
                {
                    StatusCode = httpResponse.StatusCode,
                    FullUri    = fullUri,
                    Session    = clientResponse
                };

                return(result);
            }

            case HttpStatusCode.BadRequest:
            {
                return(new CreateSessionResult
                    {
                        StatusCode = httpResponse.StatusCode,
                        FullUri = fullUri,
                        Error = content
                    });
            }

            default:
            {
                return(new CreateSessionResult
                    {
                        StatusCode = httpResponse.StatusCode,
                        Error = content,
                        FullUri = fullUri
                    });
            }
            }
        }