diff --git a/src/CertificateAuthority.Tests/FullProjectTests/Helpers/TestsHelper.cs b/src/CertificateAuthority.Tests/CaTestHelper.cs similarity index 73% rename from src/CertificateAuthority.Tests/FullProjectTests/Helpers/TestsHelper.cs rename to src/CertificateAuthority.Tests/CaTestHelper.cs index 2897ab9d16b..d40e7a1e637 100644 --- a/src/CertificateAuthority.Tests/FullProjectTests/Helpers/TestsHelper.cs +++ b/src/CertificateAuthority.Tests/CaTestHelper.cs @@ -10,12 +10,18 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using NBitcoin; +using Stratis.Feature.PoA.Tokenless; -namespace CertificateAuthority.Tests.FullProjectTests.Helpers +namespace CertificateAuthority.Tests { - public static class TestsHelper + public static class CaTestHelper { + public const string AdminPassword = "4815162342"; public static string BaseAddress = "http://localhost:5050"; + public const string CaMnemonic = "young shoe immense usual faculty edge habit misery swarm tape viable toddler"; + public const string CaMnemonicPassword = "node"; + private static Random random = new Random(); public static string GenerateRandomString(int length = 10) @@ -29,7 +35,7 @@ public static CredentialsModel CreateAccount(TestServer server, AccountAccessFla string password = GenerateRandomString(); string passHash = DataHelper.ComputeSha256Hash(password); - var adminCredentials = new CredentialsModel(1, "4815162342"); + var adminCredentials = new CredentialsModel(Settings.AdminAccountId, AdminPassword); var accountsController = (AccountsController)server.Host.Services.GetService(typeof(AccountsController)); @@ -39,6 +45,15 @@ public static CredentialsModel CreateAccount(TestServer server, AccountAccessFla return new CredentialsModel(id, password); } + internal static void InitializeCa(TestServer server) + { + var network = new TokenlessNetwork(); + + var certificatesController = (CertificatesController)server.Host.Services.GetService(typeof(CertificatesController)); + var model = new InitializeCertificateAuthorityModel(CaMnemonic, CaMnemonicPassword, network.Consensus.CoinType, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS][0], AdminPassword); + certificatesController.InitializeCertificateAuthority(model); + } + public static IWebHostBuilder CreateWebHostBuilder([CallerMemberName] string callingMethod = null) { // Create a datafolder path for the CA settings to use diff --git a/src/CertificateAuthority.Tests/DataHelperTests.cs b/src/CertificateAuthority.Tests/DataHelperTests.cs index f203e003b3b..9425f2b08e7 100644 --- a/src/CertificateAuthority.Tests/DataHelperTests.cs +++ b/src/CertificateAuthority.Tests/DataHelperTests.cs @@ -9,7 +9,7 @@ public class DataHelperTests [Fact] public void ComputeSha256HashTests() { - Dictionary inputToHashDictionary = new Dictionary() + var inputToHashDictionary = new Dictionary() { {"65y56h456gergerg", "4e0e7b3189d7cb3a4c6b7bca5844b30d83653eef364af449c6f1e7bf224701fd" }, {"rg54g4g45g45g", "1eacd796aa227beea7112f5a8524264aec1bb7d72f6fefba9b047c3bd1173c96" }, @@ -46,7 +46,7 @@ public void GetCertificateRequestLinesSuccess_Test() [Fact] public void GetCertificateRequestLinesInvalidData_Test() { - List invalidData = new List() + var invalidData = new List() { "-----BEGIN g45g54g REQUEST----- MIIE1jQH 2IpYg1u4ox 79pteewn -----END CERTIFICATE REQUEST-----", "-----BEGIN CERTIFICATE REQUEST----- MIIE1jQH 2IpYg1u4ox 79pteewn -----END CERTIFICATE REQaaaEST-----", @@ -76,7 +76,6 @@ public AccessTestData(AccountAccessFlags a, AccountAccessFlags b, bool expectedR public bool ExpectedResult { get; set; } } - [Fact] public void IsCreatorHasGreaterOrEqualAccessTest() { diff --git a/src/CertificateAuthority.Tests/FullProjectTests/AccountsControllerTests.cs b/src/CertificateAuthority.Tests/FullProjectTests/AccountsControllerTests.cs index 5da84c4e422..c1066c7588c 100644 --- a/src/CertificateAuthority.Tests/FullProjectTests/AccountsControllerTests.cs +++ b/src/CertificateAuthority.Tests/FullProjectTests/AccountsControllerTests.cs @@ -3,7 +3,6 @@ using CertificateAuthority.Controllers; using CertificateAuthority.Database; using CertificateAuthority.Models; -using CertificateAuthority.Tests.FullProjectTests.Helpers; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.TestHost; @@ -21,34 +20,36 @@ public sealed class AccountsControllerTests public AccountsControllerTests() { - IWebHostBuilder builder = TestsHelper.CreateWebHostBuilder(); + IWebHostBuilder builder = CaTestHelper.CreateWebHostBuilder(); this.server = new TestServer(builder); - this.adminCredentials = new CredentialsModel(1, "4815162342"); + this.adminCredentials = new CredentialsModel(Settings.AdminAccountId, CaTestHelper.AdminPassword); this.accountsController = (AccountsController)this.server.Host.Services.GetService(typeof(AccountsController)); this.dataCacheLayer = (DataCacheLayer)this.server.Host.Services.GetService(typeof(DataCacheLayer)); + + CaTestHelper.InitializeCa(this.server); } [Fact] private void TestAccountsControllerMethods() { // Just admin on start. - Assert.Single(TestsHelper.GetValue>(this.accountsController.GetAllAccounts(this.adminCredentials))); + Assert.Single(CaTestHelper.GetValue>(this.accountsController.GetAllAccounts(this.adminCredentials))); AccountAccessFlags credentials1Access = AccountAccessFlags.AccessAccountInfo | AccountAccessFlags.BasicAccess | AccountAccessFlags.IssueCertificates; - CredentialsModel credentials1 = TestsHelper.CreateAccount(this.server, credentials1Access); - CredentialsModel credentials2 = TestsHelper.CreateAccount(this.server, AccountAccessFlags.DeleteAccounts); - CredentialsModel accToDelete = TestsHelper.CreateAccount(this.server); + CredentialsModel credentials1 = CaTestHelper.CreateAccount(this.server, credentials1Access); + CredentialsModel credentials2 = CaTestHelper.CreateAccount(this.server, AccountAccessFlags.DeleteAccounts); + CredentialsModel accToDelete = CaTestHelper.CreateAccount(this.server); // GetAccountInfoById { // Admin can access new user's data - AccountInfo info = TestsHelper.GetValue(this.accountsController.GetAccountInfoById(new CredentialsModelWithTargetId(credentials1.AccountId, this.adminCredentials.AccountId, this.adminCredentials.Password))); + AccountInfo info = CaTestHelper.GetValue(this.accountsController.GetAccountInfoById(new CredentialsModelWithTargetId(credentials1.AccountId, this.adminCredentials.AccountId, this.adminCredentials.Password))); Assert.Equal(credentials1Access, info.AccessInfo); Assert.Equal(this.adminCredentials.AccountId, info.CreatorId); // First user can access admin's data' - AccountInfo info2 = TestsHelper.GetValue(this.accountsController.GetAccountInfoById(new CredentialsModelWithTargetId(this.adminCredentials.AccountId, credentials1.AccountId, credentials1.Password))); + AccountInfo info2 = CaTestHelper.GetValue(this.accountsController.GetAccountInfoById(new CredentialsModelWithTargetId(this.adminCredentials.AccountId, credentials1.AccountId, credentials1.Password))); Assert.Equal(this.adminCredentials.AccountId, info2.CreatorId); Assert.Equal(Settings.AdminName, info2.Name); @@ -58,13 +59,13 @@ private void TestAccountsControllerMethods() } // GetAllAccounts - List allAccounts = TestsHelper.GetValue>(this.accountsController.GetAllAccounts(this.adminCredentials)); + List allAccounts = CaTestHelper.GetValue>(this.accountsController.GetAllAccounts(this.adminCredentials)); Assert.Equal(4, allAccounts.Count); // DeleteAccountByAccountId { this.accountsController.DeleteAccountByAccountId(new CredentialsModelWithTargetId(accToDelete.AccountId, credentials2.AccountId, credentials2.Password)); - Assert.Equal(3, TestsHelper.GetValue>(this.accountsController.GetAllAccounts(this.adminCredentials)).Count); + Assert.Equal(3, CaTestHelper.GetValue>(this.accountsController.GetAllAccounts(this.adminCredentials)).Count); IActionResult result = this.accountsController.DeleteAccountByAccountId(new CredentialsModelWithTargetId(credentials2.AccountId, credentials1.AccountId, credentials1.Password)); Assert.True(((ObjectResult)result).StatusCode == 403); @@ -74,15 +75,15 @@ private void TestAccountsControllerMethods() int newFlag = 8 + 16 + 2 + 64; this.accountsController.ChangeAccountAccessLevel(new ChangeAccountAccessLevel(newFlag, credentials1.AccountId, this.adminCredentials.AccountId, this.adminCredentials.Password)); - int newAccessInfo = (int)TestsHelper.GetValue(this.accountsController.GetAccountInfoById(new CredentialsModelWithTargetId(credentials1.AccountId, this.adminCredentials.AccountId, this.adminCredentials.Password))).AccessInfo; + int newAccessInfo = (int)CaTestHelper.GetValue(this.accountsController.GetAccountInfoById(new CredentialsModelWithTargetId(credentials1.AccountId, this.adminCredentials.AccountId, this.adminCredentials.Password))).AccessInfo; Assert.Equal(newFlag, newAccessInfo); // GetCertIdsIssuedByAccountId { int issuerId = credentials1.AccountId; - string print1 = TestsHelper.GenerateRandomString(20); - string print2 = TestsHelper.GenerateRandomString(20); + string print1 = CaTestHelper.GenerateRandomString(20); + string print2 = CaTestHelper.GenerateRandomString(20); byte[] blockSignPubKey1 = (new Key()).PubKey.ToBytes(); byte[] blockSignPubKey2 = (new Key()).PubKey.ToBytes(); byte[] txSignPubKeyHash1 = (new Key()).PubKey.Hash.ToBytes(); @@ -109,7 +110,7 @@ private void TestAccountsControllerMethods() TransactionSigningPubKeyHash = txSignPubKeyHash2 }); - List certs = TestsHelper.GetValue>(this.accountsController.GetCertificatesIssuedByAccountId(new CredentialsModelWithTargetId(issuerId, this.adminCredentials.AccountId, this.adminCredentials.Password))); + List certs = CaTestHelper.GetValue>(this.accountsController.GetCertificatesIssuedByAccountId(new CredentialsModelWithTargetId(issuerId, this.adminCredentials.AccountId, this.adminCredentials.Password))); Assert.Equal(2, certs.Count); Assert.Equal(50, certs[0].CertificateContentDer.Length); @@ -123,13 +124,13 @@ private void TestAccountsControllerMethods() [Fact] public void ChangeAccountPassword_CurrentUser_Pass() { - CredentialsModel credentials = TestsHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); + CredentialsModel credentials = CaTestHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); var model = new ChangeAccountPasswordModel(credentials.AccountId, credentials.AccountId, credentials.Password, "newpassword"); this.accountsController.ChangeAccountPassword(model); var adminCredentialsModel = new CredentialsModel(this.adminCredentials.AccountId, this.adminCredentials.Password); - List accounts = TestsHelper.GetValue>(this.accountsController.GetAllAccounts(adminCredentialsModel)); + List accounts = CaTestHelper.GetValue>(this.accountsController.GetAllAccounts(adminCredentialsModel)); AccountModel account = accounts.FirstOrDefault(a => a.Id == credentials.AccountId); Assert.True(account.VerifyPassword("newpassword")); } @@ -137,13 +138,13 @@ public void ChangeAccountPassword_CurrentUser_Pass() [Fact] public void ChangeAccountPassword_CurrentUser_WrongPassword_Fail() { - CredentialsModel credentials = TestsHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); + CredentialsModel credentials = CaTestHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); var model = new ChangeAccountPasswordModel(credentials.AccountId, credentials.AccountId, "wrongpassword", "newpassword"); this.accountsController.ChangeAccountPassword(model); var adminCredentialsModel = new CredentialsModel(this.adminCredentials.AccountId, this.adminCredentials.Password); - List accounts = TestsHelper.GetValue>(this.accountsController.GetAllAccounts(adminCredentialsModel)); + List accounts = CaTestHelper.GetValue>(this.accountsController.GetAllAccounts(adminCredentialsModel)); AccountModel account = accounts.FirstOrDefault(a => a.Id == credentials.AccountId); Assert.False(account.VerifyPassword("newpassword")); } @@ -151,13 +152,13 @@ public void ChangeAccountPassword_CurrentUser_WrongPassword_Fail() [Fact] public void ChangeAccountPassword_AdminUser_Pass() { - CredentialsModel userA_Credentials = TestsHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); + CredentialsModel userA_Credentials = CaTestHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); var changePasswordModel = new ChangeAccountPasswordModel(this.adminCredentials.AccountId, userA_Credentials.AccountId, this.adminCredentials.Password, "newpassword"); this.accountsController.ChangeAccountPassword(changePasswordModel); var adminCredentialsModel = new CredentialsModel(this.adminCredentials.AccountId, this.adminCredentials.Password); - List accounts = TestsHelper.GetValue>(this.accountsController.GetAllAccounts(adminCredentialsModel)); + List accounts = CaTestHelper.GetValue>(this.accountsController.GetAllAccounts(adminCredentialsModel)); AccountModel account = accounts.FirstOrDefault(a => a.Id == userA_Credentials.AccountId); Assert.True(account.VerifyPassword("newpassword")); } @@ -165,14 +166,14 @@ public void ChangeAccountPassword_AdminUser_Pass() [Fact] public void ChangeAccountPassword_DifferentUser_Fail() { - CredentialsModel userA_Credentials = TestsHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); - CredentialsModel userB_Credentials = TestsHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); + CredentialsModel userA_Credentials = CaTestHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); + CredentialsModel userB_Credentials = CaTestHelper.CreateAccount(this.server, AccountAccessFlags.BasicAccess); var model = new ChangeAccountPasswordModel(userA_Credentials.AccountId, userB_Credentials.AccountId, userA_Credentials.Password, "newpassword"); this.accountsController.ChangeAccountPassword(model); var adminCredentialsModel = new CredentialsModel(this.adminCredentials.AccountId, this.adminCredentials.Password); - List accounts = TestsHelper.GetValue>(this.accountsController.GetAllAccounts(adminCredentialsModel)); + List accounts = CaTestHelper.GetValue>(this.accountsController.GetAllAccounts(adminCredentialsModel)); AccountModel userB_Account = accounts.FirstOrDefault(a => a.Id == userB_Credentials.AccountId); Assert.False(userB_Account.VerifyPassword("newpassword")); Assert.True(userB_Account.VerifyPassword(userB_Credentials.Password)); diff --git a/src/CertificateAuthority.Tests/FullProjectTests/CertificateAuthorityIntegrationTests.cs b/src/CertificateAuthority.Tests/FullProjectTests/CertificateAuthorityIntegrationTests.cs index 7cd501ae902..436f619eaaa 100644 --- a/src/CertificateAuthority.Tests/FullProjectTests/CertificateAuthorityIntegrationTests.cs +++ b/src/CertificateAuthority.Tests/FullProjectTests/CertificateAuthorityIntegrationTests.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Security.Cryptography.X509Certificates; using CertificateAuthority.Models; -using CertificateAuthority.Tests.FullProjectTests.Helpers; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using NBitcoin; @@ -13,13 +12,8 @@ namespace CertificateAuthority.Tests.FullProjectTests { - public class CertificateAuthorityIntegrationTests + public sealed class CertificateAuthorityIntegrationTests { - public const int TestAccountId = 1; - public const string TestPassword = "4815162342"; - public const string CaMnemonic = "young shoe immense usual faculty edge habit misery swarm tape viable toddler"; - public const string CaMnemonicPassword = "node"; - private readonly Network network; public CertificateAuthorityIntegrationTests() @@ -30,10 +24,12 @@ public CertificateAuthorityIntegrationTests() [Fact] public void CertificateAuthorityTestServerStartsUp() { - IWebHostBuilder builder = TestsHelper.CreateWebHostBuilder(); + IWebHostBuilder builder = CaTestHelper.CreateWebHostBuilder(); var server = new TestServer(builder); - var client = new CaClient(server.BaseAddress, server.CreateClient(), TestAccountId, TestPassword); + var client = new CaClient(server.BaseAddress, server.CreateClient(), Settings.AdminAccountId, CaTestHelper.AdminPassword); + + CaTestHelper.InitializeCa(server); List response = client.GetAllCertificates(); @@ -45,12 +41,12 @@ public void CertificateAuthorityTestServerStartsUp() [Fact] public void CertificateAuthorityTestServerGetsInitialized() { - IWebHostBuilder builder = TestsHelper.CreateWebHostBuilder(); + IWebHostBuilder builder = CaTestHelper.CreateWebHostBuilder(); var server = new TestServer(builder); - var client = new CaClient(server.BaseAddress, server.CreateClient(), TestAccountId, TestPassword); + var client = new CaClient(server.BaseAddress, server.CreateClient(), Settings.AdminAccountId, CaTestHelper.AdminPassword); - Assert.True(client.InitializeCertificateAuthority(CaMnemonic, CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); server.Dispose(); } @@ -58,12 +54,12 @@ public void CertificateAuthorityTestServerGetsInitialized() [Fact] public void CertificateAuthorityCanGenerateCertificateSigningRequest() { - IWebHostBuilder builder = TestsHelper.CreateWebHostBuilder(); + IWebHostBuilder builder = CaTestHelper.CreateWebHostBuilder(); var server = new TestServer(builder); - var client = new CaClient(server.BaseAddress, server.CreateClient(), TestAccountId, TestPassword); + var client = new CaClient(server.BaseAddress, server.CreateClient(), Settings.AdminAccountId, CaTestHelper.AdminPassword); - Assert.True(client.InitializeCertificateAuthority(CaMnemonic, CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); var privateKey = new Key(); PubKey pubKey = privateKey.PubKey; @@ -85,12 +81,12 @@ public void CertificateAuthorityCanGenerateCertificateSigningRequest() [Fact] public void CertificateAuthorityCanIssueCertificate() { - IWebHostBuilder builder = TestsHelper.CreateWebHostBuilder(); + IWebHostBuilder builder = CaTestHelper.CreateWebHostBuilder(); var server = new TestServer(builder); - var client = new CaClient(server.BaseAddress, server.CreateClient(), TestAccountId, TestPassword); + var client = new CaClient(server.BaseAddress, server.CreateClient(), Settings.AdminAccountId, CaTestHelper.AdminPassword); - Assert.True(client.InitializeCertificateAuthority(CaMnemonic, CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); var privateKey = new Key(); diff --git a/src/CertificateAuthority.Tests/FullProjectTests/ControllersTests.cs b/src/CertificateAuthority.Tests/FullProjectTests/ControllersTests.cs index 3e549b71276..b004507453c 100644 --- a/src/CertificateAuthority.Tests/FullProjectTests/ControllersTests.cs +++ b/src/CertificateAuthority.Tests/FullProjectTests/ControllersTests.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using System.Threading.Tasks; using CertificateAuthority.Controllers; using CertificateAuthority.Database; using CertificateAuthority.Models; -using CertificateAuthority.Tests.FullProjectTests.Helpers; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.TestHost; @@ -22,7 +20,7 @@ namespace CertificateAuthority.Tests.FullProjectTests { - public class ControllersTests + public sealed class ControllersTests { private readonly AccountsController accountsController; private readonly CredentialsModel adminCredentials; @@ -32,28 +30,28 @@ public class ControllersTests public ControllersTests() { - IWebHostBuilder builder = TestsHelper.CreateWebHostBuilder(); + IWebHostBuilder builder = CaTestHelper.CreateWebHostBuilder(); this.server = new TestServer(builder); - this.adminCredentials = new CredentialsModel(1, "4815162342"); + this.adminCredentials = new CredentialsModel(Settings.AdminAccountId, CaTestHelper.AdminPassword); this.accountsController = (AccountsController)this.server.Host.Services.GetService(typeof(AccountsController)); this.certificatesController = (CertificatesController)this.server.Host.Services.GetService(typeof(CertificatesController)); this.dataCacheLayer = (DataCacheLayer)this.server.Host.Services.GetService(typeof(DataCacheLayer)); + + CaTestHelper.InitializeCa(this.server); } [Fact] - private async Task TestCertificatesControllerMethodsAsync() + private void TestCertificatesControllerMethods() { // Just admin on start. - Assert.Single(TestsHelper.GetValue>(this.accountsController.GetAllAccounts(this.adminCredentials))); + Assert.Single(CaTestHelper.GetValue>(this.accountsController.GetAllAccounts(this.adminCredentials))); AccountAccessFlags credentials1Access = AccountAccessFlags.AccessAccountInfo | AccountAccessFlags.BasicAccess | AccountAccessFlags.IssueCertificates | AccountAccessFlags.RevokeCertificates | AccountAccessFlags.AccessAnyCertificate; - CredentialsModel credentials1 = TestsHelper.CreateAccount(this.server, credentials1Access); - - this.certificatesController.InitializeCertificateAuthority(new CredentialsModelWithMnemonicModel("young shoe immense usual faculty edge habit misery swarm tape viable toddler", "node", 105, 63, credentials1.AccountId, credentials1.Password)); + CredentialsModel credentials1 = CaTestHelper.CreateAccount(this.server, credentials1Access); - CertificateInfoModel caCertModel = TestsHelper.GetValue(this.certificatesController.GetCaCertificate(credentials1)); + CertificateInfoModel caCertModel = CaTestHelper.GetValue(this.certificatesController.GetCaCertificate(credentials1)); var certParser = new X509CertificateParser(); @@ -96,7 +94,7 @@ private async Task TestCertificatesControllerMethodsAsync() Pkcs10CertificationRequest certificateSigningRequest = CaCertificatesManager.CreateCertificateSigningRequest(clientName, clientKey, new string[0], extensionData); // IssueCertificate_UsingRequestString - CertificateInfoModel certificate1 = TestsHelper.GetValue(this.certificatesController.IssueCertificate_UsingRequestString( + CertificateInfoModel certificate1 = CaTestHelper.GetValue(this.certificatesController.IssueCertificate_UsingRequestString( new IssueCertificateFromFileContentsModel(Convert.ToBase64String(certificateSigningRequest.GetDerEncoded()), credentials1.AccountId, credentials1.Password))); X509Certificate cert1 = certParser.ReadCertificate(certificate1.CertificateContentDer); @@ -105,7 +103,7 @@ private async Task TestCertificatesControllerMethodsAsync() Assert.Equal(clientAddress, certificate1.Address); - PubKey[] pubKeys = TestsHelper.GetValue>(this.certificatesController.GetCertificatePublicKeys()).Select(s => new PubKey(s)).ToArray(); + PubKey[] pubKeys = CaTestHelper.GetValue>(this.certificatesController.GetCertificatePublicKeys()).Select(s => new PubKey(s)).ToArray(); Assert.Single(pubKeys); Assert.Equal(blockSigningPrivateKey.PubKey, pubKeys[0]); @@ -133,47 +131,47 @@ private async Task TestCertificatesControllerMethodsAsync() Pkcs10CertificationRequest certificateSigningRequest2 = CaCertificatesManager.CreateCertificateSigningRequest(clientName, clientKey2, new string[0], extensionData); - CertificateInfoModel certificate2 = TestsHelper.GetValue(this.certificatesController.IssueCertificate_UsingRequestString( + CertificateInfoModel certificate2 = CaTestHelper.GetValue(this.certificatesController.IssueCertificate_UsingRequestString( new IssueCertificateFromFileContentsModel(System.Convert.ToBase64String(certificateSigningRequest2.GetDerEncoded()), this.adminCredentials.AccountId, this.adminCredentials.Password))); Assert.Equal(clientAddress, certificate2.Address); - PubKey[] pubKeys2 = TestsHelper.GetValue>(this.certificatesController.GetCertificatePublicKeys()).Select(s => new PubKey(s)).ToArray(); + PubKey[] pubKeys2 = CaTestHelper.GetValue>(this.certificatesController.GetCertificatePublicKeys()).Select(s => new PubKey(s)).ToArray(); Assert.Equal(2, pubKeys2.Length); Assert.Equal(blockSigningPrivateKey.PubKey, pubKeys2[1]); - Assert.Empty(TestsHelper.GetValue>(this.certificatesController.GetRevokedCertificates())); + Assert.Empty(CaTestHelper.GetValue>(this.certificatesController.GetRevokedCertificates())); // GetCertificateByThumbprint - CertificateInfoModel cert1Retrieved = TestsHelper.GetValue(this.certificatesController.GetCertificateByThumbprint( + CertificateInfoModel cert1Retrieved = CaTestHelper.GetValue(this.certificatesController.GetCertificateByThumbprint( new CredentialsModelWithThumbprintModel(certificate1.Thumbprint, this.adminCredentials.AccountId, this.adminCredentials.Password))); Assert.Equal(certificate1.Id, cert1Retrieved.Id); Assert.Equal(certificate1.IssuerAccountId, cert1Retrieved.IssuerAccountId); - string status = TestsHelper.GetValue(this.certificatesController.GetCertificateStatus(new GetCertificateStatusModel(certificate1.Thumbprint, true))); + string status = CaTestHelper.GetValue(this.certificatesController.GetCertificateStatus(new GetCertificateStatusModel(certificate1.Thumbprint, true))); Assert.Equal(CertificateStatus.Good.ToString(), status); this.certificatesController.RevokeCertificate(new CredentialsModelWithThumbprintModel(certificate1.Thumbprint, credentials1.AccountId, credentials1.Password)); // Can't revoke 2nd time same cert. - bool result = TestsHelper.GetValue(this.certificatesController.RevokeCertificate(new CredentialsModelWithThumbprintModel(certificate1.Thumbprint, credentials1.AccountId, credentials1.Password))); + bool result = CaTestHelper.GetValue(this.certificatesController.RevokeCertificate(new CredentialsModelWithThumbprintModel(certificate1.Thumbprint, credentials1.AccountId, credentials1.Password))); Assert.False(result); - Assert.Equal(CertificateStatus.Revoked.ToString(), TestsHelper.GetValue(this.certificatesController.GetCertificateStatus(new GetCertificateStatusModel(certificate1.Thumbprint, true)))); - Assert.Equal(CertificateStatus.Unknown.ToString(), TestsHelper.GetValue(this.certificatesController.GetCertificateStatus(new GetCertificateStatusModel(TestsHelper.GenerateRandomString(20), true)))); + Assert.Equal(CertificateStatus.Revoked.ToString(), CaTestHelper.GetValue(this.certificatesController.GetCertificateStatus(new GetCertificateStatusModel(certificate1.Thumbprint, true)))); + Assert.Equal(CertificateStatus.Unknown.ToString(), CaTestHelper.GetValue(this.certificatesController.GetCertificateStatus(new GetCertificateStatusModel(CaTestHelper.GenerateRandomString(20), true)))); - List allCerts = TestsHelper.GetValue>(this.certificatesController.GetAllCertificates(credentials1)); + List allCerts = CaTestHelper.GetValue>(this.certificatesController.GetAllCertificates(credentials1)); Assert.True(allCerts.Count(x => x.Status == CertificateStatus.Good) == 1); Assert.True(allCerts.Count(x => x.Status == CertificateStatus.Revoked) == 1); - Assert.Equal(CertificateStatus.Revoked.ToString(), TestsHelper.GetValue(this.certificatesController.GetCertificateStatus(new GetCertificateStatusModel(certificate1.Thumbprint, true)))); + Assert.Equal(CertificateStatus.Revoked.ToString(), CaTestHelper.GetValue(this.certificatesController.GetCertificateStatus(new GetCertificateStatusModel(certificate1.Thumbprint, true)))); - List revoked = TestsHelper.GetValue>(this.certificatesController.GetRevokedCertificates()).ToList(); + List revoked = CaTestHelper.GetValue>(this.certificatesController.GetRevokedCertificates()).ToList(); Assert.Single(revoked); Assert.Equal(certificate1.Thumbprint, revoked[0]); // Public keys for revoked certificates don't appear in the list. - pubKeys = TestsHelper.GetValue>(this.certificatesController.GetCertificatePublicKeys()).Select(s => new PubKey(s)).ToArray(); + pubKeys = CaTestHelper.GetValue>(this.certificatesController.GetCertificatePublicKeys()).Select(s => new PubKey(s)).ToArray(); Assert.Single(pubKeys); Assert.Equal(blockSigningPrivateKey.PubKey, pubKeys[0]); @@ -208,7 +206,7 @@ private async Task TestCertificatesControllerMethodsAsync() Assert.True(signedCsr.Verify()); - CertificateInfoModel certificate3 = TestsHelper.GetValue(this.certificatesController.IssueCertificate_UsingRequestString( + CertificateInfoModel certificate3 = CaTestHelper.GetValue(this.certificatesController.IssueCertificate_UsingRequestString( new IssueCertificateFromFileContentsModel(Convert.ToBase64String(signedCsr.GetDerEncoded()), credentials1.AccountId, credentials1.Password))); Assert.Equal(clientAddress, certificate3.Address); @@ -217,7 +215,7 @@ private async Task TestCertificatesControllerMethodsAsync() // In this case we just use the same pubkey for both the certificate generation & transaction signing pubkey hash, they would ordinarily be different. var generateModel = new GenerateCertificateSigningRequestModel(clientAddress, Convert.ToBase64String(clientPublicKey), Convert.ToBase64String(clientPrivateKey.PubKey.Hash.ToBytes()), Convert.ToBase64String(blockSigningPrivateKey.PubKey.ToBytes()), credentials1.AccountId, credentials1.Password); - CertificateSigningRequestModel unsignedCsrModel = TestsHelper.GetValue(this.certificatesController.GenerateCertificateSigningRequest(generateModel)); + CertificateSigningRequestModel unsignedCsrModel = CaTestHelper.GetValue(this.certificatesController.GenerateCertificateSigningRequest(generateModel)); byte[] csrTemp = Convert.FromBase64String(unsignedCsrModel.CertificateSigningRequestContent); @@ -232,7 +230,7 @@ private async Task TestCertificatesControllerMethodsAsync() // TODO: Why is this failing? Do a manual verification of the EC maths //Assert.True(signedCsr.Verify()); - CertificateInfoModel certificate4 = TestsHelper.GetValue(this.certificatesController.IssueCertificate_UsingRequestString( + CertificateInfoModel certificate4 = CaTestHelper.GetValue(this.certificatesController.IssueCertificate_UsingRequestString( new IssueCertificateFromFileContentsModel(Convert.ToBase64String(signedCsr.GetDerEncoded()), credentials1.AccountId, credentials1.Password))); Assert.Equal(clientAddress, certificate4.Address); @@ -281,7 +279,7 @@ private void TestAccessLevels() private void Returns403IfNoAccess(Func action, AccountAccessFlags requiredAccess) { - CredentialsModel noAccessCredentials = TestsHelper.CreateAccount(this.server); + CredentialsModel noAccessCredentials = CaTestHelper.CreateAccount(this.server); var response = action.Invoke(noAccessCredentials.AccountId, noAccessCredentials.Password); @@ -310,7 +308,7 @@ private void Returns403IfNoAccess(Func action, AccountAcces break; } - CredentialsModel accessCredentials = TestsHelper.CreateAccount(this.server, requiredAccess); + CredentialsModel accessCredentials = CaTestHelper.CreateAccount(this.server, requiredAccess); response = action.Invoke(accessCredentials.AccountId, accessCredentials.Password); @@ -346,7 +344,7 @@ private void Returns403IfNoAccess(Func action, AccountAcces private void CheckThrowsIfNoAccess(Action action, AccountAccessFlags requiredAccess) { - CredentialsModel noAccessCredentials = TestsHelper.CreateAccount(this.server); + CredentialsModel noAccessCredentials = CaTestHelper.CreateAccount(this.server); bool throwsIfNoAccess = false; try @@ -365,7 +363,7 @@ private void CheckThrowsIfNoAccess(Action action, AccountAccessFlag if (!throwsIfNoAccess) Assert.False(true, "Action was expected to throw."); - CredentialsModel accessCredentials = TestsHelper.CreateAccount(this.server, requiredAccess); + CredentialsModel accessCredentials = CaTestHelper.CreateAccount(this.server, requiredAccess); try { diff --git a/src/CertificateAuthority.Tests/FullProjectTests/Helpers/TestOnlyStartup.cs b/src/CertificateAuthority.Tests/TestOnlyStartup.cs similarity index 89% rename from src/CertificateAuthority.Tests/FullProjectTests/Helpers/TestOnlyStartup.cs rename to src/CertificateAuthority.Tests/TestOnlyStartup.cs index 16191753231..28fb3563328 100644 --- a/src/CertificateAuthority.Tests/FullProjectTests/Helpers/TestOnlyStartup.cs +++ b/src/CertificateAuthority.Tests/TestOnlyStartup.cs @@ -5,7 +5,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -namespace CertificateAuthority.Tests.FullProjectTests.Helpers +namespace CertificateAuthority.Tests { public class TestOnlyStartup : Startup { @@ -28,7 +28,7 @@ private string GetTestDirectoryPath(object caller, [System.Runtime.CompilerServi { string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff"); - string randomString = TestsHelper.GenerateRandomString(6); + string randomString = CaTestHelper.GenerateRandomString(6); return Path.Combine(Path.GetTempPath(), caller.GetType().Name, callingMethod, timeStamp + randomString); } diff --git a/src/CertificateAuthority/CaCertificatesManager.cs b/src/CertificateAuthority/CaCertificatesManager.cs index 34b16e358ed..cd13615e2f2 100644 --- a/src/CertificateAuthority/CaCertificatesManager.cs +++ b/src/CertificateAuthority/CaCertificatesManager.cs @@ -33,20 +33,15 @@ namespace CertificateAuthority { - public class CaCertificatesManager + public sealed class CaCertificatesManager { - private readonly DataCacheLayer repository; - - private readonly Settings settings; - - private readonly Logger logger = LogManager.GetCurrentClassLogger(); - private AsymmetricCipherKeyPair caKey; - private X509Certificate caCertificate; + private readonly Logger logger = LogManager.GetCurrentClassLogger(); + private readonly DataCacheLayer repository; + private readonly Settings settings; public const int CaAddressIndex = 0; - public const string CaCertFilename = "CaCertificate.crt"; public const string CaPfxFilename = "CaCertificate.pfx"; @@ -65,9 +60,9 @@ public class CaCertificatesManager public const int CertificateValidityPeriodYears = 10; public const int CaCertificateValidityPeriodYears = 10; - public CaCertificatesManager(DataCacheLayer cache, Settings settings) + public CaCertificatesManager(DataCacheLayer repository, Settings settings) { - this.repository = cache; + this.repository = repository; this.settings = settings; } @@ -95,7 +90,7 @@ public void Initialize() this.caKey = new AsymmetricCipherKeyPair(pub, ec); // TODO: This method of deriving pubkey from private could be made into its own method. } - public bool InitializeCertificateAuthority(string mnemonic, string password, int coinType, byte addressPrefix) + public bool InitializeCertificateAuthority(byte addressPrefix, string adminPassword, int coinType, string mnemonic, string mnemonicPassword) { if (this.caCertificate != null) { @@ -109,7 +104,7 @@ public bool InitializeCertificateAuthority(string mnemonic, string password, int string caSubjectName = $"O={this.settings.CaSubjectNameOrganization},CN={this.settings.CaSubjectNameCommonName},OU={this.settings.CaSubjectNameOrganizationUnit}"; string hdPath = $"m/44'/{coinType}'/0'/0/{CaAddressIndex}"; - var caAddressSpace = new HDWalletAddressSpace(mnemonic, password); + var caAddressSpace = new HDWalletAddressSpace(mnemonic, mnemonicPassword); Key caPrivateKey = caAddressSpace.GetKey(hdPath).PrivateKey; // The CA is the big boss, and won't be signing transactions itself, so no extensions. @@ -124,18 +119,27 @@ public bool InitializeCertificateAuthority(string mnemonic, string password, int // Many tests + tools are grabbing the certificate at this point. To keep that easily available we also store just the certificate. File.WriteAllBytes(Path.Combine(this.settings.DataDirectory, CaCertFilename), this.caCertificate.GetEncoded()); + + SetAdminPassword(adminPassword); } - catch (Exception) + catch (Exception ex) { this.caKey = null; this.caCertificate = null; + this.logger.Error(ex.ToString()); + return false; } return true; } + private void SetAdminPassword(string adminPassword) + { + this.repository.ChangeAccountPassword(Settings.AdminAccountId, adminPassword); + } + private static X509Certificate CreateCertificateAuthorityCertificate(AsymmetricCipherKeyPair subjectKeyPair, string subjectName, string[] subjectAlternativeNames, KeyPurposeID[] usages, Dictionary extensionData) { SecureRandom random = GetSecureRandom(); diff --git a/src/CertificateAuthority/CaClient.cs b/src/CertificateAuthority/CaClient.cs index 9c9d3473359..c5ce0ca9761 100644 --- a/src/CertificateAuthority/CaClient.cs +++ b/src/CertificateAuthority/CaClient.cs @@ -47,7 +47,7 @@ public bool InitializeCertificateAuthority(string mnemonic, string mnemonicPassw { // Happy to not use RequestFromCA method for now because this is a more specialised method, might need different logic at some point. - var mnemonicModel = new CredentialsModelWithMnemonicModel(mnemonic, mnemonicPassword, network.Consensus.CoinType, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS][0], this.accountId, this.password); + var mnemonicModel = new InitializeCertificateAuthorityModel(mnemonic, mnemonicPassword, network.Consensus.CoinType, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS][0], this.password); HttpResponseMessage response = this.httpClient.PostAsJsonAsync($"{this.baseApiUrl}{InitializeCertificateAuthorityEndpoint}", mnemonicModel).GetAwaiter().GetResult(); diff --git a/src/CertificateAuthority/Controllers/AccountsController.cs b/src/CertificateAuthority/Controllers/AccountsController.cs index b33c6bfe235..26e729fd151 100644 --- a/src/CertificateAuthority/Controllers/AccountsController.cs +++ b/src/CertificateAuthority/Controllers/AccountsController.cs @@ -132,6 +132,12 @@ public IActionResult ChangeAccountPassword([FromBody]ChangeAccountPasswordModel }); } + /// + /// Executes a query against the certificate authority repository. + /// + /// The action that will execute the query. + /// The caller of the action. + /// Returns an that is mostly a Json object. private IActionResult ExecuteRepositoryQuery(Func action, [CallerMemberName] string memberName = "") { try @@ -152,6 +158,12 @@ private IActionResult ExecuteRepositoryQuery(Func action, [Caller } } + /// + /// Executes a command (update) against the certificate authority repository. + /// + /// The action that will execute the update. + /// The caller of the action. + /// Returns an that is mostly a OK response. private IActionResult ExecuteRepositoryCommand(Func action, [CallerMemberName] string memberName = "") { try diff --git a/src/CertificateAuthority/Controllers/CertificatesController.cs b/src/CertificateAuthority/Controllers/CertificatesController.cs index f866c45b92f..e2001b13b13 100644 --- a/src/CertificateAuthority/Controllers/CertificatesController.cs +++ b/src/CertificateAuthority/Controllers/CertificatesController.cs @@ -28,15 +28,13 @@ public CertificatesController(CaCertificatesManager caCertificateManager) : base [HttpPost("initialize_ca")] [ProducesResponseType(typeof(bool), 200)] - public IActionResult InitializeCertificateAuthority([FromBody]CredentialsModelWithMnemonicModel model) + public IActionResult InitializeCertificateAuthority([FromBody]InitializeCertificateAuthorityModel model) { this.LogEntry(model); - var data = new CredentialsAccessWithModel(model, AccountAccessFlags.InitializeCertificateAuthority); - return ExecuteCaMethod(() => { - var certificateCreationResult = this.caCertificateManager.InitializeCertificateAuthority(data.Model.Mnemonic, data.Model.MnemonicPassword, data.Model.CoinType, data.Model.AddressPrefix); + var certificateCreationResult = this.caCertificateManager.InitializeCertificateAuthority(model.AddressPrefix, model.AdminPassword, model.CoinType, model.Mnemonic, model.MnemonicPassword); return this.Json(this.LogExit(certificateCreationResult)); }); } diff --git a/src/CertificateAuthority/Database/DataCacheLayer.cs b/src/CertificateAuthority/Database/DataCacheLayer.cs index b168876d936..236d97881e6 100644 --- a/src/CertificateAuthority/Database/DataCacheLayer.cs +++ b/src/CertificateAuthority/Database/DataCacheLayer.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using CertificateAuthority.Models; -using NBitcoin; using NBitcoin.DataEncoders; using NLog; @@ -33,12 +32,10 @@ public DataCacheLayer(Settings settings) // Create Admin. var admin = new AccountModel() { - Name = Settings.AdminName, - PasswordHash = settings.DefaultAdminPasswordHash, AccessInfo = AccountAccessFlags.AdminAccess, - - // Will set below. - CreatorId = 1 + CreatorId = Settings.AdminAccountId, + Name = Settings.AdminName, + PasswordHash = settings.DefaultAdminPasswordHash }; dbContext.Accounts.Add(admin); @@ -53,6 +50,7 @@ private CADbContext CreateContext() { return new CADbContext(this.settings); } + public void Initialize() { // Fill cache. @@ -202,6 +200,32 @@ public void ChangeAccountAccessLevel(CredentialsAccessWithModel + /// This method should not exposed to the API. + /// + /// The account's password that will be set. + /// The account's new password. + internal void ChangeAccountPassword(int accountId, string password) + { + if (string.IsNullOrEmpty(password)) + throw new Exception($"Password is null."); + + CADbContext dbContext = this.CreateContext(); + + AccountModel account = dbContext.Accounts.SingleOrDefault(a => a.Id == accountId); + if (account == null) + throw new Exception($"The account was not found: {accountId}"); + + account.PasswordHash = DataHelper.ComputeSha256Hash(password); + + dbContext.Accounts.Update(account); + dbContext.SaveChanges(); + + this.logger.Info("Account Id {0}'s password has been updated.", accountId); + + return; + } + public void ChangeAccountPassword(CredentialsAccessWithModel credentialsModel) { ExecuteCommand(credentialsModel, (dbContext, account) => diff --git a/src/CertificateAuthority/Models/APIModels.cs b/src/CertificateAuthority/Models/APIModels.cs index a101a8430c8..4d27133ff9a 100644 --- a/src/CertificateAuthority/Models/APIModels.cs +++ b/src/CertificateAuthority/Models/APIModels.cs @@ -123,32 +123,6 @@ public CredentialsModelWithPubKeyHashModel() } } - public class CredentialsModelWithMnemonicModel : CredentialsModel - { - /// Mnemonic words used to derive certificate authority's private key. - public string Mnemonic { get; set; } - - /// Password to be used with the mnemonic words, used to derive certificate authority's private key. - /// This is a separate password to the actual user account to allow the user account password to be changed without affecting the CA. - public string MnemonicPassword { get; set; } - - public int CoinType { get; set; } - - public byte AddressPrefix { get; set; } - - public CredentialsModelWithMnemonicModel(string mnemonic, string mnemonicPassword, int coinType, byte addressPrefix, int accountId, string password) : base(accountId, password) - { - this.Mnemonic = mnemonic; - this.MnemonicPassword = mnemonicPassword; - this.CoinType = coinType; - this.AddressPrefix = addressPrefix; - } - - public CredentialsModelWithMnemonicModel() - { - } - } - public class GenerateCertificateSigningRequestModel : CredentialsModel { public string Address { get; set; } @@ -159,7 +133,7 @@ public class GenerateCertificateSigningRequestModel : CredentialsModel public string BlockSigningPubKey { get; set; } public string TransactionSigningPubKeyHash { get; set; } - + public GenerateCertificateSigningRequestModel(string address, string pubKey, string transactionSigningPubKeyHash, string blockSigningPubKey, int accountId, string password) : base(accountId, password) { this.Address = address; diff --git a/src/CertificateAuthority/Models/InitializeCertificateAuthorityModel.cs b/src/CertificateAuthority/Models/InitializeCertificateAuthorityModel.cs new file mode 100644 index 00000000000..b750755a61d --- /dev/null +++ b/src/CertificateAuthority/Models/InitializeCertificateAuthorityModel.cs @@ -0,0 +1,44 @@ +using System.ComponentModel.DataAnnotations; + +namespace CertificateAuthority.Models +{ + /// + /// This model initializes the certificate authority as well as set the admin account's password. + /// + public sealed class InitializeCertificateAuthorityModel + { + [Required] + public byte AddressPrefix { get; set; } + + [Required] + public int CoinType { get; set; } + + /// Mnemonic words used to derive certificate authority's private key. + [Required] + public string Mnemonic { get; set; } + + /// Password to be used with the mnemonic words, used to derive certificate authority's private key. + /// This is a separate password to the actual user account to allow the user account password to be changed without affecting the CA. + [Required] + public string MnemonicPassword { get; set; } + + /// + /// This will be used to set the admin account's password on initialization. + /// + [Required] + public string AdminPassword { get; set; } + + public InitializeCertificateAuthorityModel() + { + } + + public InitializeCertificateAuthorityModel(string mnemonic, string mnemonicPassword, int coinType, byte addressPrefix, string password) + { + this.AddressPrefix = addressPrefix; + this.CoinType = coinType; + this.Mnemonic = mnemonic; + this.MnemonicPassword = mnemonicPassword; + this.AdminPassword = password; + } + } +} diff --git a/src/CertificateAuthority/Settings.cs b/src/CertificateAuthority/Settings.cs index 7229bb26066..d1d365035ee 100644 --- a/src/CertificateAuthority/Settings.cs +++ b/src/CertificateAuthority/Settings.cs @@ -18,13 +18,14 @@ public static string NormalizeDirectorySeparator(this string path) public class Settings { + public const int AdminAccountId = 1; + public const string AdminName = "Admin"; + public const string AdminPasswordUnInitialized = "0000000000000000000000000000000000000000000000000000000000000000"; private const string DataDirRoot = "StratisNode"; private const string RootFolderName = "ca"; private const string SubFolderName = "CaMain"; private const string ConfigFileName = "ca.conf"; - public const string AdminName = "Admin"; - private string configurationFile; public string DataDirectory { get; private set; } @@ -104,7 +105,7 @@ public void Initialize(string[] commandLineArgs) this.CreateAdminAccountOnCleanStart = configFileArgs.GetOrDefault("createadmin", true); - this.DefaultAdminPasswordHash = configFileArgs.GetOrDefault("adminpasshash", "6085fee2997a53fe15f195d907590238ec1f717adf6ac7fd4d7ed137f91892aa"); + this.DefaultAdminPasswordHash = configFileArgs.GetOrDefault("adminpasshash", AdminPasswordUnInitialized); this.CaSubjectNameOrganization = configFileArgs.GetOrDefault("caorganization", "Stratis"); diff --git a/src/Stratis.SmartContracts.IntegrationTests/TokenlessNodeTests.cs b/src/Stratis.SmartContracts.IntegrationTests/TokenlessNodeTests.cs index 284aaa70a08..376f8463f7e 100644 --- a/src/Stratis.SmartContracts.IntegrationTests/TokenlessNodeTests.cs +++ b/src/Stratis.SmartContracts.IntegrationTests/TokenlessNodeTests.cs @@ -8,8 +8,7 @@ using System.Threading.Tasks; using CertificateAuthority; using CertificateAuthority.Models; -using CertificateAuthority.Tests.FullProjectTests; -using CertificateAuthority.Tests.FullProjectTests.Helpers; +using CertificateAuthority.Tests; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; @@ -61,7 +60,7 @@ public async Task StartCACorrectlyAndTestApiAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -106,7 +105,7 @@ public async Task TokenlessNodesMineAnEmptyBlockAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -134,7 +133,7 @@ public async Task TokenlessNodesConnectAndMineOpReturnAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -172,7 +171,7 @@ public async Task TokenlessNodesConnectAndMineWithoutPasswordAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -223,7 +222,7 @@ public async Task TokenlessNodesCreateAndCallAContractAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -272,7 +271,7 @@ public async Task TokenlessNodesCreateAndCallWithControllerAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -360,8 +359,7 @@ public async Task TokenlessNodesKickAMinerBasedOnCAAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, - CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -445,7 +443,7 @@ public async Task NodeStoresSendersCertificateFromApiAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -500,7 +498,7 @@ public async Task RestartCAAndEverythingStillWorksAsync() // Start + Initialize CA. client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. ac = GetCertificateFromInitializedCAServer(server); @@ -537,7 +535,7 @@ public async Task RestartTokenlessNodeAfterBlocksMinedAndContinuesAsync() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -566,13 +564,13 @@ public void CantInitializeCATwice() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); // Try and initialize it again with a new password. - Assert.False(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, "SomeRandomPassword", this.network)); + Assert.False(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, "SomeRandomPassword", this.network)); // Check that the certificate is identical X509Certificate ac2 = GetCertificateFromInitializedCAServer(server); @@ -591,7 +589,7 @@ public async Task AddedNodeCanMineWithoutBreaking() // Start + Initialize CA. var client = GetClient(); - Assert.True(client.InitializeCertificateAuthority(CertificateAuthorityIntegrationTests.CaMnemonic, CertificateAuthorityIntegrationTests.CaMnemonicPassword, this.network)); + Assert.True(client.InitializeCertificateAuthority(CaTestHelper.CaMnemonic, CaTestHelper.CaMnemonicPassword, this.network)); // Get Authority Certificate. X509Certificate ac = GetCertificateFromInitializedCAServer(server); @@ -649,7 +647,7 @@ public async Task AddedNodeCanMineWithoutBreaking() private CaClient GetClient() { var httpClient = new HttpClient(); - return new CaClient(new Uri(this.BaseAddress), httpClient, CertificateAuthorityIntegrationTests.TestAccountId, CertificateAuthorityIntegrationTests.TestPassword); + return new CaClient(new Uri(this.BaseAddress), httpClient, Settings.AdminAccountId, CaTestHelper.AdminPassword); } /// diff --git a/src/Stratis.SmartContracts.Tests.Common/FullTokenlessRunner.cs b/src/Stratis.SmartContracts.Tests.Common/FullTokenlessRunner.cs index 546b195d69b..7bbf9b8693b 100644 --- a/src/Stratis.SmartContracts.Tests.Common/FullTokenlessRunner.cs +++ b/src/Stratis.SmartContracts.Tests.Common/FullTokenlessRunner.cs @@ -1,4 +1,5 @@ -using CertificateAuthority.Tests.FullProjectTests; +using CertificateAuthority; +using CertificateAuthority.Tests; using NBitcoin; using Stratis.Bitcoin; using Stratis.Bitcoin.Base; @@ -34,8 +35,8 @@ public FullTokenlessRunner(string dataDir, Network network, EditableTimeProvider public override void BuildNode() { var settings = new NodeSettings(this.Network, args: new string[] { "-conf=poa.conf", "-datadir=" + this.DataFolder, - $"-{CertificatesManager.CaAccountIdKey}={CertificateAuthorityIntegrationTests.TestAccountId}", - $"-{CertificatesManager.CaPasswordKey}={CertificateAuthorityIntegrationTests.TestPassword}", + $"-{CertificatesManager.CaAccountIdKey}={Settings.AdminAccountId}", + $"-{CertificatesManager.CaPasswordKey}={CaTestHelper.AdminPassword}", $"-{CertificatesManager.ClientCertificateConfigurationKey}=test" });