void LogoutFlow(ServerTester tester, string clientId, SeleniumTester seleniumTester)
        {
            var logoutUrl = new Uri(tester.PayTester.ServerUri,
                                    $"connect/logout?response_type=token&client_id={clientId}");

            seleniumTester.Driver.Navigate().GoToUrl(logoutUrl);
            seleniumTester.GoToHome();
            Assert.Throws <NoSuchElementException>(() => seleniumTester.Driver.FindElement(By.Id("Logout")));
        }
Пример #2
0
        public static SeleniumTester Create([CallerMemberNameAttribute] string scope = null)
        {
            var server = ServerTester.Create(scope);

            return(new SeleniumTester()
            {
                Server = server
            });
        }
Пример #3
0
        public void CanHaveLTCOnlyStore()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("LTC");

                // First we try payment with a merchant having only BTC
                var invoice = user.BitPay.CreateInvoice(new Invoice()
                {
                    Price             = 500,
                    Currency          = "USD",
                    PosData           = "posData",
                    OrderId           = "orderId",
                    ItemDesc          = "Some description",
                    FullNotifications = true
                }, Facade.Merchant);

                Assert.Single(invoice.CryptoInfo);
                Assert.Equal("LTC", invoice.CryptoInfo[0].CryptoCode);
                var cashCow        = tester.LTCExplorerNode;
                var invoiceAddress = BitcoinAddress.Create(invoice.CryptoInfo[0].Address, cashCow.Network);
                var firstPayment   = Money.Coins(0.1m);
                cashCow.SendToAddress(invoiceAddress, firstPayment);
                Eventually(() =>
                {
                    invoice = user.BitPay.GetInvoice(invoice.Id);
                    Assert.Equal(firstPayment, invoice.CryptoInfo[0].Paid);
                });

                Assert.Single(invoice.CryptoInfo); // Only BTC should be presented

                var controller = tester.PayTester.GetController <InvoiceController>(null);
                var checkout   = (Models.InvoicingModels.PaymentModel)((JsonResult)controller.GetStatus(invoice.Id, null).GetAwaiter().GetResult()).Value;
                Assert.Single(checkout.AvailableCryptos);
                Assert.Equal("LTC", checkout.CryptoCode);

                //////////////////////

                // Despite it is called BitcoinAddress it should be LTC because BTC is not available
                Assert.Null(invoice.BitcoinAddress);
                Assert.NotEqual(1.0, invoice.Rate);
                Assert.NotEqual(invoice.BtcDue, invoice.CryptoInfo[0].Due); // Should be BTC rate
                cashCow.SendToAddress(invoiceAddress, invoice.CryptoInfo[0].Due);

                Eventually(() =>
                {
                    invoice = user.BitPay.GetInvoice(invoice.Id);
                    Assert.Equal("paid", invoice.Status);
                    checkout = (Models.InvoicingModels.PaymentModel)((JsonResult)controller.GetStatus(invoice.Id, null).GetAwaiter().GetResult()).Value;
                    Assert.Equal("paid", checkout.Status);
                });
            }
        }
Пример #4
0
        public void CanRBFPayment()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var user = tester.NewAccount();
                user.GrantAccess();
                var invoice = user.BitPay.CreateInvoice(new Invoice()
                {
                    Price    = 5000.0,
                    Currency = "USD"
                }, Facade.Merchant);

                var payment1 = Money.Coins(0.04m);
                var payment2 = Money.Coins(0.08m);
                var tx1      = new uint256(tester.ExplorerNode.SendCommand("sendtoaddress", new object[]
                {
                    invoice.BitcoinAddress.ToString(),
                    payment1.ToString(),
                    null,  //comment
                    null,  //comment_to
                    false, //subtractfeefromamount
                    true,  //replaceable
                }).ResultString);
                var invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, tester.Network);

                Eventually(() =>
                {
                    tester.SimulateCallback(invoiceAddress);
                    invoice = user.BitPay.GetInvoice(invoice.Id);
                    Assert.Equal(payment1, invoice.BtcPaid);
                    invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, tester.Network);
                });

                var tx = tester.ExplorerNode.GetRawTransaction(new uint256(tx1));
                foreach (var input in tx.Inputs)
                {
                    input.ScriptSig = Script.Empty; //Strip signatures
                }
                var change = tx.Outputs.First(o => o.Value != payment1);
                var output = tx.Outputs.First(o => o.Value == payment1);
                output.Value        = payment2;
                output.ScriptPubKey = invoiceAddress.ScriptPubKey;
                change.Value       -= (payment2 - payment1) * 2; //Add more fees
                var replaced = tester.ExplorerNode.SignRawTransaction(tx);
                tester.ExplorerNode.SendRawTransaction(replaced);
                var test = tester.ExplorerClient.Sync(user.DerivationScheme, null);
                Eventually(() =>
                {
                    tester.SimulateCallback(invoiceAddress);
                    invoice = user.BitPay.GetInvoice(invoice.Id);
                    Assert.Equal(payment2, invoice.BtcPaid);
                });
            }
        }
