Ejemplo n.º 1
0
        public void Write_Success()
        {
            var json = JsonSerializer.Serialize(new TestObject
            {
                StringProp           = "1",
                EnumerableStringProp = new List <string>
                {
                    "2",
                    "3",
                },
            });

            var jsonElement = JsonDocument.Parse(json).RootElement;

            var stringProp = AssertHelper.AssertJsonProperty(jsonElement, "StringProp", JsonValueKind.String);

            Assert.Equal("1", stringProp.GetString());
            var list = AssertHelper.AssertJsonProperty(jsonElement, "EnumerableStringProp", JsonValueKind.Array);

            Assert.Equal(2, list.GetArrayLength());
            var firstElement = list[0];

            Assert.Equal(JsonValueKind.String, firstElement.ValueKind);
            Assert.Equal("2", firstElement.GetString());
            var secondElement = list[1];

            Assert.Equal(JsonValueKind.String, secondElement.ValueKind);
            Assert.Equal("3", secondElement.GetString());
        }
Ejemplo n.º 2
0
        public async Task TokenEndpoint_GrantTypePassword_NoAuthEmailHeader_Fails()
        {
            var deviceId = "92b9d953-b9b6-4eaf-9d3e-11d57144dfeb";
            var username = "******";

            await _factory.RegisterAsync(new RegisterRequestModel
            {
                Email = username,
                MasterPasswordHash = "master_password_hash",
            });

            var context = await _factory.Server.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "scope", "api offline_access" },
                { "client_id", "web" },
                { "deviceType", DeviceTypeAsString(DeviceType.FirefoxBrowser) },
                { "deviceIdentifier", deviceId },
                { "deviceName", "firefox" },
                { "grant_type", "password" },
                { "username", username },
                { "password", "master_password_hash" },
            }));

            Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);

            var body = await AssertHelper.AssertResponseTypeIs <JsonDocument>(context);

            var root = body.RootElement;

            var error = AssertHelper.AssertJsonProperty(root, "error", JsonValueKind.String).GetString();

            Assert.Equal("invalid_grant", error);
            AssertHelper.AssertJsonProperty(root, "error_description", JsonValueKind.String);
        }
Ejemplo n.º 3
0
        private static int AssertExpiresIn(JsonElement tokenResponse, int expectedExpiresIn = 3600)
        {
            var expiresIn = AssertHelper.AssertJsonProperty(tokenResponse, "expires_in", JsonValueKind.Number).GetInt32();

            Assert.Equal(expectedExpiresIn, expiresIn);
            return(expiresIn);
        }
Ejemplo n.º 4
0
        public void GetTwoFactorProviders_SavedWithName_Success()
        {
            var user = new User();

            // This should save items with the string name of the enum and we will validate that we can read
            // from that just incase some users have it saved that way.
            user.TwoFactorProviders = JsonSerializer.Serialize(_testTwoFactorConfig);

            // Preliminary Asserts to make sure we are testing what we want to be testing
            using var jsonDocument = JsonDocument.Parse(user.TwoFactorProviders);
            var root = jsonDocument.RootElement;

            // This means it saved the enum as its string name
            AssertHelper.AssertJsonProperty(root, "WebAuthn", JsonValueKind.Object);
            AssertHelper.AssertJsonProperty(root, "Email", JsonValueKind.Object);

            // Actual checks
            var twoFactorProviders = user.GetTwoFactorProviders();

            var webAuthn = Assert.Contains(TwoFactorProviderType.WebAuthn, (IDictionary <TwoFactorProviderType, TwoFactorProvider>)twoFactorProviders);

            Assert.True(webAuthn.Enabled);
            Assert.NotNull(webAuthn.MetaData);
            var webAuthnMetaDataItem = Assert.Contains("Item", (IDictionary <string, object>)webAuthn.MetaData);

            Assert.Equal("thing", webAuthnMetaDataItem);

            var email = Assert.Contains(TwoFactorProviderType.Email, (IDictionary <TwoFactorProviderType, TwoFactorProvider>)twoFactorProviders);

            Assert.False(email.Enabled);
            Assert.NotNull(email.MetaData);
            var emailMetaDataEmail = Assert.Contains("Email", (IDictionary <string, object>)email.MetaData);

            Assert.Equal("*****@*****.**", emailMetaDataEmail);
        }
