1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-22 12:15:36 +01:00
bitwarden-server/test/Core.Test/Services/DeviceServiceTests.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

266 lines
10 KiB
C#
Raw Normal View History

Trusted Device Encryption feature (#3151) * [PM-1203] feat: allow verification for all passwordless accounts (#3038) * [PM-1033] Org invite user creation flow 1 (#3028) * [PM-1033] feat: remove user verification from password enrollment * [PM-1033] feat: auto accept invitation when enrolling into password reset * [PM-1033] fix: controller tests * [PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand` * [PM-1033] refactor(wip): make `AcceptUserCommand` * Revert "[PM-1033] refactor(wip): make `AcceptUserCommand`" This reverts commit dc1319e7fa70c4844bbc70e0b01089b682ac2843. * Revert "[PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand`" This reverts commit 43df689c7f244af4f7ffec1f9768a72081a624c3. * [PM-1033] refactor: move invite accept to controller This avoids creating yet another method that depends on having `IUserService` passed in as a parameter * [PM-1033] fix: add missing changes * [PM-1381] Add Trusted Device Keys to Auth Response (#3066) * Return Keys for Trusted Device - Check whether the current logging in device is trusted - Return their keys on successful login * Formatting * Address PR Feedback * Add Remarks Comment * [PM-1338] `AuthRequest` Event Logs (#3046) * Update AuthRequestController - Only allow AdminApproval Requests to be created from authed endpoint - Add endpoint that has authentication to be able to create admin approval * Add PasswordlessAuthSettings - Add settings for customizing expiration times * Add new EventTypes * Add Logic for AdminApproval Type - Add logic for validating AdminApproval expiration - Add event logging for Approval/Disapproval of AdminApproval - Add logic for creating AdminApproval types * Add Test Helpers - Change BitAutoData to allow you to use string representations of common types. * Add/Update AuthRequestService Tests * Run Formatting * Switch to 7 Days * Add Test Covering ResponseDate Being Set * Address PR Feedback - Create helper for checking if date is expired - Move validation logic into smaller methods * Switch to User Event Type - Make RequestDeviceApproval user type - User types will log for each org user is in * [PM-2998] Move Approving Device Check (#3101) * Move Check for Approving Devices - Exclude currently logging in device - Remove old way of checking - Add tests asserting behavior * Update DeviceType list * Update Naming & Address PR Feedback * Fix Tests * Address PR Feedback * Formatting * Now Fully Update Naming? * Feature/auth/pm 2759/add can reset password to user decryption options (#3113) * PM-2759 - BaseRequestValidator.cs - CreateUserDecryptionOptionsAsync - Add new hasManageResetPasswordPermission for post SSO redirect logic required on client. * PM-2759 - Update IdentityServerSsoTests.cs to all pass based on the addition of HasManageResetPasswordPermission to TrustedDeviceUserDecryptionOption * IdentityServerSsoTests.cs - fix typo in test name: LoggingApproval --> LoginApproval * PM1259 - Add test case for verifying that TrustedDeviceOption.hasManageResetPasswordPermission is set properly based on user permission * dotnet format run * Feature/auth/pm 2759/add can reset password to user decryption options fix jit users (#3120) * PM-2759 - IdentityServer - CreateUserDecryptionOptionsAsync - hasManageResetPasswordPermission set logic was broken for JIT provisioned users as I assumed we would always have a list of at least 1 org during the SSO process. Added TODO for future test addition but getting this out there now as QA is blocked by being unable to create JIT provisioned users. * dotnet format * Tiny tweak * [PM-1339] Allow Rotating Device Keys (#3096) * Allow Rotation of Trusted Device Keys - Add endpoint for getting keys relating to rotation - Add endpoint for rotating your current device - In the same endpoint allow a list of other devices to rotate * Formatting * Use Extension Method * Add Tests from PR Co-authored-by: Jared Snider <jsnider@bitwarden.com> --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> * Check the user directly if they have the ResetPasswordKey (#3153) * PM-3327 - UpdateKeyAsync must exempt the currently calling device from the logout notification in order to prevent prematurely logging the user out before the client side key rotation process can complete. The calling device will log itself out once it is done. (#3170) * Allow OTP Requests When Users Are On TDE (#3184) * [PM-3356][PM-3292] Allow OTP For All (#3188) * Allow OTP For All - On a trusted device isn't a good check because a user might be using a trusted device locally but not trusted it long term - The logic wasn't working for KC users anyways * Remove Old Comment * [AC-1601] Added RequireSso policy as a dependency of TDE (#3209) * Added RequireSso policy as a dependency of TDE. * Added test for RequireSso for TDE. * Added save. * Fixed policy name. --------- Co-authored-by: Andreas Coroiu <acoroiu@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: Jared Snider <jsnider@bitwarden.com>
2023-08-17 22:03:06 +02:00
using System.Runtime.CompilerServices;
using Bit.Core.Auth.Models.Api.Request;
using Bit.Core.Entities;
Families for Enterprise (#1714) * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Fix build error * Update emails * Fix tests * Skip local test * Add newline * Fix stripe subscription update * Finish emails * Skip test * Fix unit tests * Remove unused variable * Fix unit tests * Switch to handlebars ifs * Remove ending email * Remove reconfirmation template * Switch naming convention * Switch naming convention * Fix migration * Update copy and links * Switch to using Guid in the method * Remove unneeded css styles * Add sql files to Sql.sqlproj * Removed old comments * Made name more verbose * Fix SQL error * Move unit tests to service * Fix sp * Revert "Move unit tests to service" This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6. * Do repository validation in service layer * Fix tests * Fix merge conflicts and remove TODO * Remove unneeded models * Fix spacing and formatting * Switch Org -> Organization * Remove single use variables * Switch method name * Fix Controller * Switch to obfuscating email * Fix unit tests Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 23:25:06 +01:00
using Bit.Core.Enums;
Trusted Device Encryption feature (#3151) * [PM-1203] feat: allow verification for all passwordless accounts (#3038) * [PM-1033] Org invite user creation flow 1 (#3028) * [PM-1033] feat: remove user verification from password enrollment * [PM-1033] feat: auto accept invitation when enrolling into password reset * [PM-1033] fix: controller tests * [PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand` * [PM-1033] refactor(wip): make `AcceptUserCommand` * Revert "[PM-1033] refactor(wip): make `AcceptUserCommand`" This reverts commit dc1319e7fa70c4844bbc70e0b01089b682ac2843. * Revert "[PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand`" This reverts commit 43df689c7f244af4f7ffec1f9768a72081a624c3. * [PM-1033] refactor: move invite accept to controller This avoids creating yet another method that depends on having `IUserService` passed in as a parameter * [PM-1033] fix: add missing changes * [PM-1381] Add Trusted Device Keys to Auth Response (#3066) * Return Keys for Trusted Device - Check whether the current logging in device is trusted - Return their keys on successful login * Formatting * Address PR Feedback * Add Remarks Comment * [PM-1338] `AuthRequest` Event Logs (#3046) * Update AuthRequestController - Only allow AdminApproval Requests to be created from authed endpoint - Add endpoint that has authentication to be able to create admin approval * Add PasswordlessAuthSettings - Add settings for customizing expiration times * Add new EventTypes * Add Logic for AdminApproval Type - Add logic for validating AdminApproval expiration - Add event logging for Approval/Disapproval of AdminApproval - Add logic for creating AdminApproval types * Add Test Helpers - Change BitAutoData to allow you to use string representations of common types. * Add/Update AuthRequestService Tests * Run Formatting * Switch to 7 Days * Add Test Covering ResponseDate Being Set * Address PR Feedback - Create helper for checking if date is expired - Move validation logic into smaller methods * Switch to User Event Type - Make RequestDeviceApproval user type - User types will log for each org user is in * [PM-2998] Move Approving Device Check (#3101) * Move Check for Approving Devices - Exclude currently logging in device - Remove old way of checking - Add tests asserting behavior * Update DeviceType list * Update Naming & Address PR Feedback * Fix Tests * Address PR Feedback * Formatting * Now Fully Update Naming? * Feature/auth/pm 2759/add can reset password to user decryption options (#3113) * PM-2759 - BaseRequestValidator.cs - CreateUserDecryptionOptionsAsync - Add new hasManageResetPasswordPermission for post SSO redirect logic required on client. * PM-2759 - Update IdentityServerSsoTests.cs to all pass based on the addition of HasManageResetPasswordPermission to TrustedDeviceUserDecryptionOption * IdentityServerSsoTests.cs - fix typo in test name: LoggingApproval --> LoginApproval * PM1259 - Add test case for verifying that TrustedDeviceOption.hasManageResetPasswordPermission is set properly based on user permission * dotnet format run * Feature/auth/pm 2759/add can reset password to user decryption options fix jit users (#3120) * PM-2759 - IdentityServer - CreateUserDecryptionOptionsAsync - hasManageResetPasswordPermission set logic was broken for JIT provisioned users as I assumed we would always have a list of at least 1 org during the SSO process. Added TODO for future test addition but getting this out there now as QA is blocked by being unable to create JIT provisioned users. * dotnet format * Tiny tweak * [PM-1339] Allow Rotating Device Keys (#3096) * Allow Rotation of Trusted Device Keys - Add endpoint for getting keys relating to rotation - Add endpoint for rotating your current device - In the same endpoint allow a list of other devices to rotate * Formatting * Use Extension Method * Add Tests from PR Co-authored-by: Jared Snider <jsnider@bitwarden.com> --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> * Check the user directly if they have the ResetPasswordKey (#3153) * PM-3327 - UpdateKeyAsync must exempt the currently calling device from the logout notification in order to prevent prematurely logging the user out before the client side key rotation process can complete. The calling device will log itself out once it is done. (#3170) * Allow OTP Requests When Users Are On TDE (#3184) * [PM-3356][PM-3292] Allow OTP For All (#3188) * Allow OTP For All - On a trusted device isn't a good check because a user might be using a trusted device locally but not trusted it long term - The logic wasn't working for KC users anyways * Remove Old Comment * [AC-1601] Added RequireSso policy as a dependency of TDE (#3209) * Added RequireSso policy as a dependency of TDE. * Added test for RequireSso for TDE. * Added save. * Fixed policy name. --------- Co-authored-by: Andreas Coroiu <acoroiu@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: Jared Snider <jsnider@bitwarden.com>
2023-08-17 22:03:06 +02:00
using Bit.Core.Exceptions;
using Bit.Core.Repositories;
using Bit.Core.Services;
Trusted Device Encryption feature (#3151) * [PM-1203] feat: allow verification for all passwordless accounts (#3038) * [PM-1033] Org invite user creation flow 1 (#3028) * [PM-1033] feat: remove user verification from password enrollment * [PM-1033] feat: auto accept invitation when enrolling into password reset * [PM-1033] fix: controller tests * [PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand` * [PM-1033] refactor(wip): make `AcceptUserCommand` * Revert "[PM-1033] refactor(wip): make `AcceptUserCommand`" This reverts commit dc1319e7fa70c4844bbc70e0b01089b682ac2843. * Revert "[PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand`" This reverts commit 43df689c7f244af4f7ffec1f9768a72081a624c3. * [PM-1033] refactor: move invite accept to controller This avoids creating yet another method that depends on having `IUserService` passed in as a parameter * [PM-1033] fix: add missing changes * [PM-1381] Add Trusted Device Keys to Auth Response (#3066) * Return Keys for Trusted Device - Check whether the current logging in device is trusted - Return their keys on successful login * Formatting * Address PR Feedback * Add Remarks Comment * [PM-1338] `AuthRequest` Event Logs (#3046) * Update AuthRequestController - Only allow AdminApproval Requests to be created from authed endpoint - Add endpoint that has authentication to be able to create admin approval * Add PasswordlessAuthSettings - Add settings for customizing expiration times * Add new EventTypes * Add Logic for AdminApproval Type - Add logic for validating AdminApproval expiration - Add event logging for Approval/Disapproval of AdminApproval - Add logic for creating AdminApproval types * Add Test Helpers - Change BitAutoData to allow you to use string representations of common types. * Add/Update AuthRequestService Tests * Run Formatting * Switch to 7 Days * Add Test Covering ResponseDate Being Set * Address PR Feedback - Create helper for checking if date is expired - Move validation logic into smaller methods * Switch to User Event Type - Make RequestDeviceApproval user type - User types will log for each org user is in * [PM-2998] Move Approving Device Check (#3101) * Move Check for Approving Devices - Exclude currently logging in device - Remove old way of checking - Add tests asserting behavior * Update DeviceType list * Update Naming & Address PR Feedback * Fix Tests * Address PR Feedback * Formatting * Now Fully Update Naming? * Feature/auth/pm 2759/add can reset password to user decryption options (#3113) * PM-2759 - BaseRequestValidator.cs - CreateUserDecryptionOptionsAsync - Add new hasManageResetPasswordPermission for post SSO redirect logic required on client. * PM-2759 - Update IdentityServerSsoTests.cs to all pass based on the addition of HasManageResetPasswordPermission to TrustedDeviceUserDecryptionOption * IdentityServerSsoTests.cs - fix typo in test name: LoggingApproval --> LoginApproval * PM1259 - Add test case for verifying that TrustedDeviceOption.hasManageResetPasswordPermission is set properly based on user permission * dotnet format run * Feature/auth/pm 2759/add can reset password to user decryption options fix jit users (#3120) * PM-2759 - IdentityServer - CreateUserDecryptionOptionsAsync - hasManageResetPasswordPermission set logic was broken for JIT provisioned users as I assumed we would always have a list of at least 1 org during the SSO process. Added TODO for future test addition but getting this out there now as QA is blocked by being unable to create JIT provisioned users. * dotnet format * Tiny tweak * [PM-1339] Allow Rotating Device Keys (#3096) * Allow Rotation of Trusted Device Keys - Add endpoint for getting keys relating to rotation - Add endpoint for rotating your current device - In the same endpoint allow a list of other devices to rotate * Formatting * Use Extension Method * Add Tests from PR Co-authored-by: Jared Snider <jsnider@bitwarden.com> --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> * Check the user directly if they have the ResetPasswordKey (#3153) * PM-3327 - UpdateKeyAsync must exempt the currently calling device from the logout notification in order to prevent prematurely logging the user out before the client side key rotation process can complete. The calling device will log itself out once it is done. (#3170) * Allow OTP Requests When Users Are On TDE (#3184) * [PM-3356][PM-3292] Allow OTP For All (#3188) * Allow OTP For All - On a trusted device isn't a good check because a user might be using a trusted device locally but not trusted it long term - The logic wasn't working for KC users anyways * Remove Old Comment * [AC-1601] Added RequireSso policy as a dependency of TDE (#3209) * Added RequireSso policy as a dependency of TDE. * Added test for RequireSso for TDE. * Added save. * Fixed policy name. --------- Co-authored-by: Andreas Coroiu <acoroiu@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: Jared Snider <jsnider@bitwarden.com>
2023-08-17 22:03:06 +02:00
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.Services;
2022-08-29 22:06:55 +02:00
Trusted Device Encryption feature (#3151) * [PM-1203] feat: allow verification for all passwordless accounts (#3038) * [PM-1033] Org invite user creation flow 1 (#3028) * [PM-1033] feat: remove user verification from password enrollment * [PM-1033] feat: auto accept invitation when enrolling into password reset * [PM-1033] fix: controller tests * [PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand` * [PM-1033] refactor(wip): make `AcceptUserCommand` * Revert "[PM-1033] refactor(wip): make `AcceptUserCommand`" This reverts commit dc1319e7fa70c4844bbc70e0b01089b682ac2843. * Revert "[PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand`" This reverts commit 43df689c7f244af4f7ffec1f9768a72081a624c3. * [PM-1033] refactor: move invite accept to controller This avoids creating yet another method that depends on having `IUserService` passed in as a parameter * [PM-1033] fix: add missing changes * [PM-1381] Add Trusted Device Keys to Auth Response (#3066) * Return Keys for Trusted Device - Check whether the current logging in device is trusted - Return their keys on successful login * Formatting * Address PR Feedback * Add Remarks Comment * [PM-1338] `AuthRequest` Event Logs (#3046) * Update AuthRequestController - Only allow AdminApproval Requests to be created from authed endpoint - Add endpoint that has authentication to be able to create admin approval * Add PasswordlessAuthSettings - Add settings for customizing expiration times * Add new EventTypes * Add Logic for AdminApproval Type - Add logic for validating AdminApproval expiration - Add event logging for Approval/Disapproval of AdminApproval - Add logic for creating AdminApproval types * Add Test Helpers - Change BitAutoData to allow you to use string representations of common types. * Add/Update AuthRequestService Tests * Run Formatting * Switch to 7 Days * Add Test Covering ResponseDate Being Set * Address PR Feedback - Create helper for checking if date is expired - Move validation logic into smaller methods * Switch to User Event Type - Make RequestDeviceApproval user type - User types will log for each org user is in * [PM-2998] Move Approving Device Check (#3101) * Move Check for Approving Devices - Exclude currently logging in device - Remove old way of checking - Add tests asserting behavior * Update DeviceType list * Update Naming & Address PR Feedback * Fix Tests * Address PR Feedback * Formatting * Now Fully Update Naming? * Feature/auth/pm 2759/add can reset password to user decryption options (#3113) * PM-2759 - BaseRequestValidator.cs - CreateUserDecryptionOptionsAsync - Add new hasManageResetPasswordPermission for post SSO redirect logic required on client. * PM-2759 - Update IdentityServerSsoTests.cs to all pass based on the addition of HasManageResetPasswordPermission to TrustedDeviceUserDecryptionOption * IdentityServerSsoTests.cs - fix typo in test name: LoggingApproval --> LoginApproval * PM1259 - Add test case for verifying that TrustedDeviceOption.hasManageResetPasswordPermission is set properly based on user permission * dotnet format run * Feature/auth/pm 2759/add can reset password to user decryption options fix jit users (#3120) * PM-2759 - IdentityServer - CreateUserDecryptionOptionsAsync - hasManageResetPasswordPermission set logic was broken for JIT provisioned users as I assumed we would always have a list of at least 1 org during the SSO process. Added TODO for future test addition but getting this out there now as QA is blocked by being unable to create JIT provisioned users. * dotnet format * Tiny tweak * [PM-1339] Allow Rotating Device Keys (#3096) * Allow Rotation of Trusted Device Keys - Add endpoint for getting keys relating to rotation - Add endpoint for rotating your current device - In the same endpoint allow a list of other devices to rotate * Formatting * Use Extension Method * Add Tests from PR Co-authored-by: Jared Snider <jsnider@bitwarden.com> --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> * Check the user directly if they have the ResetPasswordKey (#3153) * PM-3327 - UpdateKeyAsync must exempt the currently calling device from the logout notification in order to prevent prematurely logging the user out before the client side key rotation process can complete. The calling device will log itself out once it is done. (#3170) * Allow OTP Requests When Users Are On TDE (#3184) * [PM-3356][PM-3292] Allow OTP For All (#3188) * Allow OTP For All - On a trusted device isn't a good check because a user might be using a trusted device locally but not trusted it long term - The logic wasn't working for KC users anyways * Remove Old Comment * [AC-1601] Added RequireSso policy as a dependency of TDE (#3209) * Added RequireSso policy as a dependency of TDE. * Added test for RequireSso for TDE. * Added save. * Fixed policy name. --------- Co-authored-by: Andreas Coroiu <acoroiu@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: Jared Snider <jsnider@bitwarden.com>
2023-08-17 22:03:06 +02:00
[SutProviderCustomize]
public class DeviceServiceTests
{
2022-08-29 22:06:55 +02:00
[Fact]
public async Task DeviceSaveShouldUpdateRevisionDateAndPushRegistration()
{
var deviceRepo = Substitute.For<IDeviceRepository>();
var pushRepo = Substitute.For<IPushRegistrationService>();
var deviceService = new DeviceService(deviceRepo, pushRepo);
var id = Guid.NewGuid();
var userId = Guid.NewGuid();
2021-05-14 00:06:16 +02:00
var device = new Device
{
Id = id,
Name = "test device",
Families for Enterprise (#1714) * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Fix build error * Update emails * Fix tests * Skip local test * Add newline * Fix stripe subscription update * Finish emails * Skip test * Fix unit tests * Remove unused variable * Fix unit tests * Switch to handlebars ifs * Remove ending email * Remove reconfirmation template * Switch naming convention * Switch naming convention * Fix migration * Update copy and links * Switch to using Guid in the method * Remove unneeded css styles * Add sql files to Sql.sqlproj * Removed old comments * Made name more verbose * Fix SQL error * Move unit tests to service * Fix sp * Revert "Move unit tests to service" This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6. * Do repository validation in service layer * Fix tests * Fix merge conflicts and remove TODO * Remove unneeded models * Fix spacing and formatting * Switch Org -> Organization * Remove single use variables * Switch method name * Fix Controller * Switch to obfuscating email * Fix unit tests Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 23:25:06 +01:00
Type = DeviceType.Android,
UserId = userId,
PushToken = "testtoken",
Identifier = "testid"
};
await deviceService.SaveAsync(device);
Assert.True(device.RevisionDate - DateTime.UtcNow < TimeSpan.FromSeconds(1));
await pushRepo.Received().CreateOrUpdateRegistrationAsync("testtoken", id.ToString(),
Families for Enterprise (#1714) * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Fix build error * Update emails * Fix tests * Skip local test * Add newline * Fix stripe subscription update * Finish emails * Skip test * Fix unit tests * Remove unused variable * Fix unit tests * Switch to handlebars ifs * Remove ending email * Remove reconfirmation template * Switch naming convention * Switch naming convention * Fix migration * Update copy and links * Switch to using Guid in the method * Remove unneeded css styles * Add sql files to Sql.sqlproj * Removed old comments * Made name more verbose * Fix SQL error * Move unit tests to service * Fix sp * Revert "Move unit tests to service" This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6. * Do repository validation in service layer * Fix tests * Fix merge conflicts and remove TODO * Remove unneeded models * Fix spacing and formatting * Switch Org -> Organization * Remove single use variables * Switch method name * Fix Controller * Switch to obfuscating email * Fix unit tests Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 23:25:06 +01:00
userId.ToString(), "testid", DeviceType.Android);
}
Trusted Device Encryption feature (#3151) * [PM-1203] feat: allow verification for all passwordless accounts (#3038) * [PM-1033] Org invite user creation flow 1 (#3028) * [PM-1033] feat: remove user verification from password enrollment * [PM-1033] feat: auto accept invitation when enrolling into password reset * [PM-1033] fix: controller tests * [PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand` * [PM-1033] refactor(wip): make `AcceptUserCommand` * Revert "[PM-1033] refactor(wip): make `AcceptUserCommand`" This reverts commit dc1319e7fa70c4844bbc70e0b01089b682ac2843. * Revert "[PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand`" This reverts commit 43df689c7f244af4f7ffec1f9768a72081a624c3. * [PM-1033] refactor: move invite accept to controller This avoids creating yet another method that depends on having `IUserService` passed in as a parameter * [PM-1033] fix: add missing changes * [PM-1381] Add Trusted Device Keys to Auth Response (#3066) * Return Keys for Trusted Device - Check whether the current logging in device is trusted - Return their keys on successful login * Formatting * Address PR Feedback * Add Remarks Comment * [PM-1338] `AuthRequest` Event Logs (#3046) * Update AuthRequestController - Only allow AdminApproval Requests to be created from authed endpoint - Add endpoint that has authentication to be able to create admin approval * Add PasswordlessAuthSettings - Add settings for customizing expiration times * Add new EventTypes * Add Logic for AdminApproval Type - Add logic for validating AdminApproval expiration - Add event logging for Approval/Disapproval of AdminApproval - Add logic for creating AdminApproval types * Add Test Helpers - Change BitAutoData to allow you to use string representations of common types. * Add/Update AuthRequestService Tests * Run Formatting * Switch to 7 Days * Add Test Covering ResponseDate Being Set * Address PR Feedback - Create helper for checking if date is expired - Move validation logic into smaller methods * Switch to User Event Type - Make RequestDeviceApproval user type - User types will log for each org user is in * [PM-2998] Move Approving Device Check (#3101) * Move Check for Approving Devices - Exclude currently logging in device - Remove old way of checking - Add tests asserting behavior * Update DeviceType list * Update Naming & Address PR Feedback * Fix Tests * Address PR Feedback * Formatting * Now Fully Update Naming? * Feature/auth/pm 2759/add can reset password to user decryption options (#3113) * PM-2759 - BaseRequestValidator.cs - CreateUserDecryptionOptionsAsync - Add new hasManageResetPasswordPermission for post SSO redirect logic required on client. * PM-2759 - Update IdentityServerSsoTests.cs to all pass based on the addition of HasManageResetPasswordPermission to TrustedDeviceUserDecryptionOption * IdentityServerSsoTests.cs - fix typo in test name: LoggingApproval --> LoginApproval * PM1259 - Add test case for verifying that TrustedDeviceOption.hasManageResetPasswordPermission is set properly based on user permission * dotnet format run * Feature/auth/pm 2759/add can reset password to user decryption options fix jit users (#3120) * PM-2759 - IdentityServer - CreateUserDecryptionOptionsAsync - hasManageResetPasswordPermission set logic was broken for JIT provisioned users as I assumed we would always have a list of at least 1 org during the SSO process. Added TODO for future test addition but getting this out there now as QA is blocked by being unable to create JIT provisioned users. * dotnet format * Tiny tweak * [PM-1339] Allow Rotating Device Keys (#3096) * Allow Rotation of Trusted Device Keys - Add endpoint for getting keys relating to rotation - Add endpoint for rotating your current device - In the same endpoint allow a list of other devices to rotate * Formatting * Use Extension Method * Add Tests from PR Co-authored-by: Jared Snider <jsnider@bitwarden.com> --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> * Check the user directly if they have the ResetPasswordKey (#3153) * PM-3327 - UpdateKeyAsync must exempt the currently calling device from the logout notification in order to prevent prematurely logging the user out before the client side key rotation process can complete. The calling device will log itself out once it is done. (#3170) * Allow OTP Requests When Users Are On TDE (#3184) * [PM-3356][PM-3292] Allow OTP For All (#3188) * Allow OTP For All - On a trusted device isn't a good check because a user might be using a trusted device locally but not trusted it long term - The logic wasn't working for KC users anyways * Remove Old Comment * [AC-1601] Added RequireSso policy as a dependency of TDE (#3209) * Added RequireSso policy as a dependency of TDE. * Added test for RequireSso for TDE. * Added save. * Fixed policy name. --------- Co-authored-by: Andreas Coroiu <acoroiu@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: Jared Snider <jsnider@bitwarden.com>
2023-08-17 22:03:06 +02:00
/// <summary>
/// Story: A user choosed to keep trust in one of their current trusted devices, but not in another one of their
/// devices. We will rotate the trust of the currently signed in device as well as the device they chose but will
/// remove the trust of the device they didn't give new keys for.
/// </summary>
[Theory, BitAutoData]
public async Task UpdateDevicesTrustAsync_Works(
SutProvider<DeviceService> sutProvider,
Guid currentUserId,
Device deviceOne,
Device deviceTwo,
Device deviceThree)
{
SetupOldTrust(deviceOne);
SetupOldTrust(deviceTwo);
SetupOldTrust(deviceThree);
deviceOne.Identifier = "current_device";
sutProvider.GetDependency<IDeviceRepository>()
.GetManyByUserIdAsync(currentUserId)
.Returns(new List<Device>
{
deviceOne,
deviceTwo,
deviceThree,
});
var currentDeviceModel = new DeviceKeysUpdateRequestModel
{
EncryptedPublicKey = "current_encrypted_public_key",
EncryptedUserKey = "current_encrypted_user_key",
};
var alteredDeviceModels = new List<OtherDeviceKeysUpdateRequestModel>
{
new OtherDeviceKeysUpdateRequestModel
{
DeviceId = deviceTwo.Id,
EncryptedPublicKey = "encrypted_public_key_two",
EncryptedUserKey = "encrypted_user_key_two",
},
};
await sutProvider.Sut.UpdateDevicesTrustAsync("current_device", currentUserId, currentDeviceModel, alteredDeviceModels);
// Updating trust, "current" or "other" only needs to change the EncryptedPublicKey & EncryptedUserKey
await sutProvider.GetDependency<IDeviceRepository>()
.Received(1)
.UpsertAsync(Arg.Is<Device>(d =>
d.Id == deviceOne.Id &&
d.EncryptedPublicKey == "current_encrypted_public_key" &&
d.EncryptedUserKey == "current_encrypted_user_key" &&
d.EncryptedPrivateKey == "old_private_deviceOne"));
await sutProvider.GetDependency<IDeviceRepository>()
.Received(1)
.UpsertAsync(Arg.Is<Device>(d =>
d.Id == deviceTwo.Id &&
d.EncryptedPublicKey == "encrypted_public_key_two" &&
d.EncryptedUserKey == "encrypted_user_key_two" &&
d.EncryptedPrivateKey == "old_private_deviceTwo"));
// Clearing trust should remove all key values
await sutProvider.GetDependency<IDeviceRepository>()
.Received(1)
.UpsertAsync(Arg.Is<Device>(d =>
d.Id == deviceThree.Id &&
d.EncryptedPublicKey == null &&
d.EncryptedUserKey == null &&
d.EncryptedPrivateKey == null));
// Should have recieved a total of 3 calls, the ones asserted above
await sutProvider.GetDependency<IDeviceRepository>()
.Received(3)
.UpsertAsync(Arg.Any<Device>());
// TODO: .NET 8: Use nameof for parameter name.
static void SetupOldTrust(Device device, [CallerArgumentExpression("device")] string expression = null)
{
device.EncryptedPublicKey = $"old_public_{expression}";
device.EncryptedPrivateKey = $"old_private_{expression}";
device.EncryptedUserKey = $"old_user_{expression}";
}
}
/// <summary>
/// Story: This could result from a poor implementation of this method, if they attempt add trust to a device
/// that doesn't already have trust. They would have to create brand new values and for that values to be accurate
/// they would technically have all the values needed to trust a device, that is why we don't consider this bad
/// enough to throw but do skip it because we'd rather keep number of ways for trust to be added to the endpoint we
/// already have.
/// </summary>
[Theory, BitAutoData]
public async Task UpdateDevicesTrustAsync_DoesNotUpdateUntrustedDevices(
SutProvider<DeviceService> sutProvider,
Guid currentUserId,
Device deviceOne,
Device deviceTwo)
{
deviceOne.Identifier = "current_device";
// Make deviceTwo untrusted
deviceTwo.EncryptedUserKey = string.Empty;
deviceTwo.EncryptedPublicKey = string.Empty;
deviceTwo.EncryptedPrivateKey = string.Empty;
sutProvider.GetDependency<IDeviceRepository>()
.GetManyByUserIdAsync(currentUserId)
.Returns(new List<Device>
{
deviceOne,
deviceTwo,
});
var currentDeviceModel = new DeviceKeysUpdateRequestModel
{
EncryptedPublicKey = "current_encrypted_public_key",
EncryptedUserKey = "current_encrypted_user_key",
};
var alteredDeviceModels = new List<OtherDeviceKeysUpdateRequestModel>
{
new OtherDeviceKeysUpdateRequestModel
{
DeviceId = deviceTwo.Id,
EncryptedPublicKey = "encrypted_public_key_two",
EncryptedUserKey = "encrypted_user_key_two",
},
};
await sutProvider.Sut.UpdateDevicesTrustAsync("current_device", currentUserId, currentDeviceModel, alteredDeviceModels);
// Check that UpsertAsync was called for the trusted device
await sutProvider.GetDependency<IDeviceRepository>()
.Received(1)
.UpsertAsync(Arg.Is<Device>(d =>
d.Id == deviceOne.Id &&
d.EncryptedPublicKey == "current_encrypted_public_key" &&
d.EncryptedUserKey == "current_encrypted_user_key"));
// Check that UpsertAsync was not called for the untrusted device
await sutProvider.GetDependency<IDeviceRepository>()
.DidNotReceive()
.UpsertAsync(Arg.Is<Device>(d => d.Id == deviceTwo.Id));
}
/// <summary>
/// Story: This should only happen if someone were to take the access token from a different device and try to rotate
/// a device that they don't actually have.
/// </summary>
[Theory, BitAutoData]
public async Task UpdateDevicesTrustAsync_ThrowsNotFoundException_WhenCurrentDeviceIdentifierDoesNotExist(
SutProvider<DeviceService> sutProvider,
Guid currentUserId,
Device deviceOne,
Device deviceTwo)
{
deviceOne.Identifier = "some_other_device";
deviceTwo.Identifier = "another_device";
sutProvider.GetDependency<IDeviceRepository>()
.GetManyByUserIdAsync(currentUserId)
.Returns(new List<Device>
{
deviceOne,
deviceTwo,
});
var currentDeviceModel = new DeviceKeysUpdateRequestModel
{
EncryptedPublicKey = "current_encrypted_public_key",
EncryptedUserKey = "current_encrypted_user_key",
};
await Assert.ThrowsAsync<NotFoundException>(() =>
sutProvider.Sut.UpdateDevicesTrustAsync("current_device", currentUserId, currentDeviceModel,
Enumerable.Empty<OtherDeviceKeysUpdateRequestModel>()));
}
/// <summary>
/// Story: This should only happen from a poorly implemented user of this method but important to enforce someone
/// using the method correctly, a device should only be rotated intentionally and including it as both the current
/// device and one of the users other device would mean they could rotate it twice and we aren't sure
/// which one they would want to win out.
/// </summary>
[Theory, BitAutoData]
public async Task UpdateDevicesTrustAsync_ThrowsBadRequestException_WhenCurrentDeviceIsIncludedInAlteredDevices(
SutProvider<DeviceService> sutProvider,
Guid currentUserId,
Device deviceOne,
Device deviceTwo)
{
deviceOne.Identifier = "current_device";
sutProvider.GetDependency<IDeviceRepository>()
.GetManyByUserIdAsync(currentUserId)
.Returns(new List<Device>
{
deviceOne,
deviceTwo,
});
var currentDeviceModel = new DeviceKeysUpdateRequestModel
{
EncryptedPublicKey = "current_encrypted_public_key",
EncryptedUserKey = "current_encrypted_user_key",
};
var alteredDeviceModels = new List<OtherDeviceKeysUpdateRequestModel>
{
new OtherDeviceKeysUpdateRequestModel
{
DeviceId = deviceOne.Id, // current device is included in alteredDevices
EncryptedPublicKey = "encrypted_public_key_one",
EncryptedUserKey = "encrypted_user_key_one",
},
};
await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.UpdateDevicesTrustAsync("current_device", currentUserId, currentDeviceModel, alteredDeviceModels));
}
}