Пример #5
0
        public async Task ElementsAssetsAreHandledCorrectly()
        {
            using (var tester = ServerTester.Create())
            {
                tester.ActivateLBTC();
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("LBTC");
                user.RegisterDerivationScheme("USDT");

                //no tether on our regtest, lets create it and set it
                var tether           = tester.NetworkProvider.GetNetwork <ElementsBTCPayNetwork>("USDT");
                var lbtc             = tester.NetworkProvider.GetNetwork <ElementsBTCPayNetwork>("LBTC");
                var issueAssetResult = await tester.LBTCExplorerNode.SendCommandAsync("issueasset", 100000, 0);

                tether.AssetId = uint256.Parse(issueAssetResult.Result["asset"].ToString());
                ((ElementsBTCPayNetwork)tester.PayTester.GetService <BTCPayWalletProvider>().GetWallet("USDT").Network)
                .AssetId = tether.AssetId;
                Logs.Tester.LogInformation($"Asset is {tether.AssetId}");
                Assert.Equal(tether.AssetId, tester.NetworkProvider.GetNetwork <ElementsBTCPayNetwork>("USDT").AssetId);
                Assert.Equal(tether.AssetId, ((ElementsBTCPayNetwork)tester.PayTester.GetService <BTCPayWalletProvider>().GetWallet("USDT").Network).AssetId);
                //test: register 2 assets on the same elements network and make sure paying an invoice on one does not affect the other in any way
                var invoice = await user.BitPay.CreateInvoiceAsync(new Invoice(0.1m, "BTC"));

                Assert.Equal(2, invoice.SupportedTransactionCurrencies.Count);
                var ci = invoice.CryptoInfo.Single(info => info.CryptoCode.Equals("LBTC"));
                //1 lbtc = 1 btc
                Assert.Equal(1, ci.Rate);
                var star = await tester.LBTCExplorerNode.SendCommandAsync("sendtoaddress", ci.Address, ci.Due, "", "", false, true,
                                                                          1, "UNSET", lbtc.AssetId);

                TestUtils.Eventually(() =>
                {
                    var localInvoice = user.BitPay.GetInvoice(invoice.Id, Facade.Merchant);
                    Assert.Equal("paid", localInvoice.Status);
                    Assert.Single(localInvoice.CryptoInfo.Single(info => info.CryptoCode.Equals("LBTC")).Payments);
                });

                invoice = await user.BitPay.CreateInvoiceAsync(new Invoice(0.1m, "BTC"));

                ci = invoice.CryptoInfo.Single(info => info.CryptoCode.Equals("USDT"));
                Assert.Equal(2, invoice.SupportedTransactionCurrencies.Count);
                star = await tester.LBTCExplorerNode.SendCommandAsync("sendtoaddress", ci.Address, ci.Due, "", "", false, true,
                                                                      1, "UNSET", tether.AssetId);

                TestUtils.Eventually(() =>
                {
                    var localInvoice = user.BitPay.GetInvoice(invoice.Id, Facade.Merchant);
                    Assert.Equal("paid", localInvoice.Status);
                    Assert.Single(localInvoice.CryptoInfo.Single(info => info.CryptoCode.Equals("USDT", StringComparison.InvariantCultureIgnoreCase)).Payments);
                });
            }
        }
Пример #6
0
        public async Task CanCreateViewUpdateAndDeletePaymentRequest()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");

                var user2 = tester.NewAccount();
                user2.GrantAccess();

                var paymentRequestController      = user.GetController <PaymentRequestController>();
                var guestpaymentRequestController = user2.GetController <PaymentRequestController>();

                var request = new UpdatePaymentRequestViewModel()
                {
                    Title       = "original juice",
                    Currency    = "BTC",
                    Amount      = 1,
                    StoreId     = user.StoreId,
                    Description = "description"
                };
                var id = (Assert
                          .IsType <RedirectToActionResult>(paymentRequestController.EditPaymentRequest(null, request).Result).RouteValues.Values.First().ToString());



                //permission guard for guests editing
                Assert
                .IsType <NotFoundResult>(guestpaymentRequestController.EditPaymentRequest(id).Result);

                request.Title = "update";
                Assert.IsType <RedirectToActionResult>(paymentRequestController.EditPaymentRequest(id, request).Result);

                Assert.Equal(request.Title, Assert.IsType <ViewPaymentRequestViewModel>(Assert.IsType <ViewResult>(paymentRequestController.ViewPaymentRequest(id).Result).Model).Title);

                Assert.False(string.IsNullOrEmpty(id));

                Assert.IsType <ViewPaymentRequestViewModel>(Assert
                                                            .IsType <ViewResult>(paymentRequestController.ViewPaymentRequest(id).Result).Model);

                //Delete

                Assert.IsType <ConfirmModel>(Assert
                                             .IsType <ViewResult>(paymentRequestController.RemovePaymentRequestPrompt(id).Result).Model);


                Assert.IsType <RedirectToActionResult>(paymentRequestController.RemovePaymentRequest(id).Result);

                Assert
                .IsType <NotFoundResult>(paymentRequestController.ViewPaymentRequest(id).Result);
            }
        }