Ejemplo n.º 5
0
        public void GetTwoFactorProviders_SavedWithName_Success()
        {
            var organization = new Organization();

            // This should save items with the string name of the enum and we will validate that we can read
            // from that just incase some organizations have it saved that way.
            organization.TwoFactorProviders = JsonSerializer.Serialize(_testConfig);

            // Preliminary Asserts to make sure we are testing what we want to be testing
            using var jsonDocument = JsonDocument.Parse(organization.TwoFactorProviders);
            var root = jsonDocument.RootElement;

            // This means it saved the enum as its string name
            AssertHelper.AssertJsonProperty(root, "OrganizationDuo", JsonValueKind.Object);

            // Actual checks
            var twoFactorProviders = organization.GetTwoFactorProviders();

            var duo = Assert.Contains(TwoFactorProviderType.OrganizationDuo, (IDictionary <TwoFactorProviderType, TwoFactorProvider>)twoFactorProviders);

            Assert.True(duo.Enabled);
            Assert.NotNull(duo.MetaData);
            var iKey = Assert.Contains("IKey", (IDictionary <string, object>)duo.MetaData);

            Assert.Equal("IKey_value", iKey);
            var sKey = Assert.Contains("SKey", (IDictionary <string, object>)duo.MetaData);

            Assert.Equal("SKey_value", sKey);
            var host = Assert.Contains("Host", (IDictionary <string, object>)duo.MetaData);

            Assert.Equal("Host_value", host);
        }
Ejemplo n.º 6
0
        public void Write_Null()
        {
            // When the values are null the converters aren't actually ran and it automatically serializes null
            var json = JsonSerializer.Serialize(new TestObject
            {
                StringProp           = null,
                EnumerableStringProp = null,
            });

            var jsonElement = JsonDocument.Parse(json).RootElement;

            AssertHelper.AssertJsonProperty(jsonElement, "StringProp", JsonValueKind.Null);
            AssertHelper.AssertJsonProperty(jsonElement, "EnumerableStringProp", JsonValueKind.Null);
        }
Ejemplo n.º 7
0
        public void ToSend_Text_Success()
        {
            var deletionDate = DateTime.UtcNow.AddDays(5);
            var sendRequest  = new SendRequestModel
            {
                DeletionDate   = deletionDate,
                Disabled       = false,
                ExpirationDate = null,
                HideEmail      = false,
                Key            = "encrypted_key",
                MaxAccessCount = null,
                Name           = "encrypted_name",
                Notes          = null,
                Password       = "******",
                Text           = new SendTextModel()
                {
                    Hidden = false,
                    Text   = "encrypted_text"
                },
                Type = SendType.Text,
            };

            var sendService = Substitute.For <ISendService>();

            sendService.HashPassword(Arg.Any <string>())
            .Returns((info) => $"hashed_{(string)info[0]}");

            var send = sendRequest.ToSend(Guid.NewGuid(), sendService);

            Assert.Equal(deletionDate, send.DeletionDate);
            Assert.False(send.Disabled);
            Assert.Null(send.ExpirationDate);
            Assert.False(send.HideEmail);
            Assert.Equal("encrypted_key", send.Key);
            Assert.Equal("hashed_Password", send.Password);

            using var jsonDocument = JsonDocument.Parse(send.Data);
            var root = jsonDocument.RootElement;
            var text = AssertHelper.AssertJsonProperty(root, "Text", JsonValueKind.String).GetString();

            Assert.Equal("encrypted_text", text);
            AssertHelper.AssertJsonProperty(root, "Hidden", JsonValueKind.False);
            Assert.False(root.TryGetProperty("Notes", out var _));
            var name = AssertHelper.AssertJsonProperty(root, "Name", JsonValueKind.String).GetString();

            Assert.Equal("encrypted_name", name);
        }