Пример #7
0
        public async Task CanCancelPaymentWhenPossible()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");

                var paymentRequestController = user.GetController <PaymentRequestController>();


                Assert.IsType <NotFoundResult>(await
                                               paymentRequestController.CancelUnpaidPendingInvoice(Guid.NewGuid().ToString(), false));


                var request = new UpdatePaymentRequestViewModel()
                {
                    Title       = "original juice",
                    Currency    = "BTC",
                    Amount      = 1,
                    StoreId     = user.StoreId,
                    Description = "description"
                };
                var response = Assert
                               .IsType <RedirectToActionResult>(paymentRequestController.EditPaymentRequest(null, request).Result)
                               .RouteValues.First();

                var paymentRequestId = response.Value.ToString();

                var invoiceId = Assert
                                .IsType <OkObjectResult>(await paymentRequestController.PayPaymentRequest(paymentRequestId, false)).Value
                                .ToString();

                var actionResult = Assert
                                   .IsType <RedirectToActionResult>(await paymentRequestController.PayPaymentRequest(response.Value.ToString()));

                Assert.Equal("Checkout", actionResult.ActionName);
                Assert.Equal("Invoice", actionResult.ControllerName);
                Assert.Contains(actionResult.RouteValues, pair => pair.Key == "Id" && pair.Value.ToString() == invoiceId);

                var invoice = user.BitPay.GetInvoice(invoiceId, Facade.Merchant);
                Assert.Equal(InvoiceState.ToString(InvoiceStatus.New), invoice.Status);
                Assert.IsType <OkObjectResult>(await
                                               paymentRequestController.CancelUnpaidPendingInvoice(paymentRequestId, false));

                invoice = user.BitPay.GetInvoice(invoiceId, Facade.Merchant);
                Assert.Equal(InvoiceState.ToString(InvoiceStatus.Invalid), invoice.Status);


                Assert.IsType <BadRequestObjectResult>(await
                                                       paymentRequestController.CancelUnpaidPendingInvoice(paymentRequestId, false));
            }
        }
Пример #8
0
        public void CanRBFPayment()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");
                var invoice = user.BitPay.CreateInvoice(new Invoice()
                {
                    Price    = 5000.0,
                    Currency = "USD"
                }, Facade.Merchant);
                var payment1 = invoice.BtcDue + Money.Coins(0.0001m);
                var payment2 = invoice.BtcDue;
                var tx1      = new uint256(tester.ExplorerNode.SendCommand("sendtoaddress", new object[]
                {
                    invoice.BitcoinAddress,
                    payment1.ToString(),
                    null,  //comment
                    null,  //comment_to
                    false, //subtractfeefromamount
                    true,  //replaceable
                }).ResultString);
                var invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, user.SupportedNetwork.NBitcoinNetwork);

                Eventually(() =>
                {
                    invoice = user.BitPay.GetInvoice(invoice.Id);
                    Assert.Equal(payment1, invoice.BtcPaid);
                    Assert.Equal("paid", invoice.Status);
                    Assert.Equal("paidOver", invoice.ExceptionStatus.ToString());
                    invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, user.SupportedNetwork.NBitcoinNetwork);
                });

                var tx = tester.ExplorerNode.GetRawTransaction(new uint256(tx1));
                foreach (var input in tx.Inputs)
                {
                    input.ScriptSig = Script.Empty; //Strip signatures
                }
                var output = tx.Outputs.First(o => o.Value == payment1);
                output.Value        = payment2;
                output.ScriptPubKey = invoiceAddress.ScriptPubKey;
                var replaced = tester.ExplorerNode.SignRawTransaction(tx);
                tester.ExplorerNode.SendRawTransaction(replaced);
                var test = tester.ExplorerClient.GetUTXOs(user.DerivationScheme, null);
                Eventually(() =>
                {
                    invoice = user.BitPay.GetInvoice(invoice.Id);
                    Assert.Equal(payment2, invoice.BtcPaid);
                    Assert.Equal("False", invoice.ExceptionStatus.ToString());
                });
            }
        }
Пример #9
0
 public void TestAccessBitpayAPI()
 {
     using (var tester = ServerTester.Create())
     {
         tester.Start();
         var user = tester.NewAccount();
         Assert.False(user.BitPay.TestAccess(Facade.Merchant));
         user.GrantAccess();
         Assert.True(user.BitPay.TestAccess(Facade.Merchant));
     }
 }
Пример #10
0
        public async Task StoresControllerTests()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                await user.MakeAdmin();

                var client = await user.CreateClient(Policies.Unrestricted);

                //create store
                var newStore = await client.CreateStore(new CreateStoreRequest()
                {
                    Name = "A"
                });

                //list stores
                var stores = await client.GetStores();

                var storeIds   = stores.Select(data => data.Id);
                var storeNames = stores.Select(data => data.Name);
                Assert.NotNull(stores);
                Assert.Equal(2, stores.Count());
                Assert.Contains(newStore.Id, storeIds);
                Assert.Contains(user.StoreId, storeIds);

                //get store
                var store = await client.GetStore(user.StoreId);

                Assert.Equal(user.StoreId, store.Id);
                Assert.Contains(store.Name, storeNames);

                //remove store
                await client.RemoveStore(newStore.Id);
                await AssertHttpError(403, async() =>
                {
                    await client.GetStore(newStore.Id);
                });

                Assert.Single(await client.GetStores());


                newStore = await client.CreateStore(new CreateStoreRequest()
                {
                    Name = "A"
                });

                var scopedClient = await user.CreateClient(Permission.Create(Policies.CanViewStoreSettings, user.StoreId).ToString());

                Assert.Single(await scopedClient.GetStores());
            }
        }
Пример #11
0
        public void CanPayUsingBIP70()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");
                var invoice = user.BitPay.CreateInvoice(new Invoice()
                {
                    Buyer = new Buyer()
                    {
                        email = "*****@*****.**"
                    },
                    Price    = 5000.0,
                    Currency = "USD",
                    PosData  = "posData",
                    OrderId  = "orderId",
                    //RedirectURL = redirect + "redirect",
                    //NotificationURL = CallbackUri + "/notification",
                    ItemDesc          = "Some description",
                    FullNotifications = true
                }, Facade.Merchant);

                Assert.False(invoice.Refundable);

                var url     = new BitcoinUrlBuilder(invoice.PaymentUrls.BIP72);
                var request = url.GetPaymentRequest();
                var payment = request.CreatePayment();

                Transaction tx = new Transaction();
                tx.Outputs.AddRange(request.Details.Outputs.Select(o => new TxOut(o.Amount, o.Script)));
                var cashCow = tester.ExplorerNode;
                tx = cashCow.FundRawTransaction(tx).Transaction;
                tx = cashCow.SignRawTransaction(tx);

                payment.Transactions.Add(tx);

                payment.RefundTo.Add(new PaymentOutput(Money.Coins(1.0m), new Key().ScriptPubKey));
                var ack = payment.SubmitPayment();
                Assert.NotNull(ack);

                Eventually(() =>
                {
                    var localInvoice = user.BitPay.GetInvoice(invoice.Id, Facade.Merchant);
                    Assert.Equal("paid", localInvoice.Status);
                    Assert.True(localInvoice.Refundable);
                });
            }
        }
Пример #12
0
        public async Task HealthControllerTests()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var unauthClient = new BTCPayServerClient(tester.PayTester.ServerUri);

                var apiHealthData = await unauthClient.GetHealth();

                Assert.NotNull(apiHealthData);
                Assert.True(apiHealthData.Synchronized);
            }
        }
Пример #13
0
        public async Task CanUsePoSApp1()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");
                var apps = user.GetController <AppsController>();
                var vm   = Assert.IsType <CreateAppViewModel>(Assert.IsType <ViewResult>(apps.CreateApp().Result).Model);
                vm.Name            = "test";
                vm.SelectedAppType = AppType.PointOfSale.ToString();
                Assert.IsType <RedirectToActionResult>(apps.CreateApp(vm).Result);
                var appId = Assert.IsType <ListAppsViewModel>(Assert.IsType <ViewResult>(apps.ListApps().Result).Model)
                            .Apps[0].Id;
                var vmpos = Assert.IsType <UpdatePointOfSaleViewModel>(Assert
                                                                       .IsType <ViewResult>(apps.UpdatePointOfSale(appId).Result).Model);
                vmpos.Template = @"
apple:
  price: 5.0
  title: good apple
  disabled: true
orange:
  price: 10.0
donation:
  price: 1.02
  custom: true