Ejemplo n.º 8
0
        public void Serialize_Success()
        {
            var sut = new SendFileData
            {
                Id        = "test",
                Size      = 100,
                FileName  = "thing.pdf",
                Validated = true,
            };

            var json     = JsonSerializer.Serialize(sut);
            var document = JsonDocument.Parse(json);
            var root     = document.RootElement;

            AssertHelper.AssertJsonProperty(root, "Size", JsonValueKind.String);
            Assert.False(root.TryGetProperty("SizeString", out _));
        }
Ejemplo n.º 9
0
        public void Write_Empty()
        {
            // When the values are null the converters aren't actually ran and it automatically serializes null
            var json = JsonSerializer.Serialize(new TestObject
            {
                StringProp           = "",
                EnumerableStringProp = Enumerable.Empty <string>(),
            });

            var jsonElement = JsonDocument.Parse(json).RootElement;

            var stringVal = AssertHelper.AssertJsonProperty(jsonElement, "StringProp", JsonValueKind.String).GetString();

            Assert.Equal("", stringVal);
            var array = AssertHelper.AssertJsonProperty(jsonElement, "EnumerableStringProp", JsonValueKind.Array);

            Assert.Equal(0, array.GetArrayLength());
        }
Ejemplo n.º 10
0
        public async Task TokenEndpoint_GrantTypeClientCredentials_AsInstallation_NoIdPart_Fails()
        {
            var context = await _factory.Server.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "grant_type", "client_credentials" },
                { "client_id", "installation." },
                { "client_secret", "something" },
                { "scope", "api.push" },
            }));

            Assert.Equal(StatusCodes.Status400BadRequest, context.Response.StatusCode);

            var errorBody = await AssertHelper.AssertResponseTypeIs <JsonDocument>(context);

            var error = AssertHelper.AssertJsonProperty(errorBody.RootElement, "error", JsonValueKind.String).GetString();

            Assert.Equal("invalid_client", error);
        }
Ejemplo n.º 11
0
        public async Task UpdateLicenseAsync_Success(SutProvider <UserService> sutProvider,
                                                     User user, UserLicense userLicense)
        {
            using var tempDir = new TempDirectory();

            var now = DateTime.UtcNow;

            userLicense.Issued  = now.AddDays(-10);
            userLicense.Expires = now.AddDays(10);
            userLicense.Version = 1;
            userLicense.Premium = true;

            user.EmailVerified = true;
            user.Email         = userLicense.Email;

            sutProvider.GetDependency <Settings.IGlobalSettings>().SelfHosted       = true;
            sutProvider.GetDependency <Settings.IGlobalSettings>().LicenseDirectory = tempDir.Directory;
            sutProvider.GetDependency <ILicensingService>()
            .VerifyLicense(userLicense)
            .Returns(true);

            await sutProvider.Sut.UpdateLicenseAsync(user, userLicense);

            var filePath = Path.Combine(tempDir.Directory, "user", $"{user.Id}.json");

            Assert.True(File.Exists(filePath));
            var document = JsonDocument.Parse(File.OpenRead(filePath));
            var root     = document.RootElement;

            Assert.Equal(JsonValueKind.Object, root.ValueKind);
            // Sort of a lazy way to test that it is indented but not sure of a better way
            Assert.Contains('\n', root.GetRawText());
            AssertHelper.AssertJsonProperty(root, "LicenseKey", JsonValueKind.String);
            AssertHelper.AssertJsonProperty(root, "Id", JsonValueKind.String);
            AssertHelper.AssertJsonProperty(root, "Premium", JsonValueKind.True);
            var versionProp = AssertHelper.AssertJsonProperty(root, "Version", JsonValueKind.Number);

            Assert.Equal(1, versionProp.GetInt32());
        }