";
                Assert.IsType <RedirectToActionResult>(apps.UpdatePointOfSale(appId, vmpos).Result);
                vmpos = Assert.IsType <UpdatePointOfSaleViewModel>(Assert
                                                                   .IsType <ViewResult>(apps.UpdatePointOfSale(appId).Result).Model);
                var publicApps = user.GetController <AppsPublicController>();
                var vmview     =
                    Assert.IsType <ViewPointOfSaleViewModel>(Assert
                                                             .IsType <ViewResult>(publicApps.ViewPointOfSale(appId, PosViewType.Cart).Result).Model);

                // apple shouldn't be available since we it's set to "disabled: true" above
                Assert.Equal(2, vmview.Items.Length);
                Assert.Equal("orange", vmview.Items[0].Title);
                Assert.Equal("donation", vmview.Items[1].Title);
                // orange is available
                Assert.IsType <RedirectToActionResult>(publicApps
                                                       .ViewPointOfSale(appId, PosViewType.Cart, 0, null, null, null, null, "orange").Result);
                // apple is not found
                Assert.IsType <NotFoundResult>(publicApps
                                               .ViewPointOfSale(appId, PosViewType.Cart, 0, null, null, null, null, "apple").Result);
            }
        }
Пример #14
0
        public async Task OnlyShowSupportedWallets()
        {
            using (var tester = ServerTester.Create())
            {
                tester.ActivateLBTC();
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("LBTC");
                user.RegisterDerivationScheme("BTC");
                user.RegisterDerivationScheme("USDT");

                Assert.Equal(3, Assert.IsType <ListWalletsViewModel>(Assert.IsType <ViewResult>(await user.GetController <WalletsController>().ListWallets()).Model).Wallets.Count);
            }
        }
Пример #15
0
        public void CantPairTwiceWithSamePubkey()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var acc = tester.NewAccount();
                acc.Register();
                var store       = acc.CreateStore();
                var pairingCode = acc.BitPay.RequestClientAuthorization("test", Facade.Merchant);
                Assert.IsType <RedirectToActionResult>(store.Pair(pairingCode.ToString(), acc.StoreId).GetAwaiter().GetResult());

                pairingCode = acc.BitPay.RequestClientAuthorization("test1", Facade.Merchant);
                var store2 = acc.CreateStore();
                store2.Pair(pairingCode.ToString(), store2.CreatedStoreId).GetAwaiter().GetResult();
                Assert.Contains(nameof(PairingResult.ReusedKey), store2.StatusMessage, StringComparison.CurrentCultureIgnoreCase);
            }
        }
Пример #16
0
        public async Task SpecificCanModifyStoreCantCreateNewStore()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var acc = tester.NewAccount();
                await acc.GrantAccessAsync();

                var unrestricted = await acc.CreateClient();

                var response = await unrestricted.CreateStore(new CreateStoreRequest()
                {
                    Name = "mystore"
                });

                var apiKey     = (await unrestricted.CreateAPIKey(new CreateApiKeyRequest()
                {
                    Permissions = new[] { Permission.Create("btcpay.store.canmodifystoresettings", response.Id) }
                })).ApiKey;
                var restricted = new BTCPayServerClient(unrestricted.Host, apiKey);

                // Unscoped permission should be required for create store
                await this.AssertHttpError(403, async() => await restricted.CreateStore(new CreateStoreRequest()
                {
                    Name = "store2"
                }));

                // Unrestricted should work fine
                await unrestricted.CreateStore(new CreateStoreRequest()
                {
                    Name = "store2"
                });

                // Restricted but unscoped should work fine
                apiKey     = (await unrestricted.CreateAPIKey(new CreateApiKeyRequest()
                {
                    Permissions = new[] { Permission.Create("btcpay.store.canmodifystoresettings") }
                })).ApiKey;
                restricted = new BTCPayServerClient(unrestricted.Host, apiKey);
                await restricted.CreateStore(new CreateStoreRequest()
                {
                    Name = "store2"
                });
            }
        }
        public async Task CanUseNonInteractiveFlows()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();

                var user = tester.NewAccount();
                user.GrantAccess();
                var token = await RegisterPasswordClientAndGetAccessToken(user, null, tester);
                await TestApiAgainstAccessToken(token, tester, user);

                token = await RegisterPasswordClientAndGetAccessToken(user, "secret", tester);
                await TestApiAgainstAccessToken(token, tester, user);

                token = await RegisterClientCredentialsFlowAndGetAccessToken(user, "secret", tester);
                await TestApiAgainstAccessToken(token, tester, user);
            }
        }
Пример #18
0
        private static async Task <string> GenerateAPIKey(ServerTester tester, TestAccount user)
        {
            var manageController = tester.PayTester.GetController <ManageController>(user.UserId, user.StoreId, user.IsAdmin);
            var x = Assert.IsType <RedirectToActionResult>(await manageController.AddApiKey(
                                                               new ManageController.AddApiKeyViewModel()
            {
                ServerManagementPermission = true,
                StoreManagementPermission  = true,
                StoreMode = ManageController.AddApiKeyViewModel.ApiKeyStoreMode.AllStores
            }));
            var statusMessage = manageController.TempData.GetStatusMessageModel();

            Assert.NotNull(statusMessage);
            var apiKey = statusMessage.Html.Substring(statusMessage.Html.IndexOf("<code>") + 6);

            apiKey = apiKey.Substring(0, apiKey.IndexOf("</code>"));
            return(apiKey);
        }
        public async Task CanGetOpenIdConfiguration()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                using (var response =
                           await tester.PayTester.HttpClient.GetAsync("/.well-known/openid-configuration"))
                {
                    using (var streamToReadFrom = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        var json = await streamToReadFrom.ReadToEndAsync();

                        Assert.NotNull(json);
                        JObject.Parse(json); // Should do more tests but good enough
                    }
                }
            }
        }
        public async Task CanGetOpenIdConfiguration()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                using (var response =
                           await tester.PayTester.HttpClient.GetAsync("/.well-known/openid-configuration"))
                {
                    using (var streamToReadFrom = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        var json = await streamToReadFrom.ReadToEndAsync();

                        Assert.NotNull(json);
                        var configuration = OpenIdConnectConfiguration.Create(json);
                        Assert.NotNull(configuration);
                    }
                }
            }
        }
        private static async Task <string> RegisterPasswordClientAndGetAccessToken(TestAccount user, string secret,
                                                                                   ServerTester tester)
        {
            var id           = Guid.NewGuid().ToString();
            var openIdClient = await user.RegisterOpenIdClient(
                new OpenIddictApplicationDescriptor()
            {
                ClientId    = id,
                DisplayName = id,
                Permissions = { OpenIddictConstants.Permissions.GrantTypes.Password }
            }, secret);


            var httpClient = tester.PayTester.HttpClient;

            var httpRequest = new HttpRequestMessage(HttpMethod.Post,
                                                     new Uri(tester.PayTester.ServerUri, "/connect/token"))
            {
                Content = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("grant_type", OpenIddictConstants.GrantTypes.Password),
                    new KeyValuePair <string, string>("username", user.RegisterDetails.Email),
                    new KeyValuePair <string, string>("password", user.RegisterDetails.Password),
                    new KeyValuePair <string, string>("client_id", openIdClient.ClientId),
                    new KeyValuePair <string, string>("client_secret", secret),
                    new KeyValuePair <string, string>("scope", "server_management store_management")
                })
            };


            var response = await httpClient.SendAsync(httpRequest);

            Assert.True(response.IsSuccessStatusCode);

            string content = await response.Content.ReadAsStringAsync();

            var result = System.Text.Json.JsonSerializer.Deserialize <OpenIddictResponse>(content);

            Assert.NotEmpty(result.AccessToken);
            Assert.Null(result.Error);
            return(result.AccessToken);
        }
        public async void CannotUseChangellyApiWithoutChangellyPaymentMethodSet()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                var changellyController =
                    tester.PayTester.GetController <ChangellyController>(user.UserId, user.StoreId);
                changellyController.IsTest = true;

                //test non existing payment method
                Assert.IsType <BitpayErrorModel>(Assert
                                                 .IsType <BadRequestObjectResult>(await changellyController.GetCurrencyList(user.StoreId))
                                                 .Value);

                var updateModel      = CreateDefaultChangellyParams(false);
                var storesController = tester.PayTester.GetController <StoresController>(user.UserId, user.StoreId);
                //set payment method but disabled


                Assert.Equal("UpdateStore", Assert.IsType <RedirectToActionResult>(
                                 await storesController.UpdateChangellySettings(user.StoreId, updateModel, "save")).ActionName);


                Assert.IsType <BitpayErrorModel>(Assert
                                                 .IsType <BadRequestObjectResult>(await changellyController.GetCurrencyList(user.StoreId))
                                                 .Value);

                updateModel.Enabled = true;
                //test with enabled method

                Assert.Equal("UpdateStore", Assert.IsType <RedirectToActionResult>(
                                 await storesController.UpdateChangellySettings(user.StoreId, updateModel, "save")).ActionName);


                Assert.IsNotType <BitpayErrorModel>(Assert
                                                    .IsType <OkObjectResult>(await changellyController.GetCurrencyList(user.StoreId))
                                                    .Value);
            }
        }
        public async Task GetRedirectedToLoginPathOnChallenge()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var client = tester.PayTester.HttpClient;
                //Wallets endpoint is protected
                var response = await client.GetAsync("wallets");

                var urlPath = response.RequestMessage.RequestUri.ToString()
                              .Replace(tester.PayTester.ServerUri.ToString(), "");
                //Cookie Challenge redirects you to login page
                Assert.StartsWith("Account/Login", urlPath, StringComparison.InvariantCultureIgnoreCase);

                var queryString = response.RequestMessage.RequestUri.ParseQueryString();

                Assert.NotNull(queryString["ReturnUrl"]);
                Assert.Equal("/wallets", queryString["ReturnUrl"]);
            }
        }