Ejemplo n.º 12
0
        public void SetTwoFactorProviders_Success()
        {
            var organization = new Organization();

            organization.SetTwoFactorProviders(_testConfig);

            using var jsonDocument = JsonDocument.Parse(organization.TwoFactorProviders);
            var root = jsonDocument.RootElement;

            var duo = AssertHelper.AssertJsonProperty(root, "6", JsonValueKind.Object);

            AssertHelper.AssertJsonProperty(duo, "Enabled", JsonValueKind.True);
            var duoMetaData = AssertHelper.AssertJsonProperty(duo, "MetaData", JsonValueKind.Object);
            var iKey        = AssertHelper.AssertJsonProperty(duoMetaData, "IKey", JsonValueKind.String).GetString();

            Assert.Equal("IKey_value", iKey);
            var sKey = AssertHelper.AssertJsonProperty(duoMetaData, "SKey", JsonValueKind.String).GetString();

            Assert.Equal("SKey_value", sKey);
            var host = AssertHelper.AssertJsonProperty(duoMetaData, "Host", JsonValueKind.String).GetString();

            Assert.Equal("Host_value", host);
        }
Ejemplo n.º 13
0
        public void SetTwoFactorProviders_Success()
        {
            var user = new User();

            user.SetTwoFactorProviders(_testTwoFactorConfig);

            using var jsonDocument = JsonDocument.Parse(user.TwoFactorProviders);
            var root = jsonDocument.RootElement;

            var webAuthn = AssertHelper.AssertJsonProperty(root, "7", JsonValueKind.Object);

            AssertHelper.AssertJsonProperty(webAuthn, "Enabled", JsonValueKind.True);
            var webMetaData = AssertHelper.AssertJsonProperty(webAuthn, "MetaData", JsonValueKind.Object);

            AssertHelper.AssertJsonProperty(webMetaData, "Item", JsonValueKind.String);

            var email = AssertHelper.AssertJsonProperty(root, "1", JsonValueKind.Object);

            AssertHelper.AssertJsonProperty(email, "Enabled", JsonValueKind.False);
            var emailMetaData = AssertHelper.AssertJsonProperty(email, "MetaData", JsonValueKind.Object);

            AssertHelper.AssertJsonProperty(emailMetaData, "Email", JsonValueKind.String);
        }
Ejemplo n.º 14
0
        public async Task TokenEndpoint_GrantTypePassword_Success()
        {
            var deviceId = "92b9d953-b9b6-4eaf-9d3e-11d57144dfeb";
            var username = "******";

            await _factory.RegisterAsync(new RegisterRequestModel
            {
                Email = username,
                MasterPasswordHash = "master_password_hash"
            });

            var context = await _factory.Server.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "scope", "api offline_access" },
                { "client_id", "web" },
                { "deviceType", DeviceTypeAsString(DeviceType.FirefoxBrowser) },
                { "deviceIdentifier", deviceId },
                { "deviceName", "firefox" },
                { "grant_type", "password" },
                { "username", username },
                { "password", "master_password_hash" },
            }), context => context.SetAuthEmail(username));

            using var body = await AssertDefaultTokenBodyAsync(context);

            var root = body.RootElement;

            AssertRefreshTokenExists(root);
            AssertHelper.AssertJsonProperty(root, "ForcePasswordReset", JsonValueKind.False);
            AssertHelper.AssertJsonProperty(root, "ResetMasterPassword", JsonValueKind.False);
            var kdf = AssertHelper.AssertJsonProperty(root, "Kdf", JsonValueKind.Number).GetInt32();

            Assert.Equal(0, kdf);
            var kdfIterations = AssertHelper.AssertJsonProperty(root, "KdfIterations", JsonValueKind.Number).GetInt32();

            Assert.Equal(5000, kdfIterations);
        }
Ejemplo n.º 15
0
        private static void AssertTokenType(JsonElement tokenResponse)
        {
            var tokenTypeProperty = AssertHelper.AssertJsonProperty(tokenResponse, "token_type", JsonValueKind.String).GetString();

            Assert.Equal("Bearer", tokenTypeProperty);
        }
Ejemplo n.º 16
0
 private static string AssertRefreshTokenExists(JsonElement tokenResponse)
 {
     return(AssertHelper.AssertJsonProperty(tokenResponse, "refresh_token", JsonValueKind.String).GetString());
 }
Ejemplo n.º 17
0
 private static string AssertScopeExists(JsonElement tokenResponse)
 {
     return(AssertHelper.AssertJsonProperty(tokenResponse, "scope", JsonValueKind.String).GetString());
 }