Пример #24
0
        public void CanTweakRate()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var user = tester.NewAccount();
                user.GrantAccess();
                user.RegisterDerivationScheme("BTC");

                // First we try payment with a merchant having only BTC
                var invoice1 = user.BitPay.CreateInvoice(new Invoice()
                {
                    Price             = 5000.0,
                    Currency          = "USD",
                    PosData           = "posData",
                    OrderId           = "orderId",
                    ItemDesc          = "Some description",
                    FullNotifications = true
                }, Facade.Merchant);


                var storeController = tester.PayTester.GetController <StoresController>(user.UserId);
                var vm = (StoreViewModel)((ViewResult)storeController.UpdateStore(user.StoreId).Result).Model;
                Assert.Equal(1.0, vm.RateMultiplier);
                vm.RateMultiplier = 0.5;
                storeController.UpdateStore(user.StoreId, vm).Wait();


                var invoice2 = user.BitPay.CreateInvoice(new Invoice()
                {
                    Price             = 5000.0,
                    Currency          = "USD",
                    PosData           = "posData",
                    OrderId           = "orderId",
                    ItemDesc          = "Some description",
                    FullNotifications = true
                }, Facade.Merchant);

                Assert.True(invoice2.BtcPrice.Almost(invoice1.BtcPrice * 2, 0.00001m));
            }
        }
        public async void CanSetChangellyPaymentMethod()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                var controller = tester.PayTester.GetController <StoresController>(user.UserId, user.StoreId);


                var storeBlob = controller.StoreData.GetStoreBlob();
                Assert.Null(storeBlob.ChangellySettings);

                var updateModel = new UpdateChangellySettingsViewModel()
                {
                    ApiSecret           = "secret",
                    ApiKey              = "key",
                    ApiUrl              = "http://gozo.com",
                    ChangellyMerchantId = "aaa",
                };

                Assert.Equal("UpdateStore", Assert.IsType <RedirectToActionResult>(
                                 await controller.UpdateChangellySettings(user.StoreId, updateModel, "save")).ActionName);

                var store = await tester.PayTester.StoreRepository.FindStore(user.StoreId);

                storeBlob = controller.StoreData.GetStoreBlob();
                Assert.NotNull(storeBlob.ChangellySettings);
                Assert.NotNull(storeBlob.ChangellySettings);
                Assert.IsType <ChangellySettings>(storeBlob.ChangellySettings);
                Assert.Equal(storeBlob.ChangellySettings.ApiKey, updateModel.ApiKey);
                Assert.Equal(storeBlob.ChangellySettings.ApiSecret,
                             updateModel.ApiSecret);
                Assert.Equal(storeBlob.ChangellySettings.ApiUrl, updateModel.ApiUrl);
                Assert.Equal(storeBlob.ChangellySettings.ChangellyMerchantId,
                             updateModel.ChangellyMerchantId);
            }
        }
Пример #26
0
        async Task CanSendLightningPaymentCore(ServerTester tester, TestAccount user)
        {
            await Task.Delay(TimeSpan.FromSeconds(RandomUtils.GetUInt32() % 5));

            var invoice = await user.BitPay.CreateInvoiceAsync(new Invoice()
            {
                Price    = 0.01,
                Currency = "USD",
                PosData  = "posData",
                OrderId  = "orderId",
                ItemDesc = "Some description"
            });

            await tester.SendLightningPaymentAsync(invoice);

            await EventuallyAsync(async() =>
            {
                var localInvoice = await user.BitPay.GetInvoiceAsync(invoice.Id);
                Assert.Equal("complete", localInvoice.Status);
                Assert.Equal("False", localInvoice.ExceptionStatus.ToString());
            });
        }
Пример #27
0
        public async Task CanUseAzureBlobStorage()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var user = tester.NewAccount();
                user.GrantAccess();
                var controller = tester.PayTester.GetController <ServerController>(user.UserId, user.StoreId);
                var azureBlobStorageConfiguration = Assert.IsType <AzureBlobStorageConfiguration>(Assert
                                                                                                  .IsType <ViewResult>(await controller.StorageProvider(StorageProvider.AzureBlobStorage.ToString()))
                                                                                                  .Model);

                azureBlobStorageConfiguration.ConnectionString = GetFromSecrets("AzureBlobStorageConnectionString");
                azureBlobStorageConfiguration.ContainerName    = "testscontainer";
                Assert.IsType <ViewResult>(
                    await controller.EditAzureBlobStorageStorageProvider(azureBlobStorageConfiguration));


                var shouldBeRedirectingToAzureStorageConfigPage =
                    Assert.IsType <RedirectToActionResult>(await controller.Storage());
                Assert.Equal(nameof(StorageProvider), shouldBeRedirectingToAzureStorageConfigPage.ActionName);
                Assert.Equal(StorageProvider.AzureBlobStorage,
                             shouldBeRedirectingToAzureStorageConfigPage.RouteValues["provider"]);

                //seems like azure config worked, let's see if the conn string was actually saved

                Assert.Equal(azureBlobStorageConfiguration.ConnectionString, Assert
                             .IsType <AzureBlobStorageConfiguration>(Assert
                                                                     .IsType <ViewResult>(
                                                                         await controller.StorageProvider(StorageProvider.AzureBlobStorage.ToString()))
                                                                     .Model).ConnectionString);



                await CanUploadRemoveFiles(controller);
            }
        }
Пример #28
0
        public async Task CanUseTheDelayedBroadcaster()
        {
            using (var tester = ServerTester.Create())
            {
                await tester.StartAsync();

                var network     = tester.NetworkProvider.GetNetwork <BTCPayNetwork>("BTC");
                var broadcaster = tester.PayTester.GetService <DelayedTransactionBroadcaster>();
                await broadcaster.Schedule(DateTimeOffset.UtcNow + TimeSpan.FromDays(500), RandomTransaction(network), network);

                var tx = RandomTransaction(network);
                await broadcaster.Schedule(DateTimeOffset.UtcNow - TimeSpan.FromDays(5), tx, network);

                // twice on same tx should be noop
                await broadcaster.Schedule(DateTimeOffset.UtcNow - TimeSpan.FromDays(5), tx, network);

                broadcaster.Disable();
                Assert.Equal(0, await broadcaster.ProcessAll());
                broadcaster.Enable();
                Assert.Equal(1, await broadcaster.ProcessAll());
                Assert.Equal(0, await broadcaster.ProcessAll());
            }
        }
Пример #29
0
        public void CanUseServerInitiatedPairingCode()
        {
            using (var tester = ServerTester.Create())
            {
                tester.Start();
                var acc = tester.NewAccount();
                acc.Register();
                acc.CreateStore();

                var controller = tester.PayTester.GetController <StoresController>(acc.UserId);
                var token      = (RedirectToActionResult)controller.CreateToken(acc.StoreId, new Models.StoreViewModels.CreateTokenViewModel()
                {
                    Facade    = Facade.Merchant.ToString(),
                    Label     = "bla",
                    PublicKey = null
                }).GetAwaiter().GetResult();

                var pairingCode = (string)token.RouteValues["pairingCode"];

                acc.BitPay.AuthorizeClient(new PairingCode(pairingCode)).GetAwaiter().GetResult();
                Assert.True(acc.BitPay.TestAccess(Facade.Merchant));
            }
        }
        async Task TestApiAgainstAccessToken(string accessToken, ServerTester tester, TestAccount testAccount)
        {
            var resultUser =
                await TestApiAgainstAccessToken <string>(accessToken, "api/test/me/id",
                                                         tester.PayTester.HttpClient);

            Assert.Equal(testAccount.UserId, resultUser);

            var secondUser = tester.NewAccount();

            secondUser.GrantAccess();

            var resultStores =
                await TestApiAgainstAccessToken <StoreData[]>(accessToken, "api/test/me/stores",
                                                              tester.PayTester.HttpClient);

            Assert.Contains(resultStores,
                            data => data.Id.Equals(testAccount.StoreId, StringComparison.InvariantCultureIgnoreCase));
            Assert.DoesNotContain(resultStores,
                                  data => data.Id.Equals(secondUser.StoreId, StringComparison.InvariantCultureIgnoreCase));

            Assert.True(await TestApiAgainstAccessToken <bool>(accessToken,
                                                               $"api/test/me/stores/{testAccount.StoreId}/can-edit",
                                                               tester.PayTester.HttpClient));


            Assert.Equal(testAccount.RegisterDetails.IsAdmin, await TestApiAgainstAccessToken <bool>(accessToken,
                                                                                                     $"api/test/me/is-admin",
                                                                                                     tester.PayTester.HttpClient));

            await Assert.ThrowsAnyAsync <HttpRequestException>(async() =>
            {
                await TestApiAgainstAccessToken <bool>(accessToken, $"api/test/me/stores/{secondUser.StoreId}/can-edit",
                                                       tester.PayTester.HttpClient);
            });
        }