1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-22 12:15:36 +01:00
Commit Graph

627 Commits

Author SHA1 Message Date
Shane Melton
dba7a79ad2
[AC-1696] Fix Provider permissions for Flexible Collections (#3381)
* [AC-1117] Add manage permission (#3126)

* Update sql files to add Manage permission

* Add migration script

* Rename collection manage migration file to remove duplicate migration date

* Migrations

* Add manage to models

* Add manage to repository

* Add constraint to Manage columns

* Migration lint fixes

* Add manage to OrganizationUserUserDetails_ReadWithCollectionsById

* Add missing manage fields

* Add 'Manage' to UserCollectionDetails

* Use CREATE OR ALTER where possible

* [AC-1374] Limit collection creation/deletion to Owner/Admin (#3145)

* feat: update org table with new column, write migration, refs AC-1374

* feat: update views with new column, refs AC-1374

* feat: Alter sprocs (org create/update) to include new column, refs AC-1374

* feat: update entity/data/request/response models to handle new column, refs AC-1374

* feat: update necessary Provider related views during migration, refs AC-1374

* fix: update org create to default new column to false, refs AC-1374

* feat: added new API/request model for collection management and removed property from update request model, refs AC-1374

* fix: renamed migration script to be after secrets manage beta column changes, refs AC-1374

* fix: dotnet format, refs AC-1374

* feat: add ef migrations to reflect mssql changes, refs AC-1374

* fix: dotnet format, refs AC-1374

* feat: update API signature to accept Guid and explain Cd verbiage, refs AC-1374

* fix: merge conflict resolution

* [AC-1174] CollectionUser and CollectionGroup authorization handlers (#3194)

* [AC-1174] Introduce BulkAuthorizationHandler.cs

* [AC-1174] Introduce CollectionUserAuthorizationHandler

* [AC-1174] Add CreateForNewCollection CollectionUser requirement

* [AC-1174] Add some more details to CollectionCustomization

* [AC-1174] Formatting

* [AC-1174] Add CollectionGroupOperation.cs

* [AC-1174] Introduce CollectionGroupAuthorizationHandler.cs

* [AC-1174] Cleanup CollectionFixture customization

Implement and use re-usable extension method to support seeded Guids

* [AC-1174] Introduce WithValueFromList AutoFixtureExtensions

Modify CollectionCustomization to use multiple organization Ids for auto generated test data

* [AC-1174] Simplify CollectionUserAuthorizationHandler.cs

Modify the authorization handler to only perform authorization logic. Validation logic will need to be handled by any calling commands/controllers instead.

* [AC-1174] Introduce shared CollectionAccessAuthorizationHandlerBase

A shared base authorization handler was created for both CollectionUser and CollectionGroup resources, as they share the same underlying management authorization logic.

* [AC-1174] Update CollectionUserAuthorizationHandler and CollectionGroupAuthorizationHandler to use the new CollectionAccessAuthorizationHandlerBase class

* [AC-1174] Formatting

* [AC-1174] Cleanup typo and redundant ToList() call

* [AC-1174] Add check for provider users

* [AC-1174] Reduce nested loops

* [AC-1174] Introduce ICollectionAccess.cs

* [AC-1174] Remove individual CollectionGroup and CollectionUser auth handlers and use base class instead

* [AC-1174] Tweak unit test to fail minimally

* [AC-1174] Reorganize authorization handlers in Core project

* [AC-1174] Introduce new AddCoreAuthorizationHandlers() extension method

* [AC-1174] Move CollectionAccessAuthorizationHandler into Api project

* [AC-1174] Move CollectionFixture to Vault folder

* [AC-1174] Rename operation to CreateUpdateDelete

* [AC-1174] Require single organization for collection access authorization handler

- Add requirement that all target collections must belong to the same organization
- Simplify logic related to multiple organizations
- Update tests and helpers
- Use ToHashSet to improve lookup time

* [AC-1174] Fix null reference exception

* [AC-1174] Throw bad request exception when collections belong to different organizations

* [AC-1174] Switch to CollectionAuthorizationHandler instead of CollectionAccessAuthorizationHandler to reduce complexity

* Fix improper merge conflict resolution

* fix: add permission check for collection management api, refs AC-1647 (#3252)

* [AC-1125] Enforce org setting for creating/deleting collections (#3241)

* [AC-1117] Add manage permission (#3126)

* Update sql files to add Manage permission

* Add migration script

* Rename collection manage migration file to remove duplicate migration date

* Migrations

* Add manage to models

* Add manage to repository

* Add constraint to Manage columns

* Migration lint fixes

* Add manage to OrganizationUserUserDetails_ReadWithCollectionsById

* Add missing manage fields

* Add 'Manage' to UserCollectionDetails

* Use CREATE OR ALTER where possible

* [AC-1374] Limit collection creation/deletion to Owner/Admin (#3145)

* feat: update org table with new column, write migration, refs AC-1374

* feat: update views with new column, refs AC-1374

* feat: Alter sprocs (org create/update) to include new column, refs AC-1374

* feat: update entity/data/request/response models to handle new column, refs AC-1374

* feat: update necessary Provider related views during migration, refs AC-1374

* fix: update org create to default new column to false, refs AC-1374

* feat: added new API/request model for collection management and removed property from update request model, refs AC-1374

* fix: renamed migration script to be after secrets manage beta column changes, refs AC-1374

* fix: dotnet format, refs AC-1374

* feat: add ef migrations to reflect mssql changes, refs AC-1374

* fix: dotnet format, refs AC-1374

* feat: update API signature to accept Guid and explain Cd verbiage, refs AC-1374

* feat: created collection auth handler/operations, added LimitCollectionCdOwnerAdmin to CurrentContentOrganization, refs AC-1125

* feat: create vault service collection extensions and register with base services, refs AC-1125

* feat: deprecated CurrentContext.CreateNewCollections, refs AC-1125

* feat: deprecate DeleteAnyCollection for single resource usages, refs AC-1125

* feat: move service registration to api, update references, refs AC-1125

* feat: add bulk delete authorization handler, refs AC-1125

* feat: always assign user and give manage access on create, refs AC-1125

* fix: updated CurrentContextOrganization type, refs AC-1125

* feat: combined existing collection authorization handlers/operations, refs AC-1125

* fix: OrganizationServiceTests -> CurrentContentOrganization typo, refs AC-1125

* fix: format, refs AC-1125

* fix: update collection controller tests, refs AC-1125

* fix: dotnet format, refs AC-1125

* feat: removed extra BulkAuthorizationHandler, refs AC-1125

* fix: dotnet format, refs AC-1125

* fix: change string to guid for org id, update bulk delete request model, refs AC-1125

* fix: remove delete many collection check, refs AC-1125

* fix: clean up collection auth handler, refs AC-1125

* fix: format fix for CollectionOperations, refs AC-1125

* fix: removed unnecessary owner check, add org null check to custom permission validation, refs AC-1125

* fix: remove unused methods in CurrentContext, refs AC-1125

* fix: removed obsolete test, fixed failling delete many test, refs AC-1125

* fix: CollectionAuthorizationHandlerTests fixes, refs AC-1125

* fix: OrganizationServiceTests fix broken test by mocking GetOrganization, refs AC-1125

* fix: CollectionAuthorizationHandler - remove unused repository, refs AC-1125

* feat: moved UserId null check to common method, refs AC-1125

* fix: updated auth handler tests to remove dependency on requirement for common code checks, refs AC-1125

* feat: updated conditionals/comments for create/delete methods within colleciton auth handler, refs AC-1125

* feat: added create/delete collection auth handler success methods, refs AC-1125

* fix: new up permissions to prevent excessive null checks, refs AC-1125

* fix: remove old reference to CreateNewCollections, refs AC-1125

* fix: typo within ViewAssignedCollections method, refs AC-1125

---------

Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>

* refactor: remove organizationId from CollectionBulkDeleteRequestModel, refs AC-1649 (#3282)

* [AC-1174] Bulk Collection Management (#3229)

* [AC-1174] Update SelectionReadOnlyRequestModel to use Guid for Id property

* [AC-1174] Introduce initial bulk-access collection endpoint

* [AC-1174] Introduce BulkAddCollectionAccessCommand and validation logic/tests

* [AC-1174] Add CreateOrUpdateAccessMany method to CollectionRepository

* [AC-1174] Add event logs for bulk add collection access command

* [AC-1174] Add User_BumpAccountRevisionDateByCollectionIds and database migration script

* [AC-1174] Implement EF repository method

* [AC-1174] Improve null checks

* [AC-1174] Remove unnecessary BulkCollectionAccessRequestModel helpers

* [AC-1174] Add unit tests for new controller endpoint

* [AC-1174] Fix formatting

* [AC-1174] Remove comment

* [AC-1174] Remove redundant organizationId parameter

* [AC-1174] Ensure user and group Ids are distinct

* [AC-1174] Cleanup tests based on PR feedback

* [AC-1174] Formatting

* [AC-1174] Update CollectionGroup alias in the sproc

* [AC-1174] Add some additional comments to SQL sproc

* [AC-1174] Add comment explaining additional SaveChangesAsync call

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* [AC-1646] Rename LimitCollectionCdOwnerAdmin column (#3300)

* Rename LimitCollectionCdOwnerAdmin -> LimitCollectionCreationDeletion

* Rename and bump migration script

* [AC-1666] Removed EditAnyCollection from Create/Delete permission checks (#3301)

* fix: remove EditAnyCollection from Create/Delete permission check, refs AC-1666

* fix: updated comment, refs AC-1666

* [AC-1669] Bug - Remove obsolete assignUserId from CollectionService.SaveAsync(...) (#3312)

* fix: remove AssignUserId from CollectionService.SaveAsync, refs AC-1669

* fix: add manage access conditional before creating collection, refs AC-1669

* fix: move access logic for create/update, fix all tests, refs AC-1669

* fix: add CollectionAccessSelection fixture, update tests, update bad reqeuest message, refs AC-1669

* fix: format, refs AC-1669

* fix: update null params with specific arg.is null checks, refs Ac-1669

* fix: update attribute class name, refs AC-1669

* [AC-1713] [Flexible collections] Add feature flags to server (#3334)

* Add feature flags for FlexibleCollections and BulkCollectionAccess

* Flag new routes and behaviour

---------

Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>

* Add joint codeownership for auth handlers (#3346)

* [AC-1717] Update default values for LimitCollectionCreationDeletion (#3365)

* Change default value in organization create sproc to 1

* Drop old column name still present in some QA instances

* Set LimitCollectionCreationDeletion value in code based on feature flag

* Fix: add missing namespace after merging in master

* Fix: add missing namespace after merging in master

* [AC-1683] Fix DB migrations for new Manage permission (#3307)

* [AC-1683] Update migration script and introduce V2 procedures and types

* [AC-1683] Update repository calls to use new V2 procedures / types

* [AC-1684] Update bulk add collection migration script to use new V2 type

* [AC-1683] Undo Manage changes to more original procedures

* [AC-1683] Restore whitespace changes

* [AC-1683] Clarify comments regarding explicit column lists

* [AC-1683] Update migration script dates

* [AC-1683] Split the migration script for readability

* [AC-1683] Re-name SelectReadOnlyArray_V2 to CollectionAccessSelectionType

* [AC-1648] [Flexible Collections] Bump migration scripts before feature branch merge (#3371)

* Bump dates on sql migration scripts

* Bump date on ef migrations

* [AC-1696] Rework collection auth handler to account for provider users

- Add additional check for providers only if the org membership is null, and if the user is a provider, do not early return
- Modify conditionals to use pattern matching to allow for null organization contexts from provider users
- Save the target organization id as a private field to avoid additional parameter passing because org can now be null

* [AC-1696] Add unit tests to collection auth handler for provider users

Includes helper test method/enum for creating an xUnit theory for each collection operation.

* [AC-1696] Further refactor private methods and remove provider check from public method

Updates logic in private methods to only use context.Succeed() to allow for fallback permission checking for provider access.

* [AC-1696] Ensure the correct organization id is provided when testing

* [AC-1696] Refactor provider test to remove additional operation enum

* [AC-1696] Formatting

---------

Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
Co-authored-by: Vincent Salucci <26154748+vincentsalucci@users.noreply.github.com>
Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>
2023-11-21 18:09:27 -08:00
github-actions[bot]
636a7646a3
Bumped version to 2023.10.3 (#3462)
Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com>
2023-11-21 11:43:57 -05:00
Matt Bishop
87fd4ad97d
[PM-3569] Upgrade to Duende.Identity (#3185)
* Upgrade to Duende.Identity

* Linting

* Get rid of last IdentityServer4 package

* Fix identity test since Duende returns additional configuration

* Use Configure

PostConfigure is ran after ASP.NET's PostConfigure
so ConfigurationManager was already configured and our HttpHandler wasn't
being respected.

* Regenerate lockfiles

* Move to 6.0.4 for patches

* fixes with testing

* Add additional grant type supported in 6.0.4 and beautify

* Lockfile refresh

* Reapply lockfiles

* Apply change to new WebAuthn logic

* When automated merging fails me

---------

Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
Co-authored-by: Kyle Spearrin <kyle.spearrin@gmail.com>
2023-11-20 16:32:23 -05:00
Alex Morask
03b9136623
Revert "[PM-3892] Implement dollar threshold for all subscriptions (#3283)" (#3455)
This reverts commit d9faa9a6df.
2023-11-20 16:30:48 -05:00
Andreas Coroiu
80740aa4ba
[PM-2032] Server endpoints to support authentication with a passkey (#3361)
* [PM-2032] feat: add assertion options tokenable

* [PM-2032] feat: add request and response models

* [PM-2032] feat: implement `assertion-options` identity endpoint

* [PM-2032] feat: implement authentication with passkey

* [PM-2032] chore: rename to `WebAuthnGrantValidator`

* [PM-2032] fix: add missing subsitute

* [PM-2032] feat: start adding builder

* [PM-2032] feat: add support for KeyConnector

* [PM-2032] feat: add first version of TDE

* [PM-2032] chore: refactor WithSso

* [PM-2023] feat: add support for TDE feature flag

* [PM-2023] feat: add support for approving devices

* [PM-2023] feat: add support for hasManageResetPasswordPermission

* [PM-2032] feat: add support for hasAdminApproval

* [PM-2032] chore: don't supply device if not necessary

* [PM-2032] chore: clean up imports

* [PM-2023] feat: extract interface

* [PM-2023] chore: add clarifying comment

* [PM-2023] feat: use new builder in production code

* [PM-2032] feat: add support for PRF

* [PM-2032] chore: clean-up todos

* [PM-2023] chore: remove token which is no longer used

* [PM-2032] chore: remove todo

* [PM-2032] feat: improve assertion error handling

* [PM-2032] fix: linting issues

* [PM-2032] fix: revert changes to `launchSettings.json`

* [PM-2023] chore: clean up assertion endpoint

* [PM-2032] feat: bypass 2FA

* [PM-2032] fix: rename prf option to singular

* [PM-2032] fix: lint

* [PM-2032] fix: typo

* [PM-2032] chore: improve builder tests

Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com>

* [PM-2032] chore: clarify why we don't require 2FA

* [PM-2023] feat: move `identityProvider` constant to common class

* [PM-2032] fix: lint

* [PM-2023] fix: move `IdentityProvider` to core.Constants

* [PM-2032] fix: missing import

* [PM-2032] chore: refactor token timespan to use `TimeSpan`

* [PM-2032] chore: make `StartWebAuthnLoginAssertion` sync

* [PM-2032] chore: use `FromMinutes`

* [PM-2032] fix: change to 17 minutes to cover webauthn assertion

* [PM-2032] chore: do not use `async void`

* [PM-2032] fix: comment saying wrong amount of minutes

* [PM-2032] feat: put validator behind feature flag

* [PM-2032] fix: lint

---------

Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com>
2023-11-20 15:55:31 +01:00
Alex Morask
07c202ecaf
Block org seat scaling when has Reseller provider (#3385) 2023-11-20 09:05:35 -05:00
Matt Bishop
fb89e07df7
Provide LaunchDarkly application info (#3435)
* Upgrade to SDK v8

* Provide application properties

* Test adjustments

* Clean up tests

* Ensure project name is set

* Add a 'v' for Git tagging support
2023-11-13 14:46:39 -05:00
Jake Fink
b716a925f8
[PM-3797 Part 1] Layout new key rotation methods (#3425)
* layout new key rotation methods
- add endpoint with request model
- add command with data model
- add repository method

* layout new key rotation methods
- add endpoint with request model
- add command with data model
- add repository method

* formatting

* rename account recovery to reset password

* fix tests

* remove extra endpoint

* rename account recovery to reset password

* fix tests and formatting

* register db calls in command, removing list from user repo

* formatting
2023-11-09 14:56:08 -05:00
Daniel James Smith
95680b434b
Update lockfiles by running dotnet restore --force-evaluate (#3430)
Co-authored-by: Daniel James Smith <djsmith85@users.noreply.github.com>
2023-11-09 14:48:18 +01:00
Justin Baur
81868dc5a3
Add Explicit Reference to Azure.Identity (#3426) 2023-11-08 12:58:42 -05:00
Thomas Avery
0ca65e3f9d
[SM-919] Add project people access policy management endpoints (#3285)
* Expose access policy discriminators

* Add people policy model and auth handler

* Add unit tests for authz handler

* Add people policies support in repo

* Add new endpoints and request/response models

* Update tests
2023-11-08 11:42:40 -05:00
Andreas Coroiu
35500b197d
fix: broken webauthn controller tests (#3421) 2023-11-08 14:38:54 +01:00
Andreas Coroiu
e401fc0983
[PM-4167] Add PRF attestation flow during passkey registration (#3339)
* [PM-4167] feat: add support for `SupportsPrf`

* [PM-4167] feat: add `prfStatus` property

* [PM-4167] feat: add support for storing PRF keys

* [PM-4167] fix: allow credentials to be created without encryption support

* [PM-4167] fix: broken test

* [PM-4167] chore: remove whitespace

* [PM-4167] fix: controller test

* [PM-4167] chore: improve readability of `GetPrfStatus`

* [PM-4167] fix: make prf optional

* [PM-4167] fix: commit missing controller change

* [PM-4167] fix: tests
2023-11-07 16:59:51 +01:00
github-actions[bot]
3f7ff52f0b
Bumped version to 2023.10.2 (#3415)
Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com>
2023-11-06 20:21:47 -05:00
Conner Turnbull
3eb4d547a8
[AC-1708] Teams Starter Plan (#3386)
* Upgraded old 2019 plans to have the same features as 2020 and beyond

* Removed redundant test and moved additional test cases to GetByOrgIdAsync_SmNoneFreePlans_ReturnsNull

* Fixed issue where feature flag wasn't returning correct plans

* Added teams 2010 plan

* Reverted accidental change to StripePaymentService

* Split feature flag logic and added some explanatory comments

* Removed families changes

* Resolved issue where Teams Starter could not sign up for a new org with SM enabled

* Fixed issue with signing up for SM with Teams Starter

* Resolved issue where an active plan could increase their SM seat count to be greater than the base seats in the password manager plan

* Updated unit test to ensure Seats are higher than SmSeats

* Resolved issue where getting plans would return a value that LINQ previously cached when feature flag was in a different state
2023-11-03 22:26:47 +00:00
Conner Turnbull
62e99bcaf4
[AC-1578] Fixed issue where legacy plans couldn't sign up for SM (#3400)
* Fixed issue where legacy plans couldn't sign up for SM

* Removed unit test that check to make sure enterprise 2019 couldn't be upgraded to SM
2023-11-03 19:32:30 +00:00
github-actions[bot]
a66528cf46
Bumped version to 2023.10.1 (#3408)
Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com>
2023-11-02 14:21:55 -04:00
Jared Snider
ee618328c0
Auth/PM-3275 - Changes to support TDE User without MP being able to Set a Password + misc refactoring (#3242)
* PM-3275 - Add new GetMasterPasswordPolicy endpoint which will allow authenticated clients to get an enabled MP org policy if it exists for the purposes of enforcing those policy requirements when setting a password.

* PM-3275 - AccountsController.cs - PostSetPasswordAsync - (1) Convert UserService.setPasswordAsync into new SetInitialMasterPasswordCommand (2) Refactor SetInitialMasterPasswordCommand to only accept post SSO users who are in the invited state
(3) Add TODOs for more cleanup work and more commands

* PM-3275 - Update AccountsControllerTests.cs to add new SetInitialMasterPasswordCommand

* PM-3275 - UserService.cs - Remove non implemented ChangePasswordAsync method

* PM-3275 - The new SetInitialMasterPasswordCommand leveraged the OrganizationService.cs AcceptUserAsync method so while I was in here I converted the AcceptUserAsync methods into a new AcceptOrgUserCommand.cs and turned the private method which accepted an existing org user public for use in the SetInitialMasterPasswordCommand

* PM-3275 - Dotnet format

* PM-3275 - Test SetInitialMasterPasswordCommand

* Dotnet format

* PM-3275 - In process AcceptOrgUserCommandTests.cs

* PM-3275 - Migrate changes from AC-244 / #3199 over into new AcceptOrgUserCommand

* PM-3275 - AcceptOrgUserCommand.cs - create data protector specifically for this command

* PM-3275 - Add TODO for renaming / removing overloading of methods to improve readability / clarity

* PM-3275 - AcceptOrgUserCommand.cs - refactor AcceptOrgUserAsync by OrgId to retrieve orgUser with _organizationUserRepository.GetByOrganizationAsync which gets a single user instead of a collection

* PM-3275 - AcceptOrgUserCommand.cs - update name in TODO for evaluation later

* PM-3275 / PM-1196 - (1) Slightly refactor SsoEmail2faSessionTokenable to provide public static GetTokenLifeTime() method for testing (2) Add missed tests to SsoEmail2faSessionTokenable in preparation for building tests for new OrgUserInviteTokenable.cs

* PM-3275 / PM-1196 - Removing SsoEmail2faSessionTokenable.cs changes + tests as I've handled that separately in a new PR (#3270) for newly created task PM-3925

* PM-3275 - ExpiringTokenable.cs - add clarifying comments to help distinguish between the Valid property and the TokenIsValid method.

* PM-3275 - Create OrgUserInviteTokenable.cs and add tests in OrgUserInviteTokenableTests.cs

* PM-3275 - OrganizationService.cs - Refactor Org User Invite methods to use new OrgUserInviteTokenable instead of manual creation of a token

* PM-3275 - OrgUserInviteTokenable.cs - clarify backwards compat note

* PM-3275 - AcceptOrgUserCommand.cs - Add TODOs + minor name refactor

* PM-3275 - AcceptOrgUserCommand.cs - replace method overloading with more easily readable names.

* PM-3275 - AcceptOrgUserCommand.cs - Update ValidateOrgUserInviteToken to add new token validation while maintaining backwards compatibility for 1 release.

* dotnet format

* PM-3275 - AcceptOrgUserCommand.cs - Move private method below where it is used

* PM-3275 - ServiceCollectionExtensions.cs - Must register IDataProtectorTokenFactory<OrgUserInviteTokenable> for new tokenable

* PM-3275 - OrgUserInviteTokenable needed access to global settings to set its token lifetime to the _globalSettings.OrganizationInviteExpirationHours value.  Creating a factory seemed the most straightforward way to encapsulate the desired creation logic. Unsure if in the correct location in ServiceCollectionExtensions.cs but will figure that out later.

* PM-3275 - In process work of creating AcceptOrgUserCommandTests.cs

* PM-3275 - Remove no longer relevant AcceptOrgUser tests from OrganizationServiceTests.cs

* PM-3275 - Register OrgUserInviteTokenableFactory alongside tokenizer

* PM-3275 - AcceptOrgUserCommandTests.cs - AcceptOrgUserAsync basic test suite completed.

* PM-3275 - AcceptOrgUserCommandTests.cs - tweak test names

* PM-3275 - AcceptOrgUserCommandTests.cs - (1) Remove old tests from OrganizationServiceTests as no longer needed to reference (2) Add summary for SetupCommonAcceptOrgUserMocks (3) Get AcceptOrgUserByToken_OldToken_AcceptsUserAndVerifiesEmail passing

* PM-3275 - Create interface for OrgUserInviteTokenableFactory b/c that's the right thing to do + enables test substitution

* PM-3275 - AcceptOrgUserCommandTests.cs - (1) Start work on AcceptOrgUserByToken_NewToken_AcceptsUserAndVerifiesEmail (2) Create and use SetupCommonAcceptOrgUserByTokenMocks() (3) Create generic FakeDataProtectorTokenFactory for tokenable testing

* PM-3275 - (1) Get AcceptOrgUserByToken_NewToken_AcceptsUserAndVerifiesEmail test passing (2) Move FakeDataProtectorTokenFactory to own file

* PM-3275 - AcceptOrgUserCommandTests.cs - Finish up tests for AcceptOrgUserByTokenAsync

* PM-3275 - Add pseudo section comments

* PM-3275 - Clean up unused params on AcceptOrgUserByToken_EmailMismatch_ThrowsBadRequest test

* PM-3275 - (1) Tests written for AcceptOrgUserByOrgSsoIdAsync (2) Refactor happy path assertions into helper function AssertValidAcceptedOrgUser to reduce code duplication

* PM-3275 - Finish up testing AcceptOrgUserCommandTests.cs by adding tests for AcceptOrgUserByOrgIdAsync

* PM-3275 - Tweaking test naming to ensure consistency.

* PM-3275 - Bugfix - OrgUserInviteTokenableFactory implementation required when declaring singleton service in ServiceCollectionExtensions.cs

* PM-3275 - Resolve failing OrganizationServiceTests.cs

* dotnet format

* PM-3275 - PoliciesController.cs - GetMasterPasswordPolicy bugfix - for orgs without a MP policy, policy comes back as null and we should return notFound in that case.

* PM-3275 - Add PoliciesControllerTests.cs specifically for new GetMasterPasswordPolicy(...) endpoint.

* PM-3275 - dotnet format PoliciesControllerTests.cs

* PM-3275 - PoliciesController.cs - (1) Add tech debt task number (2) Properly flag endpoint as deprecated

* PM-3275 - Add new hasManageResetPasswordPermission property to ProfileResponseModel.cs primarily for sync so that we can condition client side if TDE user obtains elevated permissions

* PM-3275 - Fix AccountsControllerTests.cs

* PM-3275 - OrgUserInviteTokenable.cs - clarify TODO

* PM-3275 - AcceptOrgUserCommand.cs - Refactor token validation to use short circuiting to only run old token validation if new token validation fails.

* PM-3275 - OrgUserInviteTokenable.cs - (1) Add new static methods to centralize validation logic to avoid repetition (2) Add new token validation method so we can avoid having to pass in a full org user (and hitting the db to do so)

* PM-3275 - Realized that the old token validation was used in the PoliciesController.cs (existing user clicks invite link in email and goes to log in) and UserService.cs (user clicks invite link in email and registers for a new acct). Added tech debt item for cleaning up backwards compatibility in future.

* dotnet format

* PM-3275 - (1) AccountsController.cs - Update PostSetPasswordAsync SetPasswordRequestModel to allow null keys for the case where we have a TDE user who obtains elevated permissions - they already have a user public and user encrypted private key saved in the db. (2) AccountsControllerTests.cs - test PostSetPasswordAsync scenarios to ensure changes will work as expected.

* PM-3275 - PR review feedback - (1) set CurrentContext to private (2) Refactor GetProfile to use variables to improve clarity and simplify debugging.

* PM-3275 - SyncController.cs - PR Review Feedback - Set current context as private instead of protected.

* PM-3275 - CurrentContextExtensions.cs - PR Feedback - move parenthesis up from own line.

* PM-3275 - SetInitialMasterPasswordCommandTests.cs - Replace unnecessary variable

* PM-3275 - SetInitialMasterPasswordCommandTests.cs - PR Feedback - Add expected outcome statement to test name

* PM-3275 - Set Initial Password command and tests - PR Feedback changes - (1) Rename orgIdentifier --> OrgSsoIdentifier for clarity (2) Update SetInitialMasterPasswordAsync to not allow null orgSsoId with explicit message saying this vs letting null org trigger invalid organization (3) Add test to cover this new scenario.

* PM-3275 - SetInitialMasterPasswordCommand.cs - Move summary from implementation to interface to better respect standards and the fact that the interface is the more seen piece of code.

* PM-3275 - AcceptOrgUserCommand.cs - Per PR feedback, rename AcceptOrgUserByTokenAsync -> AcceptOrgUserByEmailTokenAsync + replace generic name token with emailToken

* PM-3275 - OrganizationService.cs - Per PR feedback, remove dupe line

* PM-3275 - AcceptOrgUserCommand.cs - Per PR feedback, remove new lines in error messages for consistency.

* PM-3275 - SetInitialMasterPasswordCommand.cs - Per PR feedback, adjust formatting of constructor for improved readability.

* PM-3275 - CurrentContextExtensions.cs - Refactor AnyOrgUserHasManageResetPasswordPermission per PR feedback to remove unnecessary var.

* PM-3275 - AcceptOrgUserCommand.cs - Per PR feedback, remove completed TODO

* PM-3275 - PoliciesController.cs - Per PR feedback, update GetByInvitedUser param to be guid instead of string.

* PM-3275 - OrgUserInviteTokenable.cs - per PR feedback, add tech debt item info.

* PM-3275 - AcceptOrgUserCommand.cs - Per PR feedback, use const purpose from tokenable instead of magic string.

* PM-3275 - Restore non duplicate line to fix tests

* PM-3275 - Per PR feedback, revert all sync controller changes as the ProfileResponseModel.organizations array has org objects which have permissions which have the ManageResetPassword permission.  So, I have the information that I need clientside already to determine if the user has the ManageResetPassword in any org.

* PM-3275 - PoliciesControllerTests.cs - Update imports as the PoliciesController was moved under the admin console team's domain.

* PM-3275 - Resolve issues from merge conflict resolutions to get solution building.

* PM-3275 / PM-4633 - PoliciesController.cs - use orgUserId to look up user instead of orgId. Oops.

* Fix user service tests

* Resolve merge conflict
2023-11-02 08:02:25 -07:00
Jared Snider
f5f64059c5
Auth/PM-3659 - Disable Passkey registration if Require SSO Policy Enabled (#3399)
* PM-3659 - WebAuthnController.cs - Passkey Creation - Add RequireSSO login policy validation to prevent users from creating passkeys if require SSO applies to them.

* PM-3659 - per PR feedback, apply new require SSO validation to options call

* PM-3659 - Remove unneeded comment

* PM-3659 - Per PR feedback, add unit tests for new require SSO scenarios on both Post and Options endpoints on the WebAuthnController

* Remove duplicated line

* Remove extra whitespace
2023-11-01 13:39:00 -04:00
Alex Morask
34a3d4a4df
[AC-1593] Auto-Grant SM access to org owner when they add SM (#3349)
* Auto grant SM access to org owner

* Thomas' feedback
2023-11-01 11:05:04 -04:00
cyprain-okeke
d9faa9a6df
[PM-3892] Implement dollar threshold for all subscriptions (#3283)
* Initial commit

* Fix the failing text

* Fix the unpaid invoice issue

* fix the unpaid invoice issue

* Changes for the threshold amount

* remove the billing threshold

* Add some comments to the old method

* Fixing issues on secret manager test

* import missing package

* Resolve pr comments

* Refactor PreviewUpcomingInvoiceAndPayAsync method

* Resolve some pr comments

* Resolving the comment around constant

* Resolve pr comment

* Add new class

* Resolve pr comments

* Change the prorateThreshold from 5 to 500 dollars

* Fix the failing test

* Fix the server returns a 500 error with the banner
2023-11-01 14:19:28 +00:00
Conner Turnbull
f9fc43dbb1
[AC-1650] [AC-1578] (#3320)
* Upgraded old 2019 plans to have the same features as 2020 and beyond

* Removed redundant test and moved additional test cases to GetByOrgIdAsync_SmNoneFreePlans_ReturnsNull

* Fixed issue where feature flag wasn't returning correct plans

* Resolved issue where getting plans would return a value that LINQ previously cached when feature flag was in a different state

---------

Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
2023-11-01 12:43:35 +00:00
Thomas Rittson
da4a86c643
[AC-1373] Flexible Collections (#3245)
* [AC-1117] Add manage permission (#3126)

* Update sql files to add Manage permission

* Add migration script

* Rename collection manage migration file to remove duplicate migration date

* Migrations

* Add manage to models

* Add manage to repository

* Add constraint to Manage columns

* Migration lint fixes

* Add manage to OrganizationUserUserDetails_ReadWithCollectionsById

* Add missing manage fields

* Add 'Manage' to UserCollectionDetails

* Use CREATE OR ALTER where possible

* [AC-1374] Limit collection creation/deletion to Owner/Admin (#3145)

* feat: update org table with new column, write migration, refs AC-1374

* feat: update views with new column, refs AC-1374

* feat: Alter sprocs (org create/update) to include new column, refs AC-1374

* feat: update entity/data/request/response models to handle new column, refs AC-1374

* feat: update necessary Provider related views during migration, refs AC-1374

* fix: update org create to default new column to false, refs AC-1374

* feat: added new API/request model for collection management and removed property from update request model, refs AC-1374

* fix: renamed migration script to be after secrets manage beta column changes, refs AC-1374

* fix: dotnet format, refs AC-1374

* feat: add ef migrations to reflect mssql changes, refs AC-1374

* fix: dotnet format, refs AC-1374

* feat: update API signature to accept Guid and explain Cd verbiage, refs AC-1374

* fix: merge conflict resolution

* [AC-1174] CollectionUser and CollectionGroup authorization handlers (#3194)

* [AC-1174] Introduce BulkAuthorizationHandler.cs

* [AC-1174] Introduce CollectionUserAuthorizationHandler

* [AC-1174] Add CreateForNewCollection CollectionUser requirement

* [AC-1174] Add some more details to CollectionCustomization

* [AC-1174] Formatting

* [AC-1174] Add CollectionGroupOperation.cs

* [AC-1174] Introduce CollectionGroupAuthorizationHandler.cs

* [AC-1174] Cleanup CollectionFixture customization

Implement and use re-usable extension method to support seeded Guids

* [AC-1174] Introduce WithValueFromList AutoFixtureExtensions

Modify CollectionCustomization to use multiple organization Ids for auto generated test data

* [AC-1174] Simplify CollectionUserAuthorizationHandler.cs

Modify the authorization handler to only perform authorization logic. Validation logic will need to be handled by any calling commands/controllers instead.

* [AC-1174] Introduce shared CollectionAccessAuthorizationHandlerBase

A shared base authorization handler was created for both CollectionUser and CollectionGroup resources, as they share the same underlying management authorization logic.

* [AC-1174] Update CollectionUserAuthorizationHandler and CollectionGroupAuthorizationHandler to use the new CollectionAccessAuthorizationHandlerBase class

* [AC-1174] Formatting

* [AC-1174] Cleanup typo and redundant ToList() call

* [AC-1174] Add check for provider users

* [AC-1174] Reduce nested loops

* [AC-1174] Introduce ICollectionAccess.cs

* [AC-1174] Remove individual CollectionGroup and CollectionUser auth handlers and use base class instead

* [AC-1174] Tweak unit test to fail minimally

* [AC-1174] Reorganize authorization handlers in Core project

* [AC-1174] Introduce new AddCoreAuthorizationHandlers() extension method

* [AC-1174] Move CollectionAccessAuthorizationHandler into Api project

* [AC-1174] Move CollectionFixture to Vault folder

* [AC-1174] Rename operation to CreateUpdateDelete

* [AC-1174] Require single organization for collection access authorization handler

- Add requirement that all target collections must belong to the same organization
- Simplify logic related to multiple organizations
- Update tests and helpers
- Use ToHashSet to improve lookup time

* [AC-1174] Fix null reference exception

* [AC-1174] Throw bad request exception when collections belong to different organizations

* [AC-1174] Switch to CollectionAuthorizationHandler instead of CollectionAccessAuthorizationHandler to reduce complexity

* Fix improper merge conflict resolution

* fix: add permission check for collection management api, refs AC-1647 (#3252)

* [AC-1125] Enforce org setting for creating/deleting collections (#3241)

* [AC-1117] Add manage permission (#3126)

* Update sql files to add Manage permission

* Add migration script

* Rename collection manage migration file to remove duplicate migration date

* Migrations

* Add manage to models

* Add manage to repository

* Add constraint to Manage columns

* Migration lint fixes

* Add manage to OrganizationUserUserDetails_ReadWithCollectionsById

* Add missing manage fields

* Add 'Manage' to UserCollectionDetails

* Use CREATE OR ALTER where possible

* [AC-1374] Limit collection creation/deletion to Owner/Admin (#3145)

* feat: update org table with new column, write migration, refs AC-1374

* feat: update views with new column, refs AC-1374

* feat: Alter sprocs (org create/update) to include new column, refs AC-1374

* feat: update entity/data/request/response models to handle new column, refs AC-1374

* feat: update necessary Provider related views during migration, refs AC-1374

* fix: update org create to default new column to false, refs AC-1374

* feat: added new API/request model for collection management and removed property from update request model, refs AC-1374

* fix: renamed migration script to be after secrets manage beta column changes, refs AC-1374

* fix: dotnet format, refs AC-1374

* feat: add ef migrations to reflect mssql changes, refs AC-1374

* fix: dotnet format, refs AC-1374

* feat: update API signature to accept Guid and explain Cd verbiage, refs AC-1374

* feat: created collection auth handler/operations, added LimitCollectionCdOwnerAdmin to CurrentContentOrganization, refs AC-1125

* feat: create vault service collection extensions and register with base services, refs AC-1125

* feat: deprecated CurrentContext.CreateNewCollections, refs AC-1125

* feat: deprecate DeleteAnyCollection for single resource usages, refs AC-1125

* feat: move service registration to api, update references, refs AC-1125

* feat: add bulk delete authorization handler, refs AC-1125

* feat: always assign user and give manage access on create, refs AC-1125

* fix: updated CurrentContextOrganization type, refs AC-1125

* feat: combined existing collection authorization handlers/operations, refs AC-1125

* fix: OrganizationServiceTests -> CurrentContentOrganization typo, refs AC-1125

* fix: format, refs AC-1125

* fix: update collection controller tests, refs AC-1125

* fix: dotnet format, refs AC-1125

* feat: removed extra BulkAuthorizationHandler, refs AC-1125

* fix: dotnet format, refs AC-1125

* fix: change string to guid for org id, update bulk delete request model, refs AC-1125

* fix: remove delete many collection check, refs AC-1125

* fix: clean up collection auth handler, refs AC-1125

* fix: format fix for CollectionOperations, refs AC-1125

* fix: removed unnecessary owner check, add org null check to custom permission validation, refs AC-1125

* fix: remove unused methods in CurrentContext, refs AC-1125

* fix: removed obsolete test, fixed failling delete many test, refs AC-1125

* fix: CollectionAuthorizationHandlerTests fixes, refs AC-1125

* fix: OrganizationServiceTests fix broken test by mocking GetOrganization, refs AC-1125

* fix: CollectionAuthorizationHandler - remove unused repository, refs AC-1125

* feat: moved UserId null check to common method, refs AC-1125

* fix: updated auth handler tests to remove dependency on requirement for common code checks, refs AC-1125

* feat: updated conditionals/comments for create/delete methods within colleciton auth handler, refs AC-1125

* feat: added create/delete collection auth handler success methods, refs AC-1125

* fix: new up permissions to prevent excessive null checks, refs AC-1125

* fix: remove old reference to CreateNewCollections, refs AC-1125

* fix: typo within ViewAssignedCollections method, refs AC-1125

---------

Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>

* refactor: remove organizationId from CollectionBulkDeleteRequestModel, refs AC-1649 (#3282)

* [AC-1174] Bulk Collection Management (#3229)

* [AC-1174] Update SelectionReadOnlyRequestModel to use Guid for Id property

* [AC-1174] Introduce initial bulk-access collection endpoint

* [AC-1174] Introduce BulkAddCollectionAccessCommand and validation logic/tests

* [AC-1174] Add CreateOrUpdateAccessMany method to CollectionRepository

* [AC-1174] Add event logs for bulk add collection access command

* [AC-1174] Add User_BumpAccountRevisionDateByCollectionIds and database migration script

* [AC-1174] Implement EF repository method

* [AC-1174] Improve null checks

* [AC-1174] Remove unnecessary BulkCollectionAccessRequestModel helpers

* [AC-1174] Add unit tests for new controller endpoint

* [AC-1174] Fix formatting

* [AC-1174] Remove comment

* [AC-1174] Remove redundant organizationId parameter

* [AC-1174] Ensure user and group Ids are distinct

* [AC-1174] Cleanup tests based on PR feedback

* [AC-1174] Formatting

* [AC-1174] Update CollectionGroup alias in the sproc

* [AC-1174] Add some additional comments to SQL sproc

* [AC-1174] Add comment explaining additional SaveChangesAsync call

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* [AC-1646] Rename LimitCollectionCdOwnerAdmin column (#3300)

* Rename LimitCollectionCdOwnerAdmin -> LimitCollectionCreationDeletion

* Rename and bump migration script

* [AC-1666] Removed EditAnyCollection from Create/Delete permission checks (#3301)

* fix: remove EditAnyCollection from Create/Delete permission check, refs AC-1666

* fix: updated comment, refs AC-1666

* [AC-1669] Bug - Remove obsolete assignUserId from CollectionService.SaveAsync(...) (#3312)

* fix: remove AssignUserId from CollectionService.SaveAsync, refs AC-1669

* fix: add manage access conditional before creating collection, refs AC-1669

* fix: move access logic for create/update, fix all tests, refs AC-1669

* fix: add CollectionAccessSelection fixture, update tests, update bad reqeuest message, refs AC-1669

* fix: format, refs AC-1669

* fix: update null params with specific arg.is null checks, refs Ac-1669

* fix: update attribute class name, refs AC-1669

* [AC-1713] [Flexible collections] Add feature flags to server (#3334)

* Add feature flags for FlexibleCollections and BulkCollectionAccess

* Flag new routes and behaviour

---------

Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>

* Add joint codeownership for auth handlers (#3346)

* [AC-1717] Update default values for LimitCollectionCreationDeletion (#3365)

* Change default value in organization create sproc to 1

* Drop old column name still present in some QA instances

* Set LimitCollectionCreationDeletion value in code based on feature flag

* Fix: add missing namespace after merging in master

* Fix: add missing namespace after merging in master

* [AC-1683] Fix DB migrations for new Manage permission (#3307)

* [AC-1683] Update migration script and introduce V2 procedures and types

* [AC-1683] Update repository calls to use new V2 procedures / types

* [AC-1684] Update bulk add collection migration script to use new V2 type

* [AC-1683] Undo Manage changes to more original procedures

* [AC-1683] Restore whitespace changes

* [AC-1683] Clarify comments regarding explicit column lists

* [AC-1683] Update migration script dates

* [AC-1683] Split the migration script for readability

* [AC-1683] Re-name SelectReadOnlyArray_V2 to CollectionAccessSelectionType

* [AC-1648] [Flexible Collections] Bump migration scripts before feature branch merge (#3371)

* Bump dates on sql migration scripts

* Bump date on ef migrations

---------

Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
Co-authored-by: Vincent Salucci <26154748+vincentsalucci@users.noreply.github.com>
Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com>
Co-authored-by: Shane Melton <smelton@bitwarden.com>
Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>
2023-11-01 09:30:52 +00:00
github-actions[bot]
1800e6ffd3
Bumped version to 2023.10.0 (#3396)
Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com>
2023-10-31 09:32:34 -04:00
Kyle Spearrin
44c559c723
Support for passkey registration (#2885)
* support for fido2 auth

* stub out registration implementations

* stub out assertion steps and token issuance

* verify token

* webauthn tokenable

* remove duplicate expiration set

* revert sqlproj changes

* update sqlproj target framework

* update new validator signature

* [PM-2014] Passkey registration (#2915)

* [PM-2014] chore: rename `IWebAuthnRespository` to `IWebAuthnCredentialRepository`

* [PM-2014] fix: add missing service registration

* [PM-2014] feat: add user verification when fetching options

* [PM-2014] feat: create migration script for mssql

* [PM-2014] chore: append to todo comment

* [PM-2014] feat: add support for creation token

* [PM-2014] feat: implement credential saving

* [PM-2014] chore: add resident key TODO comment

* [PM-2014] feat: implement passkey listing

* [PM-2014] feat: implement deletion without user verification

* [PM-2014] feat: add user verification to delete

* [PM-2014] feat: implement passkey limit

* [PM-2014] chore: clean up todo comments

* [PM-2014] fix: add missing sql scripts

Missed staging them when commiting

* [PM-2014] feat: include options response model in swagger docs

* [PM-2014] chore: move properties after ctor

* [PM-2014] feat: use `Guid` directly as input paramter

* [PM-2014] feat: use nullable guid in token

* [PM-2014] chore: add new-line

* [PM-2014] feat: add support for feature flag

* [PM-2014] feat: start adding controller tests

* [PM-2014] feat: add user verification test

* [PM-2014] feat: add controller tests for token interaction

* [PM-2014] feat: add tokenable tests

* [PM-2014] chore: clean up commented premium check

* [PM-2014] feat: add user service test for credential limit

* [PM-2014] fix: run `dotnet format`

* [PM-2014] chore: remove trailing comma

* [PM-2014] chore: add `Async` suffix

* [PM-2014] chore: move delay to constant

* [PM-2014] chore: change `default` to `null`

* [PM-2014] chore: remove autogenerated weirdness

* [PM-2014] fix: lint

* Added check for PasswordlessLogin feature flag on new controller and methods. (#3284)

* Added check for PasswordlessLogin feature flag on new controller and methods.

* fix: build error from missing constructor argument

---------

Co-authored-by: Andreas Coroiu <andreas.coroiu@gmail.com>

* [PM-4171] Update DB to support PRF (#3321)

* [PM-4171] feat: update database to support PRF

* [PM-4171] feat: rename `DescriptorId` to `CredentialId`

* [PM-4171] feat: add PRF felds to domain object

* [PM-4171] feat: add `SupportsPrf` column

* [PM-4171] fix: add missing comma

* [PM-4171] fix: add comma

* [PM-3263] fix identity server tests for passkey registration (#3331)

* Added WebAuthnRepo to EF DI

* updated config to match current grant types

* Remove ExtensionGrantValidator (#3363)

* Linting

---------

Co-authored-by: Andreas Coroiu <acoroiu@bitwarden.com>
Co-authored-by: Andreas Coroiu <andreas.coroiu@gmail.com>
Co-authored-by: Todd Martin <106564991+trmartin4@users.noreply.github.com>
Co-authored-by: Ike <137194738+ike-kottlowski@users.noreply.github.com>
Co-authored-by: Todd Martin <tmartin@bitwarden.com>
2023-10-30 09:40:06 -04:00
Thomas Avery
1053f49fb1
[SM-943] [BEEEP] Swap to SQLite in-memory for integration tests (#3292)
* Swap to sqlite in-memory for integration tests

* Fix integration tests

* Remove EF Core in-memory dependency
2023-10-27 11:13:52 -05:00
Thomas Rittson
ad230fb6a5
[AC-1200] Admin Console code ownership - move OrganizationFeatures (#3369) 2023-10-26 16:47:44 -05:00
Thomas Rittson
26dd8b0e47
[AC-1284] AC Team code ownership moves - Provider (#3359) 2023-10-26 13:38:29 -04:00
Alex Morask
9007aa6556
Fix broken test (#3374) 2023-10-24 08:44:37 -04:00
Alex Morask
c442bae2bc
[AC-1693] Send InvoiceUpcoming Notification to Client Owners (#3319)
* Add Organization_ReadOwnerEmailAddresses SPROC

* Add IOrganizationRepository.GetOwnerEmailAddressesById

* Add SendInvoiceUpcoming overload for multiple emails

* Update InvoiceUpcoming handler to send multiple emails

* Cy's feedback

* Updates from testing

Hardened against missing entity IDs in Stripe events in the StripeEventService. Updated ValidateCloudRegion to not use a refresh/expansion for the customer because the invoice.upcoming event does not have an invoice.Id. Updated the StripeController's handling of invoice.upcoming to not use a refresh/expansion for the subscription because the invoice does not have an ID.

* Fix broken test
2023-10-23 13:46:29 -04:00
cyprain-okeke
d7c544a116
[AC 1536] Breakdown The SubscriptionUpdate.cs into multiple files (#3356)
* Move sub-subscription classes to a separate files

* Refactor the sub-class to a separate files

* format whitespace

* remove directive that is unnecessary

* Remove the baseSeat class
2023-10-23 11:28:13 +01:00
Thomas Avery
728cd1c0b5
[SM-949] Add endpoint to fetch events by service account (#3336)
* Add ability to fetch events by service account

* Extract GetDateRange into ApiHelpers util

* Add dapper implementation

* Add EF repo implementation

* Add authz handler case

* unit + integration tests for controller

* swap to read check

* Adding comments

* Fix integration tests from merge

* Enabled SM events controller for self-hosting
2023-10-19 16:57:14 -05:00
Thomas Rittson
c1cf07d764
[AC-1750] AC Team code ownership moves - Groups (#3358) 2023-10-20 06:37:46 +10:00
Thomas Rittson
37e9d70bee
AC Team code ownership moves - Api project (#3351) 2023-10-18 11:27:56 -04:00
Thomas Rittson
d230b10f82
Fix flaky UpdateSecretsManagerSubscriptionCommandTests (#3355)
Fix flaky UpdateSubscriptionAsync_ThrowsBadRequestException_WhenOccupiedSeatsExceedNewSeatTotal
test by expressly setting SmSeat value instead of relying on autodata.
This ensures that the new smSeat value is actually different.
2023-10-18 10:00:55 -05:00
Rui Tomé
21219262a2
[PM-3779] idor allow the attacker to delete the victim domain (#3308)
* [PM-3779] Added IOrganizationDomainRepository.GetDomainByIdAndOrganizationIdAsync and SQL stored procedure

* [PM-3779] Changed GetOrganizationDomainByIdQuery to also take OrgId as a parameter. Updated existing unit tests and added new. Updated controller to match command changes

* [PM-3779] Removed type from url routes

* [PM-3779] Renamed IGetOrganizationDomainByIdAndOrganizationIdQuery to IGetOrganizationDomainByIdOrganizationIdQuery

* [PM-3779] Renamed GetOrganizationDomainByIdOrganizationIdQueryTests file and added more tests
2023-10-18 11:57:59 +01:00
Rui Tomé
cb73056c42
[AC-1654] idor allow the attacker to disable any one scim provising (#3325)
* [AC-1654] Added IOrganizationConnectionRepository.GetByIdOrganizationIdAsync and modified OrganizationConnectionsController to use it to get a connection matching both Id and OrganizationId

* [AC-1654] Fixed unit tests
2023-10-18 11:39:00 +01:00
cyprain-okeke
8177821e8b
[AC 1451] Refactor staticstore plans and consuming logic (#3164)
* refactor the plan and create new objects

* initial commit

* Add new plan types

* continue the refactoring by adding new plantypes

* changes for plans

* Refactoring continues

* making changes for plan

* Fixing the failing test

* Fixing  whitespace

* Fix some in correct values

* Resolve the plan data

* rearranging the plan

* Make the plan more immutable

* Resolve the lint errors

* Fix the failing test

* Add custom plan

* Fix the failing test

* Fix the failing test

* resolve the failing addons after refactoring

* Refactoring

* Merge branch 'master' into ac-1451/refactor-staticstore-plans-and-consuming-logic

* merge from master

* Merge branch 'master' into ac-1451/refactor-staticstore-plans-and-consuming-logic

* format whitespace

* resolve the conflict

* Fix some pr comments

* Fixing some of the pr comments

* fixing some of the pr comments

* Resolve some pr comments

* Resolve pr comments

* Resolves some pr comments

* Resolving some or comments

* Resolve a failing test

* fix the failing test

* Resolving some pr comments

* Fix the failing test

* resolve pr comment

* add a using statement fir a failing test

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
2023-10-17 15:56:35 +01:00
cd-bitwarden
b772784af3
[SM-896] restricting access to disabled orgs (#3287)
* restricting access to disabled orgs

* Unit Test Updates

* Update test/Api.IntegrationTest/SecretsManager/Controllers/AccessPoliciesControllerTests.cs

Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>

* Covering all test cases

* making organization enabled NOT default

---------

Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>
2023-10-16 14:29:02 +00:00
Oscar Hinton
27314ac375
Add identity tests to test solution (#3342) 2023-10-13 14:15:11 +02:00
Thomas Rittson
53f5eee215
[AC-1638] Disallow Secrets Manager for MSP-managed organizations (#3297)
* Block MSPs from creating orgs with SM

* Block MSPs from adding SM to a managed org

* Prevent manually adding SM to an MSP-managed org

* Revert "Prevent manually adding SM to an MSP-managed org"

This change is no longer required

This reverts commit 51b086243b.

* Block provider from adding org with SM

* Update error message when adding existing org with SM to provider

* Update check to match client

* Revert "Update check to match client"

This reverts commit f195c1c1f6.
2023-10-12 15:56:50 +01:00
Justin Baur
79648b311e
[PM-3555] Remove ClearTracker() (#3213)
* Remove ClearTracker

* Remove from CipherRepositoryTests
2023-10-12 11:15:02 +02:00
Alex Morask
b2af73f00f
[PM-212] Sync Organization Billing Email from Stripe Webhook (#3305)
* Add StripeFacade and StripeEventService

* Add StripeEventServiceTests

* Handle customer.updated event in StripeController
2023-10-11 15:57:51 -04:00
Conner Turnbull
90d600db9d
[PM-2961] Upgrade Braintree (#3206)
* Upgraded Braintree to 5.19.0

* Force evaluate of nuget packages

---------

Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
2023-09-20 14:11:29 -04:00
Oscar Hinton
8b30b3c7fd
Refresh lockfiles (#3274) 2023-09-15 15:49:34 -04:00
Jared Snider
227178980a
PM-3925 - Tech Debt - Add missed tests for SSO Email 2FA Tokenable (#3270)
* PM-3925 - (1) Slightly refactor SsoEmail2faSessionTokenable to provide public static GetTokenLifeTime() method for testing  (2) Add missed tests to SsoEmail2faSessionTokenable

* PM-3925 - Take into account PR feedback
2023-09-15 14:54:52 -04:00
Jake Fink
f909563211
[PM-3487] prevent account enumeration on auth request endpoint (#3239) 2023-09-11 10:23:32 -04:00
Thomas Avery
4b482f0a34
[SM-918] Enforce project maximums on import (#3253)
* Refactor MaxProjectsQuery for multiple adds

* Update unit tests

* Add max project enforcement to imports
2023-09-07 17:51:35 -05:00
Rui Tomé
721c18e94a
[AC-244] Consider a user's email as verified when they accept an organization invitation via the email link (#3199)
* [AC-244] Saving User.EmailVerified = true when accepting organization invite

* [AC-244] Added unit tests

* [AC-244] Added the parameter 'verifyEmail' to OrganizationService.AcceptUserAsync

* [AC-244] Refactored unit tests

* [AC-244] Fixed failing unit tests

* [AC-244] Marking email as verified only in the endpoint for accepting an invite with a token

* Update src/Core/Services/IOrganizationService.cs

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* [AC-244] Marking email as verified only if it was not

* [AC-244] Updated unit test to have the user's email unverified at the start

* [AC-244] dotnet format

---------

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com>
2023-09-07 14:36:54 +01:00
Thomas Rittson
4d0630081a
Fix flaky OrganizationService tests (#3246)
Set up test data more explicitly instead of relying on AutoData
2023-09-05 06:32:47 +10:00
Matt Bishop
d0cf8204c7
[PM-3708] Allow local overrides for flag values (#3243)
* Allow local overrides for flag values

* Rename helper method
2023-09-01 07:06:21 -04:00
Rui Tomé
c271e2dae2
[PM-3177] Extract IOrganizationService.UpdateUserGroupsAsync to a command (#3131)
* [AC-1423] Add AddonProduct and BitwardenProduct properties to BillingSubscriptionItem (#3037)

* [AC-1423] Add AddonProduct and BitwardenProduct properties to BillingSubscriptionItem

- Add a helper method to determine the appropriate addon type based on the subscription items StripeId

* [AC-1423] Add helper to StaticStore.cs to find a Plan by StripePlanId

* [AC-1423] Use the helper method to set SubscriptionInfo.BitwardenProduct

* Add SecretsManagerBilling feature flag to Constants

* [AC 1409] Secrets Manager Subscription Stripe Integration  (#3019)

* Adding the Secret manager to the Plan List

* Adding the unit test for the StaticStoreTests class

* Fix whitespace formatting

* Fix whitespace formatting

* Price update

* Resolving the PR comments

* Resolving PR comments

* Fixing the whitespace

* only password manager plans are return for now

* format whitespace

* Resolve the test issue

* Fixing the failing test

* Refactoring the Plan separation

* add a unit test for SingleOrDefault

* Fix the whitespace format

* Separate the PM and SM plans

* Fixing the whitespace

* Remove unnecessary directive

* Fix imports ordering

* Fix imports ordering

* Resolve imports ordering

* Fixing imports ordering

* Fix response model, add MaxProjects

* Fix filename

* Fix format

* Fix: seat price should match annual/monthly

* Fix service account annual pricing

* Changes for secret manager signup and upgradeplan

* Changes for secrets manager signup and upgrade

* refactoring the code

* Format whitespace

* remove unnecessary using directive

* Resolve the PR comment on Subscription creation

* Resolve PR comment

* Add password manager to the error message

* Add UseSecretsManager to the event log

* Resolve PR comment on plan validation

* Resolving pr comments for service account count

* Resolving pr comments for service account count

* Resolve the pr comments

* Remove the store procedure that is no-longer needed

* Rename a property properly

* Resolving the PR comment

* Resolve PR comments

* Resolving PR comments

* Resolving the Pr comments

* Resolving some PR comments

* Resolving the PR comments

* Resolving the build identity build

* Add additional Validation

* Resolve the Lint issues

* remove unnecessary using directive

* Remove the white spaces

* Adding unit test for the stripe payment

* Remove the incomplete test

* Fixing the failing test

* Fix the failing test

* Fix the fail test on organization service

* Fix the failing unit test

* Fix the whitespace format

* Fix the failing test

* Fix the whitespace format

* resolve pr comments

* Fix the lint message

* Resolve the PR comments

* resolve pr comments

* Resolve pr comments

* Resolve the pr comments

* remove unused code

* Added for sm validation test

* Fix the whitespace format issues

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* SM-802: Add SecretsManagerBetaColumn SQL migration and Org table update

* SM-802: Run EF Migrations for SecretsManagerBeta

* SM-802: Update the two Org procs and View, and move data migration to a separate file

* SM-802: Add missing comma to Organization_Create

* [AC-1418] Add missing SecretsManagerPlan property to OrganizationResponseModel (#3055)

* SM-802: Remove extra GO statement from data migration script

* [AC 1460] Update Stripe Configuration (#3070)

* change the stripeseat id

* change service accountId to align with new product

* make all the Id name for consistent

* SM-802: Add SecretsManagerBeta to OrganizationResponseModel

* SM-802: Move SecretsManagerBeta from OrganizationResponseModel to OrganizationSubscriptionResponseModel. Use sp_refreshview instead of sp_refreshsqlmodule in the migration script.

* SM-802: Remove OrganizationUserOrganizationDetailsView.sql changes

* [AC 1410] Secrets Manager subscription adjustment back-end changes (#3036)

* Create UpgradeSecretsManagerSubscription command

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* SM-802: Remove SecretsManagerBetaColumn migration

* SM-802: Add SecretsManagerBetaColumn migration

* SM-802: Remove OrganizationUserOrganizationDetailsView update

* [AC-1495] Extract UpgradePlanAsync into a command (#3081)

* This is a pure lift & shift with no refactors

* Only register subscription commands in Api

---------

Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>

* [AC-1503] Fix Stripe integration on organization upgrade (#3084)

* Fix SM parameters not being passed to Stripe

* Fix flaky test

* Fix error message

* [AC-1504] Allow SM max autoscale limits to be disabled (#3085)

* [AC-1488] Changed SM Signup and Upgrade paths to set SmServiceAccounts to include the plan BaseServiceAccount (#3086)

* [AC-1510] Enable access to Secrets Manager to Organization owner for new Subscription (#3089)

* Revert changes to ReferenceEvent code (#3091)

* Revert changes to ReferenceEvent code

This will be done in AC-1481

* Revert ReferenceEventType change

* Move NoopServiceAccountRepository to SM and update namespace

* [AC-1462] Add secrets manager service accounts autoscaling commands (#3059)

* Adding the Secret manager to the Plan List

* Adding the unit test for the StaticStoreTests class

* Fix whitespace formatting

* Fix whitespace formatting

* Price update

* Resolving the PR comments

* Resolving PR comments

* Fixing the whitespace

* only password manager plans are return for now

* format whitespace

* Resolve the test issue

* Fixing the failing test

* Refactoring the Plan separation

* add a unit test for SingleOrDefault

* Fix the whitespace format

* Separate the PM and SM plans

* Fixing the whitespace

* Remove unnecessary directive

* Fix imports ordering

* Fix imports ordering

* Resolve imports ordering

* Fixing imports ordering

* Fix response model, add MaxProjects

* Fix filename

* Fix format

* Fix: seat price should match annual/monthly

* Fix service account annual pricing

* Changes for secret manager signup and upgradeplan

* Changes for secrets manager signup and upgrade

* refactoring the code

* Format whitespace

* remove unnecessary using directive

* Changes for subscription Update

* Update the seatAdjustment and update

* Resolve the PR comment on Subscription creation

* Resolve PR comment

* Add password manager to the error message

* Add UseSecretsManager to the event log

* Resolve PR comment on plan validation

* Resolving pr comments for service account count

* Resolving pr comments for service account count

* Resolve the pr comments

* Remove the store procedure that is no-longer needed

* Add a new class for update subscription

* Modify the Update subscription for sm

* Add the missing property

* Rename a property properly

* Resolving the PR comment

* Resolve PR comments

* Resolving PR comments

* Resolving the Pr comments

* Resolving some PR comments

* Resolving the PR comments

* Resolving the build identity build

* Add additional Validation

* Resolve the Lint issues

* remove unnecessary using directive

* Remove the white spaces

* Adding unit test for the stripe payment

* Remove the incomplete test

* Fixing the failing test

* Fix the failing test

* Fix the fail test on organization service

* Fix the failing unit test

* Fix the whitespace format

* Fix the failing test

* Fix the whitespace format

* resolve pr comments

* Fix the lint message

* refactor the code

* Fix the failing Test

* adding a new endpoint

* Remove the unwanted code

* Changes for Command and Queries

* changes for command and queries

* Fix the Lint issues

* Fix imports ordering

* Resolve the PR comments

* resolve pr comments

* Resolve pr comments

* Fix the failing test on adjustSeatscommandtests

* Fix the failing test

* Fix the whitespaces

* resolve failing test

* rename a property

* Resolve the pr comments

* refactoring the existing implementation

* Resolve the whitespaces format issue

* Resolve the pr comments

* [AC-1462] Created IAvailableServiceAccountsQuery along its implementation and with unit tests

* [AC-1462] Renamed ICountNewServiceAccountSlotsRequiredQuery

* [AC-1462] Added IAutoscaleServiceAccountsCommand and implementation

* Add more unit testing

* fix the whitespaces issues

* [AC-1462] Added unit tests for AutoscaleServiceAccountsCommand

* Add more unit test

* Remove unnecessary directive

* Resolve some pr comments

* Adding more unit test

* adding more test

* add more test

* Resolving some pr comments

* Resolving some pr comments

* Resolving some pr comments

* resolve some pr comments

* Resolving pr comments

* remove whitespaces

* remove white spaces

* Resolving pr comments

* resolving pr comments and fixing white spaces

* resolving the lint error

* Run dotnet format

* resolving the pr comments

* Add a missing properties to plan response model

* Add the email sender for sm seat and service acct

* Add the email sender for sm seat and service acct

* Fix the failing test after email sender changes

* Add staticstorewrapper to properly test the plans

* Add more test and validate the existing test

* Fix the white spaces issues

* Remove staticstorewrapper and fix the test

* fix a null issue on autoscaling

* Suggestion: do all seat calculations in update model

* Resolve some pr comments

* resolving some pr comments

* Return value is unnecessary

* Resolve the failing test

* resolve pr comments

* Resolve the pr comments

* Resolving admin api failure and adding more test

* Resolve the issue failing admin project

* Fixing the failed test

* Clarify naming and add comments

* Clarify naming conventions

* Dotnet format

* Fix the failing dependency

* remove similar test

* [AC-1462] Rewrote AutoscaleServiceAccountsCommand to use UpdateSecretsManagerSubscriptionCommand which has the same logic

* [AC-1462] Deleted IAutoscaleServiceAccountsCommand as the logic will be moved to UpdateSecretsManagerSubscriptionCommand

* [AC-1462] Created method AdjustSecretsManagerServiceAccountsAsync

* [AC-1462] Changed SecretsManagerSubscriptionUpdate to only be set by its constructor

* [AC-1462] Added check to CountNewServiceAccountSlotsRequiredQuery and revised unit tests

* [AC-1462] Revised logic for CountNewServiceAccountSlotsRequiredQuery and fixed unit tests

* [AC-1462] Changed SecretsManagerSubscriptionUpdate to receive Organization as a parameter and fixed the unit tests

* [AC-1462] Renamed IUpdateSecretsManagerSubscriptionCommand methods UpdateSubscriptionAsync and AdjustServiceAccountsAsync

* [AC-1462] Rewrote unit test UpdateSubscriptionAsync_ValidInput_Passes

* [AC-1462] Registered CountNewServiceAccountSlotsRequiredQuery for dependency injection

* [AC-1462] Added parameter names to SecretsManagerSubscriptionUpdateRequestModel

* [AC-1462] Updated SecretsManagerSubscriptionUpdate logic to handle null parameters. Revised the unit tests to test null values

---------

Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* Add UsePasswordManager to sync data (#3114)

* [AC-1522] Fix service account check on upgrading (#3111)

* Create new query and add to save orgUser flow

* Add tests

* Resolved the checkmarx issues

* [AC-1521] Address checkmarx security feedback (#3124)

* Reinstate target attribute but add noopener noreferrer

* Make same updates to service account adjustment code

* Wire up to BulkEnableSecretsManager, delete separate command

* Register new query

* WIP: autoscaling in invite user flow

* Resolve dependency issues

* circular dependency between OrganizationService and
  UpdateSecretsManagerSubscriptionCommand - fixed by temporarily
  duplicating ReplaceAndUpdateCache

* Unresolvable dependencies in other services - fixed by temporarily
  registering noop services and moving around some DI code

All should be resolved in PM-1880

* fix using refs

* Update date on migration script

* Remove unused constant

* Revert "Remove unused constant"

This reverts commit 4fcb9da4d6.

This is required to make feature flags work on the client

* Fix tests

* Refactor: fix the update object and use it to adjust values

* [PM-3177] Created OrganizationUserCommand and UpdateOrganizationUserGroupsCommand

* [PM-3177] Added unit tests for UpdateOrganizationUserGroupsCommand

* [PM-3177] Replaced IOrganizationService.UpdateUserGroupsAsync with IUpdateOrganizationUserGroupsCommand

* [AC-1458] Add Endpoint And Service Logic for secrets manager to existing subscription (#3087)

---------

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* Handle autoscaling-specific errors

* Revert name change to method

* Fix typo

* Exclude beta users from seat limits

* Fix inaccurate comment

* Update nullable properties to use .Value accessor

* Fix tests

* Add missing awaits

* Move early return up

* Revert based on currentOrganization

* Remove duplicate migrations from incorrectly resolved merge

* Add tests

* [PM-3177] Remove Admin project referencing Commercial.Infrastructure.EntityFramework

* [PM-3177] Removed abstract class OrganizationUserCommand. Added ValidateOrganizationUserUpdatePermissions to IOrganizationService

---------

Co-authored-by: Shane Melton <smelton@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Colton Hurst <colton@coltonhurst.com>
Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Conner Turnbull <cturnbull@bitwarden.com>
2023-09-01 09:10:02 +01:00
Rui Tomé
e679d3127a
[AC-1585] Automatically verify managed members on an organization with a verified domain (#3207) 2023-08-30 07:23:45 +01:00
Thomas Avery
a1d227c121
[SM-895] Enforce project maximums (#3214)
* Add ProjectLimitQuery

* Add query to DI

* Add unit tests

* Add query to controller

* Add controller unit tests

* add integration tests

* rename query and variables

* More renaming
2023-08-28 12:34:37 -05:00
Thomas Avery
640cb68d51
[SM-863] Add endpoint for fetching multiple secrets by IDs (#3134)
* Add support CanReadSecret authorization

* Extract base response model for secret

* Add support for SA bulk fetching event logging

* secret repository bug fix

* Add endpoint and request for bulk fetching secrets

* Swap to original reference event

* Add unit tests

* Add integration tests

* Add unit tests for authz handler

* update authz handler tests

---------
2023-08-28 10:16:50 -05:00
Thomas Rittson
8de9f4d10d
Fix flaky OrganizationService test (#3232) 2023-08-28 08:01:00 +01:00
Thomas Rittson
4d59dd4a6b
Fix typo: CurrentContent -> CurrentContext (#3231) 2023-08-28 10:20:01 +10:00
Thomas Rittson
4748b5b3fc
[AC-1568] Finish refactor of update subscription interface, minor fixes (#3189)
* Remove UpdateSecretsManagerSubscriptionCommand.AdjustServiceAccounts interface

* Rewrite tests and use autofixture customizations

* Reduce method nesting in the command, simplify parameters

* Fix capitalization and wording of error messages

* Add checks for existing SM beta enrolment etc
2023-08-28 08:05:23 +10:00
Rui Tomé
4c77f993e5
[AC-108] Enterprise policies are not removed when downgraded to teams (#3168)
* [AC-1423] Add AddonProduct and BitwardenProduct properties to BillingSubscriptionItem (#3037)

* [AC-1423] Add AddonProduct and BitwardenProduct properties to BillingSubscriptionItem

- Add a helper method to determine the appropriate addon type based on the subscription items StripeId

* [AC-1423] Add helper to StaticStore.cs to find a Plan by StripePlanId

* [AC-1423] Use the helper method to set SubscriptionInfo.BitwardenProduct

* Add SecretsManagerBilling feature flag to Constants

* [AC 1409] Secrets Manager Subscription Stripe Integration  (#3019)

* Adding the Secret manager to the Plan List

* Adding the unit test for the StaticStoreTests class

* Fix whitespace formatting

* Fix whitespace formatting

* Price update

* Resolving the PR comments

* Resolving PR comments

* Fixing the whitespace

* only password manager plans are return for now

* format whitespace

* Resolve the test issue

* Fixing the failing test

* Refactoring the Plan separation

* add a unit test for SingleOrDefault

* Fix the whitespace format

* Separate the PM and SM plans

* Fixing the whitespace

* Remove unnecessary directive

* Fix imports ordering

* Fix imports ordering

* Resolve imports ordering

* Fixing imports ordering

* Fix response model, add MaxProjects

* Fix filename

* Fix format

* Fix: seat price should match annual/monthly

* Fix service account annual pricing

* Changes for secret manager signup and upgradeplan

* Changes for secrets manager signup and upgrade

* refactoring the code

* Format whitespace

* remove unnecessary using directive

* Resolve the PR comment on Subscription creation

* Resolve PR comment

* Add password manager to the error message

* Add UseSecretsManager to the event log

* Resolve PR comment on plan validation

* Resolving pr comments for service account count

* Resolving pr comments for service account count

* Resolve the pr comments

* Remove the store procedure that is no-longer needed

* Rename a property properly

* Resolving the PR comment

* Resolve PR comments

* Resolving PR comments

* Resolving the Pr comments

* Resolving some PR comments

* Resolving the PR comments

* Resolving the build identity build

* Add additional Validation

* Resolve the Lint issues

* remove unnecessary using directive

* Remove the white spaces

* Adding unit test for the stripe payment

* Remove the incomplete test

* Fixing the failing test

* Fix the failing test

* Fix the fail test on organization service

* Fix the failing unit test

* Fix the whitespace format

* Fix the failing test

* Fix the whitespace format

* resolve pr comments

* Fix the lint message

* Resolve the PR comments

* resolve pr comments

* Resolve pr comments

* Resolve the pr comments

* remove unused code

* Added for sm validation test

* Fix the whitespace format issues

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* SM-802: Add SecretsManagerBetaColumn SQL migration and Org table update

* SM-802: Run EF Migrations for SecretsManagerBeta

* SM-802: Update the two Org procs and View, and move data migration to a separate file

* SM-802: Add missing comma to Organization_Create

* [AC-1418] Add missing SecretsManagerPlan property to OrganizationResponseModel (#3055)

* SM-802: Remove extra GO statement from data migration script

* [AC 1460] Update Stripe Configuration (#3070)

* change the stripeseat id

* change service accountId to align with new product

* make all the Id name for consistent

* SM-802: Add SecretsManagerBeta to OrganizationResponseModel

* SM-802: Move SecretsManagerBeta from OrganizationResponseModel to OrganizationSubscriptionResponseModel. Use sp_refreshview instead of sp_refreshsqlmodule in the migration script.

* SM-802: Remove OrganizationUserOrganizationDetailsView.sql changes

* [AC 1410] Secrets Manager subscription adjustment back-end changes (#3036)

* Create UpgradeSecretsManagerSubscription command

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* SM-802: Remove SecretsManagerBetaColumn migration

* SM-802: Add SecretsManagerBetaColumn migration

* SM-802: Remove OrganizationUserOrganizationDetailsView update

* [AC-1495] Extract UpgradePlanAsync into a command (#3081)

* This is a pure lift & shift with no refactors

* Only register subscription commands in Api

---------

Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>

* [AC-1503] Fix Stripe integration on organization upgrade (#3084)

* Fix SM parameters not being passed to Stripe

* Fix flaky test

* Fix error message

* [AC-1504] Allow SM max autoscale limits to be disabled (#3085)

* [AC-1488] Changed SM Signup and Upgrade paths to set SmServiceAccounts to include the plan BaseServiceAccount (#3086)

* [AC-1510] Enable access to Secrets Manager to Organization owner for new Subscription (#3089)

* Revert changes to ReferenceEvent code (#3091)

* Revert changes to ReferenceEvent code

This will be done in AC-1481

* Revert ReferenceEventType change

* Move NoopServiceAccountRepository to SM and update namespace

* [AC-1462] Add secrets manager service accounts autoscaling commands (#3059)

* Adding the Secret manager to the Plan List

* Adding the unit test for the StaticStoreTests class

* Fix whitespace formatting

* Fix whitespace formatting

* Price update

* Resolving the PR comments

* Resolving PR comments

* Fixing the whitespace

* only password manager plans are return for now

* format whitespace

* Resolve the test issue

* Fixing the failing test

* Refactoring the Plan separation

* add a unit test for SingleOrDefault

* Fix the whitespace format

* Separate the PM and SM plans

* Fixing the whitespace

* Remove unnecessary directive

* Fix imports ordering

* Fix imports ordering

* Resolve imports ordering

* Fixing imports ordering

* Fix response model, add MaxProjects

* Fix filename

* Fix format

* Fix: seat price should match annual/monthly

* Fix service account annual pricing

* Changes for secret manager signup and upgradeplan

* Changes for secrets manager signup and upgrade

* refactoring the code

* Format whitespace

* remove unnecessary using directive

* Changes for subscription Update

* Update the seatAdjustment and update

* Resolve the PR comment on Subscription creation

* Resolve PR comment

* Add password manager to the error message

* Add UseSecretsManager to the event log

* Resolve PR comment on plan validation

* Resolving pr comments for service account count

* Resolving pr comments for service account count

* Resolve the pr comments

* Remove the store procedure that is no-longer needed

* Add a new class for update subscription

* Modify the Update subscription for sm

* Add the missing property

* Rename a property properly

* Resolving the PR comment

* Resolve PR comments

* Resolving PR comments

* Resolving the Pr comments

* Resolving some PR comments

* Resolving the PR comments

* Resolving the build identity build

* Add additional Validation

* Resolve the Lint issues

* remove unnecessary using directive

* Remove the white spaces

* Adding unit test for the stripe payment

* Remove the incomplete test

* Fixing the failing test

* Fix the failing test

* Fix the fail test on organization service

* Fix the failing unit test

* Fix the whitespace format

* Fix the failing test

* Fix the whitespace format

* resolve pr comments

* Fix the lint message

* refactor the code

* Fix the failing Test

* adding a new endpoint

* Remove the unwanted code

* Changes for Command and Queries

* changes for command and queries

* Fix the Lint issues

* Fix imports ordering

* Resolve the PR comments

* resolve pr comments

* Resolve pr comments

* Fix the failing test on adjustSeatscommandtests

* Fix the failing test

* Fix the whitespaces

* resolve failing test

* rename a property

* Resolve the pr comments

* refactoring the existing implementation

* Resolve the whitespaces format issue

* Resolve the pr comments

* [AC-1462] Created IAvailableServiceAccountsQuery along its implementation and with unit tests

* [AC-1462] Renamed ICountNewServiceAccountSlotsRequiredQuery

* [AC-1462] Added IAutoscaleServiceAccountsCommand and implementation

* Add more unit testing

* fix the whitespaces issues

* [AC-1462] Added unit tests for AutoscaleServiceAccountsCommand

* Add more unit test

* Remove unnecessary directive

* Resolve some pr comments

* Adding more unit test

* adding more test

* add more test

* Resolving some pr comments

* Resolving some pr comments

* Resolving some pr comments

* resolve some pr comments

* Resolving pr comments

* remove whitespaces

* remove white spaces

* Resolving pr comments

* resolving pr comments and fixing white spaces

* resolving the lint error

* Run dotnet format

* resolving the pr comments

* Add a missing properties to plan response model

* Add the email sender for sm seat and service acct

* Add the email sender for sm seat and service acct

* Fix the failing test after email sender changes

* Add staticstorewrapper to properly test the plans

* Add more test and validate the existing test

* Fix the white spaces issues

* Remove staticstorewrapper and fix the test

* fix a null issue on autoscaling

* Suggestion: do all seat calculations in update model

* Resolve some pr comments

* resolving some pr comments

* Return value is unnecessary

* Resolve the failing test

* resolve pr comments

* Resolve the pr comments

* Resolving admin api failure and adding more test

* Resolve the issue failing admin project

* Fixing the failed test

* Clarify naming and add comments

* Clarify naming conventions

* Dotnet format

* Fix the failing dependency

* remove similar test

* [AC-1462] Rewrote AutoscaleServiceAccountsCommand to use UpdateSecretsManagerSubscriptionCommand which has the same logic

* [AC-1462] Deleted IAutoscaleServiceAccountsCommand as the logic will be moved to UpdateSecretsManagerSubscriptionCommand

* [AC-1462] Created method AdjustSecretsManagerServiceAccountsAsync

* [AC-1462] Changed SecretsManagerSubscriptionUpdate to only be set by its constructor

* [AC-1462] Added check to CountNewServiceAccountSlotsRequiredQuery and revised unit tests

* [AC-1462] Revised logic for CountNewServiceAccountSlotsRequiredQuery and fixed unit tests

* [AC-1462] Changed SecretsManagerSubscriptionUpdate to receive Organization as a parameter and fixed the unit tests

* [AC-1462] Renamed IUpdateSecretsManagerSubscriptionCommand methods UpdateSubscriptionAsync and AdjustServiceAccountsAsync

* [AC-1462] Rewrote unit test UpdateSubscriptionAsync_ValidInput_Passes

* [AC-1462] Registered CountNewServiceAccountSlotsRequiredQuery for dependency injection

* [AC-1462] Added parameter names to SecretsManagerSubscriptionUpdateRequestModel

* [AC-1462] Updated SecretsManagerSubscriptionUpdate logic to handle null parameters. Revised the unit tests to test null values

---------

Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* Add UsePasswordManager to sync data (#3114)

* [AC-1522] Fix service account check on upgrading (#3111)

* Resolved the checkmarx issues

* [AC-1521] Address checkmarx security feedback (#3124)

* Reinstate target attribute but add noopener noreferrer

* Update date on migration script

* Remove unused constant

* Revert "Remove unused constant"

This reverts commit 4fcb9da4d6.

This is required to make feature flags work on the client

* [AC-1458] Add Endpoint And Service Logic for secrets manager to existing subscription (#3087)

---------

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* Remove duplicate migrations from incorrectly resolved merge

* [AC-1468] Modified CountNewServiceAccountSlotsRequiredQuery to return zero if organization has SecretsManagerBeta == true (#3112)

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* [Ac 1563] Unable to load billing and subscription related pages for non-enterprise organizations (#3138)

* Resolve the failing family plan

* resolve issues

* Resolve code related pr comments

* Resolve test related comments

* Resolving or comments

* [SM-809] Add service account slot limit check (#3093)

* Add service account slot limit check

* Add query to DI

* [AC-1462] Registered CountNewServiceAccountSlotsRequiredQuery for dependency injection

* remove duplicate DI entry

* Update unit tests

* Remove comment

* Code review updates

---------

Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Rui Tome <rtome@bitwarden.com>

* [AC-1461] Secrets manager seat autoscaling (#3121)

* Add autoscaling code to invite user, save user, and bulk enable SM
  flows

* Add tests

* Delete command for BulkEnableSecretsManager

* circular dependency between OrganizationService and
  UpdateSecretsManagerSubscriptionCommand - fixed by temporarily
  duplicating ReplaceAndUpdateCache

* Unresolvable dependencies in other services - fixed by temporarily
  registering noop services and moving around some DI code

All should be resolved in PM-1880

* Refactor: improve the update object and use it to adjust values,
  remove excess interfaces on the command

* Handle autoscaling-specific errors

---------

Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>

* Move bitwarden_license include reference into conditional block

* [AC 1526]Show current SM seat and service account usage in Bitwarden Portal (#3142)

* changes base on the tickets request

* Code refactoring

* Removed the unwanted method

* Add implementation to the new method

* Resolve some pr comments

* resolve lint issue

* resolve pr comments

* add the new noop files

* Add new noop file and resolve some pr comments

* resolve pr comments

* removed unused method

* Fix prefill when changing plans or starting trials

* [AC-1575] Don't overwrite existing org information when changing plans
* [AC-1577] Prefill SM configuration section when starting trial

* Clarify property names

* Set SM subscription based on current usage

* Fix label for Service Accounts field

* Prevent subscribing to SM on an invalid plan

* Edit comment

* Set minimum seat count for SM

* Don't use hardcoded plan values

* Use plans directly in JS

* Refactor to getPlan function

* Remove unneeded namespace refs

* Add GetPlansHelper to provide some typesafety

* Use planType from form instead of model

* Add @model specification

* Add null coalescing

* [AC-108] Updated PolicyService to use IApplicationCacheService to determine if an organization uses policies

(cherry picked from commit b98b107c4b)

* [AC-108] Removed checking if Organization is enabled

---------

Co-authored-by: Shane Melton <smelton@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Colton Hurst <colton@coltonhurst.com>
Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Conner Turnbull <cturnbull@bitwarden.com>
Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>
2023-08-25 11:22:16 +01:00
Thomas Rittson
c5b5225642
[AC-1568] Refactor UpdateSecretsManagerSubscriptionCommandTests to use new ctor (#3210) 2023-08-22 09:55:39 +10:00
Todd Martin
1c3afcdffc
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 dc1319e7fa.

* Revert "[PM-1033] refactor: `UpdateUserResetPasswordEnrollmentCommand`"

This reverts commit 43df689c7f.

* [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 16:03:06 -04:00
Thomas Rittson
fc814ff352
[AC-1597] Revert GetByUserIdWithPolicyDetailsAsync changes to unblock SQL CPU (#3203)
* Revert "[PM-3007] Caching user policies on PolicyService variable (#3117)"

This reverts commit 78588d0246.

* Don't delete old migration script

* Add migration to revert sproc
2023-08-16 13:42:09 +10:00
cd-bitwarden
115ead00d4
Adding missing test to projectscontroller (#3129) 2023-08-11 15:07:29 -04:00
renovate[bot]
ceae31e7bf
Update dependency AngleSharp to v1 (#3079)
* Update dependency AngleSharp to v1

* Update lock files

* update test lockfile

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Matt Gibson <mgibson@bitwarden.com>
2023-08-10 14:34:39 -05:00
Oscar Hinton
d4bcaf10ff
Remove moq (#3166) 2023-08-10 17:03:42 +02:00
Matt Gibson
4377c7a897
Rewrite Icon fetching (#3023)
* Rewrite Icon fetching

* Move validation to IconUri, Uri, or UriBuilder

* `dotnet format` 🤖

* PR suggestions

* Add not null compiler hint

* Add twitter to test case

* Move Uri manipulation to UriService

* Implement MockedHttpClient

Presents better, fluent handling of message matching and response
building.

* Add redirect handling tests

* Add testing to models

* More aggressively dispose content in icon link

* Format 🤖

* Update icon lockfile

* Convert to cloned stream for HttpResponseBuilder

Content was being disposed when HttResponseMessage was being disposed.
This avoids losing our reference to our content and allows multiple
usages of the same `MockedHttpMessageResponse`

* Move services to extension

Extension is shared by testing and allows access to services from
our service tests

* Remove unused `using`

* Prefer awaiting asyncs for better exception handling

* `dotnet format` 🤖

* Await async

* Update tests to use test TLD and ip ranges

* Remove unused interfaces

* Make assignments static when possible

* Prefer invariant comparer to downcasing

* Prefer injecting interface services to implementations

* Prefer comparer set in HashSet initialization

* Allow SVG icons

* Filter out icons with unknown formats

* Seek to beginning of MemoryStream after writing it

* More appropriate to not return icon if it's invalid

* Add svg icon test
2023-08-08 19:29:40 +00:00
Matt Gibson
ca368466ce
Allow acceptable result ranges for integration tests (#3161) 2023-08-08 12:49:51 -05:00
Rui Tomé
95b7652ca9
[AC-1443] Update manager permission to only see collections they have access to (#3071)
* [AC-1443] Changed CurrentContext.ViewAllCollections to only check if the user can edit or delete any collection

* [AC-1443] Renamed ICollectionService.GetOrganizationCollections to GetOrganizationCollectionsAsync

* [AC-1443] Changed CollectionService.GetOrganizationCollectionsAsync to first check CurrentContext.ViewAssignedCollections instead
Added unit tests

* [AC-1443] Added new unit test to check for Exception when user does not have permission
2023-08-08 16:54:10 +01:00
Matt Gibson
a5bda60c4e
Platform/pm 2535/upgrade to azure messaging servicebus (#3102)
* `dotnet add package Azure.Messaging.ServiceBus` 🤖

* Move to Azure.Messaging.ServiceBus

* `dotnet restore --locked-mode --force-evaluate` 🤖

Remove Microsoft.Azure.ServiceBus

* `dotnet restore --locked-mode --force-evaluate` 🤖

* Include broker filter

* `dotnet restore --locked-mode --force-evaluate` 🤖
2023-08-07 08:57:18 -05:00
Thomas Rittson
3573aee2ef
[AC-1512] Feature: Secrets Manager Billing - round 2 (#3119)
* [AC-1423] Add AddonProduct and BitwardenProduct properties to BillingSubscriptionItem (#3037)

* [AC-1423] Add AddonProduct and BitwardenProduct properties to BillingSubscriptionItem

- Add a helper method to determine the appropriate addon type based on the subscription items StripeId

* [AC-1423] Add helper to StaticStore.cs to find a Plan by StripePlanId

* [AC-1423] Use the helper method to set SubscriptionInfo.BitwardenProduct

* Add SecretsManagerBilling feature flag to Constants

* [AC 1409] Secrets Manager Subscription Stripe Integration  (#3019)

* Adding the Secret manager to the Plan List

* Adding the unit test for the StaticStoreTests class

* Fix whitespace formatting

* Fix whitespace formatting

* Price update

* Resolving the PR comments

* Resolving PR comments

* Fixing the whitespace

* only password manager plans are return for now

* format whitespace

* Resolve the test issue

* Fixing the failing test

* Refactoring the Plan separation

* add a unit test for SingleOrDefault

* Fix the whitespace format

* Separate the PM and SM plans

* Fixing the whitespace

* Remove unnecessary directive

* Fix imports ordering

* Fix imports ordering

* Resolve imports ordering

* Fixing imports ordering

* Fix response model, add MaxProjects

* Fix filename

* Fix format

* Fix: seat price should match annual/monthly

* Fix service account annual pricing

* Changes for secret manager signup and upgradeplan

* Changes for secrets manager signup and upgrade

* refactoring the code

* Format whitespace

* remove unnecessary using directive

* Resolve the PR comment on Subscription creation

* Resolve PR comment

* Add password manager to the error message

* Add UseSecretsManager to the event log

* Resolve PR comment on plan validation

* Resolving pr comments for service account count

* Resolving pr comments for service account count

* Resolve the pr comments

* Remove the store procedure that is no-longer needed

* Rename a property properly

* Resolving the PR comment

* Resolve PR comments

* Resolving PR comments

* Resolving the Pr comments

* Resolving some PR comments

* Resolving the PR comments

* Resolving the build identity build

* Add additional Validation

* Resolve the Lint issues

* remove unnecessary using directive

* Remove the white spaces

* Adding unit test for the stripe payment

* Remove the incomplete test

* Fixing the failing test

* Fix the failing test

* Fix the fail test on organization service

* Fix the failing unit test

* Fix the whitespace format

* Fix the failing test

* Fix the whitespace format

* resolve pr comments

* Fix the lint message

* Resolve the PR comments

* resolve pr comments

* Resolve pr comments

* Resolve the pr comments

* remove unused code

* Added for sm validation test

* Fix the whitespace format issues

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* SM-802: Add SecretsManagerBetaColumn SQL migration and Org table update

* SM-802: Run EF Migrations for SecretsManagerBeta

* SM-802: Update the two Org procs and View, and move data migration to a separate file

* SM-802: Add missing comma to Organization_Create

* [AC-1418] Add missing SecretsManagerPlan property to OrganizationResponseModel (#3055)

* SM-802: Remove extra GO statement from data migration script

* [AC 1460] Update Stripe Configuration (#3070)

* change the stripeseat id

* change service accountId to align with new product

* make all the Id name for consistent

* SM-802: Add SecretsManagerBeta to OrganizationResponseModel

* SM-802: Move SecretsManagerBeta from OrganizationResponseModel to OrganizationSubscriptionResponseModel. Use sp_refreshview instead of sp_refreshsqlmodule in the migration script.

* SM-802: Remove OrganizationUserOrganizationDetailsView.sql changes

* [AC 1410] Secrets Manager subscription adjustment back-end changes (#3036)

* Create UpgradeSecretsManagerSubscription command

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* SM-802: Remove SecretsManagerBetaColumn migration

* SM-802: Add SecretsManagerBetaColumn migration

* SM-802: Remove OrganizationUserOrganizationDetailsView update

* [AC-1495] Extract UpgradePlanAsync into a command (#3081)

* This is a pure lift & shift with no refactors

* Only register subscription commands in Api

---------

Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>

* [AC-1503] Fix Stripe integration on organization upgrade (#3084)

* Fix SM parameters not being passed to Stripe

* Fix flaky test

* Fix error message

* [AC-1504] Allow SM max autoscale limits to be disabled (#3085)

* [AC-1488] Changed SM Signup and Upgrade paths to set SmServiceAccounts to include the plan BaseServiceAccount (#3086)

* [AC-1510] Enable access to Secrets Manager to Organization owner for new Subscription (#3089)

* Revert changes to ReferenceEvent code (#3091)

* Revert changes to ReferenceEvent code

This will be done in AC-1481

* Revert ReferenceEventType change

* Move NoopServiceAccountRepository to SM and update namespace

* [AC-1462] Add secrets manager service accounts autoscaling commands (#3059)

* Adding the Secret manager to the Plan List

* Adding the unit test for the StaticStoreTests class

* Fix whitespace formatting

* Fix whitespace formatting

* Price update

* Resolving the PR comments

* Resolving PR comments

* Fixing the whitespace

* only password manager plans are return for now

* format whitespace

* Resolve the test issue

* Fixing the failing test

* Refactoring the Plan separation

* add a unit test for SingleOrDefault

* Fix the whitespace format

* Separate the PM and SM plans

* Fixing the whitespace

* Remove unnecessary directive

* Fix imports ordering

* Fix imports ordering

* Resolve imports ordering

* Fixing imports ordering

* Fix response model, add MaxProjects

* Fix filename

* Fix format

* Fix: seat price should match annual/monthly

* Fix service account annual pricing

* Changes for secret manager signup and upgradeplan

* Changes for secrets manager signup and upgrade

* refactoring the code

* Format whitespace

* remove unnecessary using directive

* Changes for subscription Update

* Update the seatAdjustment and update

* Resolve the PR comment on Subscription creation

* Resolve PR comment

* Add password manager to the error message

* Add UseSecretsManager to the event log

* Resolve PR comment on plan validation

* Resolving pr comments for service account count

* Resolving pr comments for service account count

* Resolve the pr comments

* Remove the store procedure that is no-longer needed

* Add a new class for update subscription

* Modify the Update subscription for sm

* Add the missing property

* Rename a property properly

* Resolving the PR comment

* Resolve PR comments

* Resolving PR comments

* Resolving the Pr comments

* Resolving some PR comments

* Resolving the PR comments

* Resolving the build identity build

* Add additional Validation

* Resolve the Lint issues

* remove unnecessary using directive

* Remove the white spaces

* Adding unit test for the stripe payment

* Remove the incomplete test

* Fixing the failing test

* Fix the failing test

* Fix the fail test on organization service

* Fix the failing unit test

* Fix the whitespace format

* Fix the failing test

* Fix the whitespace format

* resolve pr comments

* Fix the lint message

* refactor the code

* Fix the failing Test

* adding a new endpoint

* Remove the unwanted code

* Changes for Command and Queries

* changes for command and queries

* Fix the Lint issues

* Fix imports ordering

* Resolve the PR comments

* resolve pr comments

* Resolve pr comments

* Fix the failing test on adjustSeatscommandtests

* Fix the failing test

* Fix the whitespaces

* resolve failing test

* rename a property

* Resolve the pr comments

* refactoring the existing implementation

* Resolve the whitespaces format issue

* Resolve the pr comments

* [AC-1462] Created IAvailableServiceAccountsQuery along its implementation and with unit tests

* [AC-1462] Renamed ICountNewServiceAccountSlotsRequiredQuery

* [AC-1462] Added IAutoscaleServiceAccountsCommand and implementation

* Add more unit testing

* fix the whitespaces issues

* [AC-1462] Added unit tests for AutoscaleServiceAccountsCommand

* Add more unit test

* Remove unnecessary directive

* Resolve some pr comments

* Adding more unit test

* adding more test

* add more test

* Resolving some pr comments

* Resolving some pr comments

* Resolving some pr comments

* resolve some pr comments

* Resolving pr comments

* remove whitespaces

* remove white spaces

* Resolving pr comments

* resolving pr comments and fixing white spaces

* resolving the lint error

* Run dotnet format

* resolving the pr comments

* Add a missing properties to plan response model

* Add the email sender for sm seat and service acct

* Add the email sender for sm seat and service acct

* Fix the failing test after email sender changes

* Add staticstorewrapper to properly test the plans

* Add more test and validate the existing test

* Fix the white spaces issues

* Remove staticstorewrapper and fix the test

* fix a null issue on autoscaling

* Suggestion: do all seat calculations in update model

* Resolve some pr comments

* resolving some pr comments

* Return value is unnecessary

* Resolve the failing test

* resolve pr comments

* Resolve the pr comments

* Resolving admin api failure and adding more test

* Resolve the issue failing admin project

* Fixing the failed test

* Clarify naming and add comments

* Clarify naming conventions

* Dotnet format

* Fix the failing dependency

* remove similar test

* [AC-1462] Rewrote AutoscaleServiceAccountsCommand to use UpdateSecretsManagerSubscriptionCommand which has the same logic

* [AC-1462] Deleted IAutoscaleServiceAccountsCommand as the logic will be moved to UpdateSecretsManagerSubscriptionCommand

* [AC-1462] Created method AdjustSecretsManagerServiceAccountsAsync

* [AC-1462] Changed SecretsManagerSubscriptionUpdate to only be set by its constructor

* [AC-1462] Added check to CountNewServiceAccountSlotsRequiredQuery and revised unit tests

* [AC-1462] Revised logic for CountNewServiceAccountSlotsRequiredQuery and fixed unit tests

* [AC-1462] Changed SecretsManagerSubscriptionUpdate to receive Organization as a parameter and fixed the unit tests

* [AC-1462] Renamed IUpdateSecretsManagerSubscriptionCommand methods UpdateSubscriptionAsync and AdjustServiceAccountsAsync

* [AC-1462] Rewrote unit test UpdateSubscriptionAsync_ValidInput_Passes

* [AC-1462] Registered CountNewServiceAccountSlotsRequiredQuery for dependency injection

* [AC-1462] Added parameter names to SecretsManagerSubscriptionUpdateRequestModel

* [AC-1462] Updated SecretsManagerSubscriptionUpdate logic to handle null parameters. Revised the unit tests to test null values

---------

Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* Add UsePasswordManager to sync data (#3114)

* [AC-1522] Fix service account check on upgrading (#3111)

* Resolved the checkmarx issues

* [AC-1521] Address checkmarx security feedback (#3124)

* Reinstate target attribute but add noopener noreferrer

* Update date on migration script

* Remove unused constant

* Revert "Remove unused constant"

This reverts commit 4fcb9da4d6.

This is required to make feature flags work on the client

* [AC-1458] Add Endpoint And Service Logic for secrets manager to existing subscription (#3087)

---------

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* Remove duplicate migrations from incorrectly resolved merge

* [AC-1468] Modified CountNewServiceAccountSlotsRequiredQuery to return zero if organization has SecretsManagerBeta == true (#3112)

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* [Ac 1563] Unable to load billing and subscription related pages for non-enterprise organizations (#3138)

* Resolve the failing family plan

* resolve issues

* Resolve code related pr comments

* Resolve test related comments

* Resolving or comments

* [SM-809] Add service account slot limit check (#3093)

* Add service account slot limit check

* Add query to DI

* [AC-1462] Registered CountNewServiceAccountSlotsRequiredQuery for dependency injection

* remove duplicate DI entry

* Update unit tests

* Remove comment

* Code review updates

---------

Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Rui Tome <rtome@bitwarden.com>

* [AC-1461] Secrets manager seat autoscaling (#3121)

* Add autoscaling code to invite user, save user, and bulk enable SM
  flows

* Add tests

* Delete command for BulkEnableSecretsManager

* circular dependency between OrganizationService and
  UpdateSecretsManagerSubscriptionCommand - fixed by temporarily
  duplicating ReplaceAndUpdateCache

* Unresolvable dependencies in other services - fixed by temporarily
  registering noop services and moving around some DI code

All should be resolved in PM-1880

* Refactor: improve the update object and use it to adjust values,
  remove excess interfaces on the command

* Handle autoscaling-specific errors

---------

Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>

* Move bitwarden_license include reference into conditional block

* [AC 1526]Show current SM seat and service account usage in Bitwarden Portal (#3142)

* changes base on the tickets request

* Code refactoring

* Removed the unwanted method

* Add implementation to the new method

* Resolve some pr comments

* resolve lint issue

* resolve pr comments

* add the new noop files

* Add new noop file and resolve some pr comments

* resolve pr comments

* removed unused method

---------

Co-authored-by: Shane Melton <smelton@bitwarden.com>
Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
Co-authored-by: Colton Hurst <colton@coltonhurst.com>
Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>
Co-authored-by: Conner Turnbull <cturnbull@bitwarden.com>
Co-authored-by: Rui Tome <rtome@bitwarden.com>
Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>
2023-08-04 21:51:12 +00:00
Rui Tomé
78588d0246
[PM-3007] Caching user policies on PolicyService variable (#3117)
* [PM-3007] Caching user policies on PolicyService variable

* [PM-3007] Added missing newlines on sql files
2023-08-03 18:36:47 +01:00
Thomas Avery
73c6421bd3
[SM-722] Add optional access to secrets for service account lists (#3074)
* Add access to secret count to service account list

* dotnet format

* refactor into query

* Remove duplicate

* Add new method to noop
2023-08-03 10:06:34 -05:00
Rui Tomé
d94a54516e
[AC-1344] Provider users unable to bulk restore vault items for client organizations (#2871)
* [AC-1344] Added method PutRestoreManyAdmin to CiphersController and refactored PutRestoreMany

* [AC-1344] Fixed unit test

* [AC-1344] Removed comment

* [AC-1344] Fixed sql.csproj

* [AC-1344] Added check for empty or null array; added more unit tests
2023-08-02 16:22:37 +01:00
Álison Fernandes
35111382e5
[AC-1486] Feature: SM Billing (#3073)
* [AC-1423] Add AddonProduct and BitwardenProduct properties to BillingSubscriptionItem (#3037)

* [AC-1423] Add AddonProduct and BitwardenProduct properties to BillingSubscriptionItem

* [AC-1423] Add helper to StaticStore.cs to find a Plan by StripePlanId

* [AC-1423] Use the helper method to set SubscriptionInfo.BitwardenProduct

* Add SecretsManagerBilling feature flag to Constants

* [AC 1409] Secrets Manager Subscription Stripe Integration  (#3019)

* [AC-1418] Add missing SecretsManagerPlan property to OrganizationResponseModel (#3055)

* [AC 1460] Update Stripe Configuration (#3070)

* [AC 1410] Secrets Manager subscription adjustment back-end changes (#3036)

* Create UpgradeSecretsManagerSubscription command

* [AC-1495] Extract UpgradePlanAsync into a command (#3081)

* This is a pure lift & shift with no refactors

* [AC-1503] Fix Stripe integration on organization upgrade (#3084)

* Fix SM parameters not being passed to Stripe

* [AC-1504] Allow SM max autoscale limits to be disabled (#3085)

* [AC-1488] Changed SM Signup and Upgrade paths to set SmServiceAccounts to include the plan BaseServiceAccount (#3086)

* [AC-1510] Enable access to Secrets Manager to Organization owner for new Subscription (#3089)

* Revert changes to ReferenceEvent code (#3091)

This will be done in AC-1481

* Add UsePasswordManager to sync data (#3114)

* [AC-1522] Fix service account check on upgrading (#3111)

* [AC-1521] Address checkmarx security feedback (#3124)

* Reinstate target attribute but add noopener noreferrer

* Update date on migration script

---------

Co-authored-by: Shane Melton <smelton@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: cyprain-okeke <cokeke@bitwarden.com>
Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>
Co-authored-by: Conner Turnbull <cturnbull@bitwarden.com>
Co-authored-by: Rui Tome <rtome@bitwarden.com>
2023-07-25 08:05:05 +10:00
Federico Maccaroni
10782d55f3
[PM-2682] Fix v0 attachments migration on share cipher with org (#3051)
* PM-2682 Fix v0 attachments migration on share cipher with org

* PM-2682 Fix format

* PM-2682 Fix tests recursion

* Update src/Core/Vault/Models/Data/CipherAttachment.cs

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>

---------

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>
2023-07-21 16:08:08 -03:00
Conner Turnbull
a61290a3c8
[AC-1508] Stripe changes for the EU datacenter (#3092)
* Added region to customer metadata

* Updated webhook to filter out events for other DCs

* Flipped ternary to be positive, fixed indentation

* Updated to allow for unit testing andupdated tests

---------

Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
2023-07-20 17:00:40 -04:00
Shane Melton
a095e02e86
[AC-1435] Single Organization policy prerequisite for Account Recovery policy (#3082)
* [AC-1435] Automatically enable Single Org policy when selecting TDE

* [AC-1435] Add test for automatic policy enablement

* [AC-1435] Prevent disabling single org when account recovery is enabled

* [AC-1435] Require Single Org policy when enabling Account recovery

* [AC-1435] Add unit test to check for account recovery policy when attempting to disable single org

* [AC-1435] Add test to verify single org policy is enabled for account recovery policy

* [AC-1435] Fix failing test
2023-07-18 10:00:49 -05:00
Daniel García
4f87e4e1a4
[PM-2196] Improvements to the Swagger generator (#2914)
* Swagger fixes

Co-Authored-By: Oscar Hinton <Hinton@users.noreply.github.com>

* Make Response Models return Guids instead of strings

* Change strings into guids in ScimApplicationFactory

---------

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>
2023-07-14 17:18:26 +02:00
Thomas Avery
1d9aeb37aa
[SM-707] Refactor authorization for Access Policy Commands (#2905)
* Extract authorization from access policy commands

* Use auto mapper to ignore unwanted properties

---------
2023-07-13 11:46:01 -05:00
Thomas Avery
d6a45d4802
[SM-789] Extract authorization from service account delete command (#2999)
* Extract authorization from SA delete command

* swap to IEnumerable

---------

Co-authored-by: Matt Bishop <mbishop@bitwarden.com>
2023-07-12 15:32:40 -05:00
Thomas Avery
b629c31de9
[SM-787] Extract authorization from project delete command (#2987)
* Extract authorization from project delete command

* Support service account write access

---------

Co-authored-by: Matt Bishop <mbishop@bitwarden.com>
2023-07-11 15:15:18 -05:00
Colton Hurst
a565b19ffb
SM-768: Update EFCore and related packages to >= 7.0 (#3006)
* SM-768: Update EFCore and related packages to >= 7.0

* SM-768: Update more packages for the EF 7 upgrade

* SM-768: Update the PostgreSQL package

* SM-768: Run dotnet restore --force-evaluate

* SM-768: Revert package upgrades for 3 projects

* SM-768: Update the dotnet-ef tool
2023-07-07 09:56:31 -04:00
Vincent Salucci
3b4c8afea0
[AC-1191] TDE admin approval email (#3044)
* feat: add new command for updating request and emailing user, refs AC-1191

* feat: inject service with organization service collection extensions, refs AC-1191

* feat: add function to send admin approval email to mail services (interface/noop/handlebars), refs AC-1191

* feat: add html/text mail templates and add view model for email data, refs AC-1191

* feat: update org auth request controller to use new command during auth request update, refs AC-1191

* fix: dotnet format, refs AC-1191

* refactor: update user not found error, FirstOrDefault for enum type display name, refs AC-1191

* refactor: update user not found to log error instead of throws, refs AC-1191

* fix: remove whitespace lint errors, refs AC-1191

* refactor: update hardcoded UTC timezone string, refs AC-1191

* refactor: add unit test for new command, refs AC-1191

* refactor: improve enum name fallback and identifier string creation, refs AC-1191

* refactor: add addtional unit tests, refs AC-1191

* refactor: update success test to use more generated params, refs AC-1191

* fix: dotnet format...again, refs AC-1191

* refactor: make UTC display a constant for handlebars mail service, refs AC-1191

* refactor: update displayTypeIdentifer to displayTypeAndIdentifier for clarity, refs AC-1191
2023-07-06 10:03:49 -05:00
Justin Baur
b0214ae1be
[PM-863] Fix Organization Folders in EF Databases (#2856)
* Fix Setting Organization Folders

* Fix Formatting

* Added ReplaceAsync Test

* Fix SQL Server Test

* Update Replace Call Also

* Be Case Insensitive With Guids

* Fix Assignment to Cipher
2023-06-30 18:41:11 -04:00
Justin Baur
49e849deb9
[PM-1198] Modify AuthRequest Purge Job (#3048)
* Add PasswordlessAuth Settings

* Update Repository Method to Take TimeSpan

* Update AuthRequest_DeleteIfExpired

- Take Configurable Expiration
- Add Special Cases for AdminApproval AuthRequests

* Add AuthRequestRepositoryTests

* Run Formatting

* Remove Comment

* Fix Bug in EF Repo

* Add Test Covering Expired Rejected AuthRequest

* Use Longer Param Names

* Use Longer Names in Test Helpers
2023-06-30 14:13:31 -04:00
cd-bitwarden
3f3f52399b
[SM-716] Adding ability for service account to have write access (#3021)
* adding ability for service account to have write access

* Suggested changes

* fixing tests

* dotnet format changes

* Adding RunAsServiceAccountWIthPermission logic to ProjectAuthorizationhandlerTests

* Removing logic that prevents deleting and updating a secret. Adding Service Account logic to tests inside of secretAuthorizationhandlerTests.

* Removing Service Account from CanUpdateSecret_NotSupportedClientTypes_DoesNotSuceed because it is a supported client type now :)

* thomas sugested changes

* using Arg.Any<AccessClientType>() instead of default in tests

* merge conflict changes and code updates to remove service account tests that are  outdated

* fixing tests

* removing extra  spaces that lint hates
2023-06-30 17:17:41 +00:00
Thomas Avery
74ab7e8672
[SM-771] Add new endpoint for bulk enabling users for Secrets Manager (#3020)
* Add new endpoint for bulk enabling users for sm

* Review updates
2023-06-29 12:42:44 -04:00
Justin Baur
3bffd480cb
Pin Microsoft.AspNetCore.Http (#3001) 2023-06-29 08:37:58 -05:00
Thomas Avery
d020c49c0e
[SM-788] Extract authorization from secret delete command (#3003)
* Extract authorization from secret delete command
2023-06-27 13:12:34 -05:00
Justin Baur
e0b231a220
[PM-2697] Return UserDecryptionOptions Always (#3032)
* Add Comments to UserDecryptionOptions

* Move Feature Flag Check

* Remove SSO Config Check

* Move UserDecryptionOptions Creation

- Put logic in BaseRequestValidator

* Remove 'async'
2023-06-26 20:17:39 -04:00
SmithThe4th
e96fc56dc2
[SG-497] BEEEP - Health Checks API Project (#2237)
* health check services added

* health check extension added

* added get connection string

* made changes to hrslth check method

* Added database health check

* added identity server health check

* added identity server health check

* Added logger publisher

* latest changes

* removed file

* Added mail server check for dev

* Added authorization to health check url path

* commented

* Added exception to switch

* Removed exclude code coverage

* Added health check for redis

* Added todos

* Added storage queue checks

* Added checks for mail

* Removed unused references and fixed linting issue

* Lint issues

* Moved healthchecks to sharedWeb project and exposed builder as a parameter to configure more health checks based on a project

* Added health check to API project

* dependencies updated

* Removed ef core health check dependencies

* Added checks to only add a health check when the connection string exists, moved health check from startup to extension class

* Merged with master and fixed conflicts

* Fixed lint issues

* Added check for amazon ses

* merged with master

* fixed lint

* Removed Amazon SES health check
2023-06-26 15:04:21 -04:00
Thomas Avery
bb3a9daf98
[SM-678] ClientSecret migration (#2943)
* Init ClientSecret migration

* Fix unit tests

* Move to src/Sql/dbo_future

* Formatting changes

* Update migration date for next release

* Swap to just executing sp_refreshview

* Fix formatting

* Add EF Migrations

* Rename to ClientSecretHash

* Fix unit test

* EF column rename

* Batch the migration

* Fix formatting

* Add deprecation notice to property

* Move data migration

* Swap to CREATE OR ALTER
2023-06-21 13:16:06 -05:00
Justin Baur
5a8e549194
[PM-1815] Include Member Decryption Type in Token Response (#2927)
* Include Member Decryption Type

* Make ICurrentContext protected from base class

* Return MemberDecryptionType

* Extend WebApplicationFactoryBase

- Allow for service subsitution

* Create SSO Tests

- Mock IAuthorizationCodeStore so the SSO process can be limited to Identity

* Add MemberDecryptionOptions

* Remove Unused Property Assertion

* Make MemberDecryptionOptions an Array

* Address PR Feedback

* Make HasAdminApproval Policy Aware

* Format

* Use Object Instead

* Add UserDecryptionOptions File
2023-06-19 10:16:15 -04:00
Matt Bishop
53327b1993
[PM-2633] Warnings cleanup (#3010)
* Warnings cleanup

* One-line response with null

Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>

* Remove condition

* Fix lint from suggestion

---------

Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>
2023-06-16 10:02:05 -04:00
cyprain-okeke
5a12db18d1
[AC-1408] Update plan to include secrets manager (#2942)
* Adding the Secret manager to the Plan List

* Adding the unit test for the StaticStoreTests class

* Fix whitespace formatting

* Fix whitespace formatting

* Price update

* Resolving the PR comments

* Resolving PR comments

* Fixing the whitespace

* only password manager plans are return for now

* format whitespace

* Resolve the test issue

* Fixing the failing test

* Refactoring the Plan separation

* add a unit test for SingleOrDefault

* Fix the whitespace format

* Separate the PM and SM plans

* Fixing the whitespace

* Remove unnecessary directive

* Fix imports ordering

* Fix imports ordering

* Resolve imports ordering

* Fixing imports ordering

* Fix response model, add MaxProjects

* Fix filename

* Fix format

* Fix: seat price should match annual/monthly

* Fix service account annual pricing

* Name the sm service account planId properly

* Update the secrets manager plan

* correcting the wrong amount for the seats

---------

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
2023-06-16 11:12:38 +01:00
Shane Melton
904b2fe205
[AC-1192] Create endpoints for new Device Approvals page (#2993)
* [AC-1192] Create new OrganizationAuthRequestsController.cs

* [AC-1192] Introduce OrganizationAdminAuthRequest model

* [AC-1192] Add GetManyPendingByOrganizationId method to AuthRequest repository

* [AC-1192] Add new list pending organization auth requests endpoint

* [AC-1192] Add new GetManyAdminApprovalsByManyIdsAsync method to the AuthRequestRepository

* [AC-1192] Make the response device identifier optional for admin approval requests

* [AC-1192] Add endpoint for bulk denying admin device auth requests

* [AC-1192] Add OrganizationUserId to PendingOrganizationAuthRequestResponseModel

* [AC-1192] Add UpdateAuthRequest endpoint and logic to OrganizationAuthRequestsController

* [AC-1192] Secure new endpoints behind TDE feature flag

* [AC-1192] Formatting

* [AC-1192] Add sql migration script

* [AC-1192] Add optional OrganizationId column to AuthRequest entity

- Rename migration script to match existing formatting
- Add new column
- Add migration scripts
- Update new sprocs to filter/join on OrganizationId
- Update old sprocs to include OrganizationId

* [AC-1192] Format migration scripts

* [AC-1192] Fix failing AuthRequest EF unit test

* [AC-1192] Make OrganizationId optional in updated AuthRequest sprocs for backwards compatability

* [AC-1192] Fix missing comma in migration file

* [AC-1192] Rename Key to EncryptedUserKey to be more descriptive

* [AC-1192] Move request validation into helper method to reduce repetition

* [AC-1192] Return UnauthorizedAccessException instead of NotFound when user is missing permission

* [AC-1192] Introduce FeatureUnavailableException

* [AC-1192] Introduce RequireFeatureAttribute

* [AC-1192] Utilize the new RequireFeatureAttribute in the OrganizationAuthRequestsController

* [AC-1192] Attempt to fix out of sync database migration by moving new OrganizationId column

* [AC-1192] More attempts to sync database migrations

* [AC-1192] Formatting

* [AC-1192] Remove unused reference to FeatureService

* [AC-1192] Change Id types from String to Guid

* [AC-1192] Add EncryptedString attribute

* [AC-1192] Remove redundant OrganizationId property

* [AC-1192] Switch to projection for OrganizationAdminAuthRequest mapping

- Add new OrganizationUser relationship to EF entity
- Replace AuthRequest DBContext config with new IEntityTypeConfiguration
- Add navigation property to AuthRequest entity configuration for OrganizationUser
- Update EF AuthRequestRepository to use new mapping and navigation properties

* [AC-1192] Remove OrganizationUser navigation property
2023-06-15 14:54:08 -07:00
Thomas Avery
3449d28c83
[SM-705] Extract Authorization from Access Token Commands (#2928)
* refactor authorization for access token commands

* Unit tests for authorization handler
2023-06-13 15:30:44 -05:00
Thomas Avery
05f11a8ee1
[SM-706] Extract Authorization From Create/Update Secret Commands (#2896)
* Extract authorization from commands

* Swap to request model validation.

* Swap to pattern detection
2023-06-08 16:40:35 -05:00
Matt Bishop
6a9e7a1d0a
Project configuration tune-up (#2994) 2023-06-08 13:21:03 -04:00
Rui Tomé
746dec6496
[PM-1270] Throw error when removing master password reset policy with TDE enabled (#2964)
* [PM-1270] Updated PolicyService to throw an exception in case TDE is enabled and the user is trying to turn off the master password reset policy or tries to remove auto-enrollment

* [PM-1270] Added unit tests around the checks for turning off the master password reset policy or removing auto-enrollment

* [PM-1270] Fixed existing unit test SaveAsync_NewPolicy_Created

* [PM-1270] Removed unused method mock on unit test
2023-06-07 09:56:31 +01:00
Thomas Avery
d1155ee376
[SM-704] Extract Authorization For ServiceAccounts (#2869)
* Move to access query for project commands

* Swap to hasAccess method per action

* Swap to authorization handler pattern

* Move ProjectOperationRequirement to Core

* Add default throw + tests

* Extract authorization out of commands

* Unit tests for authorization handler

* Formatting

* Swap to reflection for testing switch

* Swap to check read & reflections in test

* fix wording on exception

* Refactor GetAccessClient into its own query

* Use accessClientQuery in project handler
2023-05-31 13:49:58 -05:00
Justin Baur
61a0efbdfc
[PM-2444] Add Pipeline for Testing All Database Variants in CI (#2471)
* Add Pipeline

* Fix Lint

* Added a Change

* Update Pipeline

* Add Multi-Version Support

* Use Profile Switch for each profile

* Fix MySql

* Debug MySql

* Use Proper Seperator

* Add Allow User Variables=true

* Pipeline Work

* Expand Config for Postgres

* Change Config Key

* Add Debug Step

* Fix Debug Step

* Fix Tests

* Add Sleep

* Fix Tests

* Fix SQL Server Tests

* Add Sqlite

* Use Context Property

* Fix Tests

* Fix Test Logger

* Update AccountRevisionDate Check

* Fix Postgres Time Issues

* Formatting and Pipeline Update

* Remove Unneeded SqlServer Setting

* Update .github/workflows/infrastructure-tests.yml

Co-authored-by: mimartin12 <77340197+mimartin12@users.noreply.github.com>

---------

Co-authored-by: mimartin12 <77340197+mimartin12@users.noreply.github.com>
2023-05-30 13:25:55 -04:00
Daniel James Smith
09144ddb52
[PM-153] Extend Freshdesk integration (#2939)
* Move keys into FreshDeskSettings class

* Add configurable custom fields for user and org

In FreshDesk we currently use the custom fields `cf_user` and `cf_org`.

- For the US instance these will be set to those values.
- For the EU instance these will likely be configured to `cf_user_eu` and `cf_org_eu`

* Fix file encoding

* Add region to notes

* Use customizable org field value in condition check
2023-05-23 14:43:44 +02:00
cyprain-okeke
662ac7f059
Signups Fail for Organization & User Names >30 Characters (#2923)
* Add a length limit to include only the LEFT 30

* Resolving PR comment

* Fix the failing test

* Add a comment to stripepayment

* Refactoring the code
2023-05-19 18:45:47 +01:00
Rui Tomé
04e18ee8e7
[AC-621] Added possibility of adding users through SCIM to an Organization without a confirmed Owner (#2846)
* [AC-621] Added possibility of adding users through SCIM to an Organization without a confirmed Owner

* [AC-621] Passing EventSystemUser argument for HasConfirmedOwnersExceptAsync in user delete actions by SCIM

* [AC-624] Removed EventSystemUser parameter from IOrganizationService.HasConfirmedOwnersExceptAsync

* [AC-621] Added IProviderUserRepository.GetManyOrganizationDetailsByOrganizationAsync

* [AC-621] Updated OrganizationService.HasConfirmedOwnersExceptAsync to use IProviderUserRepository.GetManyOrganizationDetailsByOrganizationAsync to check for any confirmed provider users

* [AC-621] Removed unused EventSystemUser parameters

* [AC-621] Refactored ProviderUserRepository.GetManyByOrganizationAsync to return ProviderUser objects

* [AC-621] Removed default parameter value for Status
2023-05-17 16:39:08 +01:00
Rui Tomé
bcf096971b
[PM-1879] Allow custom users to grant the same custom permissions that they have (#2897)
* [PM-1879] Replaced JsonSerializer.Serialize with CoreHelpers.ClassToJsonData

* [PM-1879] Changed OrganizationService.SaveUserAsync to check Custom permissions

* [PM-1879] Added unit tests for saving Custom permissions using a Custom user

* [PM-1879] Added method OrganizationUser.GetPermissions to deserialize the Permissions property

* [PM-1879] Refactored ValidateCustomPermissionsGrant to return bool

* [PM-1879] Added unit test SaveUser_WithCustomPermission_WhenUpgradingToAdmin_Throws
2023-05-17 14:17:37 +01:00
Jim Hays
8262af3c53
[PM-1969] Spellcheck other (#2878)
* Fix typo in error message: 'Unkown' -> 'Unknown'

* Fix typos in error message

* Fix typo in example text: 'licence' -> 'license'

* Fix typo in validation: 'Ooganization' -> 'Organization'

* Fix typo in text string: 'compatibilty' -> 'compatibility'

* Fix typo: 'ProviderDisllowedOrganizationTypes' -> 'ProviderDisallowedOrganizationTypes'

* Fix typo: 'NSubstitueVersion' -> 'NSubstituteVersion'

* Fix typo: 'CreateIntialInvite' -> 'CreateInitialInvite'

* Fix typo: '_queuryScheme' -> '_queryScheme'

* Fix typo: 'GetApplicationCacheServiceBusSubcriptionName' -> 'GetApplicationCacheServiceBusSubscriptionName'

* Fix typo: 'metaDataRespository' -> 'metaDataRepository'

* Fix typo: 'cipherAttachements' -> 'cipherAttachments'

* Fix typo: 'savedEmergencyAccesss' -> 'savedEmergencyAccesses'

* Fix typo: 'owerOrgUser' -> 'ownerOrgUser'

* Fix typo: 'Organiation' -> 'Organization'

* Fix typo: 'extistingUser' -> 'existingUser'

* Fix typo: 'availibleAccess' -> 'availableAccess'

* Fix typo: 'HasEnouphStorage' -> 'HasEnoughStorage'

* Fix typo: 'extistingOrg' -> 'existingOrg'

* Fix typo: 'subcriber' -> 'subscriber'

* Fix typo: 'availibleCollections' -> 'availableCollections'

* Fix typo: 'Succes' -> 'Success'

* Fix typo: 'CreateAsync_UpdateWithCollecitons_Works' -> 'CreateAsync_UpdateWithCollections_Works'

* Fix typo: 'BadInsallationId' -> 'BadInstallationId'

* Fix typo: 'OrgNotFamiles' -> 'OrgNotFamilies'

* Revert "Fix typo: 'Organiation' -> 'Organization'"

This reverts commit 8aadad1c25.

* Revert "Fix typos in error message"

This reverts commit 81d201fc09.

---------

Co-authored-by: Daniel James Smith <djsmith@web.de>
2023-05-17 12:14:36 +02:00
Shane Melton
bfd3f85bb0
[AC-358] Server changes for self host subscription page changes (#2826)
* [AC-358] Add constant for grace period length

* [AC-358] Add SubscriptionExpiration to OrganizationLicense.cs and increment Current_License_File_Version

* [AC-358] Update org subscription response model

- Add new SelfHostSubscriptionExpiration field that does not include a grace period
- Add optional License argument to constructor for self host responses
- Use the License, if available, to populate the expiration/subscription expiration fields
- Maintain backwards compatability by falling back to organization expiration date

* [AC-358] Read organization license file for self hosted subscription response

* [AC-358] Decrement current license file version and add comment documenting why

* [AC-358] Clarify name for new expiration without grace period field
2023-05-15 07:38:41 -07:00
Rui Tomé
8d3fe12170
[EC-787] Create a method in PolicyService to check if a policy applies to a user (#2537)
* [EC-787] Add new stored procedure OrganizationUser_ReadByUserIdWithPolicyDetails

* [EC-787] Add new method IOrganizationUserRepository.GetByUserIdWithPolicyDetailsAsync

* [EC-787] Add OrganizationUserPolicyDetails to represent policies applicable to a specific user

* [EC-787] Add method IPolicyService.GetPoliciesApplicableToUser to filter the obtained policy data

* [EC-787] Returning PolicyData on stored procedures

* [EC-787] Changed GetPoliciesApplicableToUserAsync to return ICollection

* [EC-787] Switched all usings of IPolicyRepository.GetManyByTypeApplicableToUserIdAsync to IPolicyService.GetPoliciesApplicableToUserAsync

* [EC-787] Removed policy logic from BaseRequestValidator and added usage of IPolicyService.GetPoliciesApplicableToUserAsync

* [EC-787] Added unit tests for IPolicyService.GetPoliciesApplicableToUserAsync

* [EC-787] Added unit tests for OrganizationUserRepository.GetByUserIdWithPolicyDetailsAsync

* [EC-787] Changed integration test to check for single result

* [EC-787] Marked IPolicyRepository methods GetManyByTypeApplicableToUserIdAsync and GetCountByTypeApplicableToUserIdAsync as obsolete

* [EC-787] Returning OrganizationUserId on OrganizationUser_ReadByUserIdWithPolicyDetails

* [EC-787] Remove deprecated stored procedures Policy_CountByTypeApplicableToUser, Policy_ReadByTypeApplicableToUser and function PolicyApplicableToUser

* [EC-787] Added method IPolicyService.AnyPoliciesApplicableToUserAsync

* [EC-787] Removed 'OrganizationUserType' parameter from queries

* [EC-787] Formatted OrganizationUserPolicyDetailsCompare

* [EC-787] Renamed SQL migration files

* [EC-787] Changed OrganizationUser_ReadByUserIdWithPolicyDetails to return Permissions json

* [EC-787] Refactored excluded user types for each Policy

* [EC-787] Updated dates on dbo_future files

* [EC-787] Remove dbo_future files from sql proj

* [EC-787] Added parameter PolicyType to IOrganizationUserRepository.GetByUserIdWithPolicyDetailsAsync

* [EC-787] Rewrote OrganizationUser_ReadByUserIdWithPolicyDetails and added parameter for PolicyType

* Update util/Migrator/DbScripts/2023-03-10_00_OrganizationUserReadByUserIdWithPolicyDetails.sql

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

---------

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
2023-05-12 08:22:19 +01:00
Matt Bishop
99b0953acd
Remove Secrets Manager LaunchDarkly feature flag (#2925) 2023-05-11 10:27:58 -04:00
Shane Melton
620a7e0a8d
[AC-1145] Add trusted devices option to SSO Config Data (#2909)
* [AC-1145] Add TDE feature flag

* [AC-1145] Update .gitignore to ignore flags.json in the Api project

* [AC-1145] Introduce MemberDecryptionType property on SsoConfigurationData

* [AC-1145] Add MemberDecryptionType to the SsoConfigurationDataRequest model

* [AC-1145] Automatically enable password reset policy on TDE selection

* [AC-1145] Remove references to obsolete KeyConnectorEnabled field

* [AC-1145] Formatting

* [AC-1145] Update XML doc reference to MemberDecryptionType
2023-05-10 12:52:08 -07:00
Justin Baur
5a850f48e2
[PM-1807] Add Auth Request Service (#2900)
* Refactor AuthRequest Logic into Service

* Add Tests & Run Formatting

* Register Service

* Add Tests From PR Feedback

Co-authored-by: Jared Snider <jsnider@bitwarden.com>

---------

Co-authored-by: Jared Snider <jsnider@bitwarden.com>
2023-05-09 12:39:33 -04:00
Jim Hays
f9038472ce
Fix typos in comments (#2876) 2023-05-09 17:38:47 +02:00
Thomas Avery
5474d3da18
[SM-702] Extract access policy checks from create/update project commands (#2842)
* Move to access query for project commands

* Swap to hasAccess method per action

* Swap to authorization handler pattern

* Move ProjectOperationRequirement to Core

* Add default throw + tests

* Swap to reflection for testing switch
2023-05-03 09:40:24 -05:00
Thomas Avery
20d3b4b4e8
[SM-670] Add permission context to project lists. (#2822)
* Attach permission context to project lists.

* restrict service-account actions

* Fix project permission details

* Add getters and setters

* dotnet format

* Fix admin create unassigned secret (#2872)
2023-04-26 13:09:25 -05:00
Justin Baur
a2d45c09ad
Fix Organization License Sync (#2864) 2023-04-24 13:51:08 -04:00
Vincent Salucci
9a1a369472
[AC-1201] refactor: move all SCIM related files into the AdminConsole scope (#2841)
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
2023-04-19 09:31:00 +10:00
Jake Fink
4f2fb2ccf5
[PM-1188] Move EF auth models for code ownership (#2859)
* [PM-1188] move ef auth files to auth folder

* [PM-1188] rename ef models namespace

* [PM-1188] fix auth ef model imports

* [PM-1188] fix ef model usings
2023-04-18 08:45:02 -04:00
Daniel James Smith
4e7b9d2edd
[PM-328] Move files for team-tools (#2857)
* Extract Import-Api endpoints into separate controller

Moved ciphers/import and ciphers/import-organization into new ImportController
Paths have been kept intact for now (no changes on clients needed)
Moved request-models used for import into tools-subfolder

* Update CODEOWNERS for team-tools-dev

* Move HibpController (reports) to tools

* Moving files related to Send

* Moving files related to ReferenceEvent

* Removed unneeded newline
2023-04-18 14:05:17 +02:00
Shane Melton
f2fad5513d
[AC-1070] Enforce master password policy on login (#2714)
* [EC-1070] Add API endpoint to retrieve all policies for the current user

The additional API endpoint is required to avoid forcing a full sync call before every login for master password policy enforcement on login.

* [EC-1070] Add MasterPasswordPolicyData model

* [EC-1070] Move PolicyResponseModel to Core project

The response model is used by both the Identity and Api projects.

* [EC-1070] Supply master password polices as a custom identity token response

* [EC-1070] Include master password policies in 2FA token response

* [EC-1070] Add response model to verify-password endpoint that includes master password policies

* [AC-1070] Introduce MasterPasswordPolicyResponseModel

* [AC-1070] Add policy service method to retrieve a user's master password policy

* [AC-1070] User new policy service method

- Update BaseRequestValidator
- Update AccountsController for /verify-password endpoint
- Update VerifyMasterPasswordResponseModel to accept MasterPasswordPolicyData

* [AC-1070] Cleanup new policy service method

- Use User object instead of Guid
- Remove TODO message
- Use `PolicyRepository.GetManyByTypeApplicableToUserIdAsync` instead of filtering locally

* [AC-1070] Cleanup MasterPasswordPolicy models

- Remove default values from both models
- Add missing `RequireLower`
- Fix mismatched properties in `CombineWith` method
- Make properties nullable in response model

* [AC-1070] Remove now un-used GET /policies endpoint

* [AC-1070] Update policy service method to use GetManyByUserIdAsync

* [AC-1070] Ensure existing value is not null before comparison

* [AC-1070] Remove redundant VerifyMasterPasswordResponse model

* [AC-1070] Fix service typo in constructor
2023-04-17 07:35:47 -07:00
Jake Fink
88dd745070
[PM-1188] Server owner auth migration (#2825)
* [PM-1188] add sso project to auth

* [PM-1188] move sso api models to auth

* [PM-1188] fix sso api model namespace & imports

* [PM-1188] move core files to auth

* [PM-1188] fix core sso namespace & models

* [PM-1188] move sso repository files to auth

* [PM-1188] fix sso repo files namespace & imports

* [PM-1188] move sso sql files to auth folder

* [PM-1188] move sso test files to auth folders

* [PM-1188] fix sso tests namespace & imports

* [PM-1188] move auth api files to auth folder

* [PM-1188] fix auth api files namespace & imports

* [PM-1188] move auth core files to auth folder

* [PM-1188] fix auth core files namespace & imports

* [PM-1188] move auth email templates to auth folder

* [PM-1188] move auth email folder back into shared directory

* [PM-1188] fix auth email names

* [PM-1188] move auth core models to auth folder

* [PM-1188] fix auth model namespace & imports

* [PM-1188] add entire Identity project to auth codeowners

* [PM-1188] fix auth orm files namespace & imports

* [PM-1188] move auth orm files to auth folder

* [PM-1188] move auth sql files to auth folder

* [PM-1188] move auth tests to auth folder

* [PM-1188] fix auth test files namespace & imports

* [PM-1188] move emergency access api files to auth folder

* [PM-1188] fix emergencyaccess api files namespace & imports

* [PM-1188] move emergency access core files to auth folder

* [PM-1188] fix emergency access core files namespace & imports

* [PM-1188] move emergency access orm files to auth folder

* [PM-1188] fix emergency access orm files namespace & imports

* [PM-1188] move emergency access sql files to auth folder

* [PM-1188] move emergencyaccess test files to auth folder

* [PM-1188] fix emergency access test files namespace & imports

* [PM-1188] move captcha files to auth folder

* [PM-1188] fix captcha files namespace & imports

* [PM-1188] move auth admin files into auth folder

* [PM-1188] fix admin auth files namespace & imports
- configure mvc to look in auth folders for views

* [PM-1188] remove extra imports and formatting

* [PM-1188] fix ef auth model imports

* [PM-1188] fix DatabaseContextModelSnapshot paths

* [PM-1188] fix grant import in ef

* [PM-1188] update sqlproj

* [PM-1188] move missed sqlproj files

* [PM-1188] move auth ef models out of auth folder

* [PM-1188] fix auth ef models namespace

* [PM-1188] remove auth ef models unused imports

* [PM-1188] fix imports for auth ef models

* [PM-1188] fix more ef model imports

* [PM-1188] fix file encodings
2023-04-14 13:25:56 -04:00
Colton Hurst
2529c5b36f
SM-695: Block Create & Update for Admins on Secrets Outside of the Org (#2844)
* SM-695: Block create or update for admins on secrets outside of the org

* SM-695: Update test, org is required on project

* SM-695: Update tests to set matching org id in project

* SM-695: Ensure there is no more than 1 project connected to a secret, plus remove org admin check in the CreateSecretCommand.

* SM-695: Add integration tests for create and update secrets security fixes

* SM-695: Update Create and Update secret tests, a secret can only be in one project at a time
2023-04-14 09:48:11 -04:00
Rui Tomé
f5a8cf5c9c
[AC-1081] Merge feature/billing-obfuscation (#2665)
* [EC-1014] Create Organization Status (Pending/Created) (#2610)

* [EC-427] Add columns 'Type' and 'BillingPhone' to Provider table

* [EC-427] Provider table Type and BillingPhone MySql migrations

* [EC-427] Provider table Type and BillingPhone Postgres migrations

* [EC-427] Add mysql migration script

* [EC-427] Add mysql migration script

* [EC-427] Updated Provider sql script to include default column value

* [EC-427] Removed default value from Provider.Type column

* [EC-427] Changed migration script to include a default value constraint instead of updating the null type

* [EC-427] Updated Sql project Provider table script

* [EC-427] Changed migration script to use 'Create OR Alter' for views and sprocs

* [EC-427] Added default values for 'BillingPhone' and 'Type' fields on sprocs [dbo].[Provider_Create] and [dbo].[Provider_Update]

* [EC-427] Adjusting metadata in migration script

* [EC-427] Updated Provider sprocs SQL script files

* [EC-427] Fixed migration script

* [EC-427] Added sqlite migration

* [EC-427] Add missing Provider_Update sproc default value

* [EC-427] Added missing GO action to migration script

* [EC-428] Redirect to Edit after creating Provider

* Revert "[EC-428] Redirect to Edit after creating Provider"

This reverts commit 6347bca1ed.

* [EC-1014] Create OrganizationStatusType and add Status column to Organizations table

* [EC-1014] Added EF migrations

* [EC-1014] dotnet format

* [EC-1014] Changed Organization.Status from SMALLINT to TINYINT

* [EC-1014] Set Organization.Status default value = 1

* [EC-1014] Setting Organization.Status default value as 1

* [EC-459 / EC-428] Admin panel: Add Provider Type to list and creation flow (#2593)

* [EC-427] Add columns 'Type' and 'BillingPhone' to Provider table

* [EC-427] Provider table Type and BillingPhone MySql migrations

* [EC-427] Provider table Type and BillingPhone Postgres migrations

* [EC-427] Add mysql migration script

* [EC-427] Add mysql migration script

* [EC-427] Updated Provider sql script to include default column value

* [EC-427] Removed default value from Provider.Type column

* [EC-427] Changed migration script to include a default value constraint instead of updating the null type

* [EC-427] Updated Sql project Provider table script

* [EC-427] Changed migration script to use 'Create OR Alter' for views and sprocs

* [EC-427] Added default values for 'BillingPhone' and 'Type' fields on sprocs [dbo].[Provider_Create] and [dbo].[Provider_Update]

* [EC-427] Adjusting metadata in migration script

* [EC-427] Updated Provider sprocs SQL script files

* [EC-427] Fixed migration script

* [EC-427] Added sqlite migration

* [EC-427] Add missing Provider_Update sproc default value

* [EC-427] Added missing GO action to migration script

* [EC-459] Added Type column to Providers list

* [EC-428] Added Type, BusinessName and BillingEmail to CreateProviderModel

* [EC-428] Updated Create Provider view to include new fields

* [EC-428] Updated ProviderService to not create a ProviderUser for the type Reseller

* [EC-428] Added custom validation for Provider fields depending on selected Type

* [EC-428] Redirect to Edit after creating Provider

* [EC-428] Setting Provider status as Created for Resellers

* [EC-428] Redirect on Provider creation depending if self host server

* [EC-428] Split ProviderService.CreateAsync into two methods: CreateMspAsync and CreateResellerAsync

* [EC-428] Created ICreateProviderCommand and added service for injection on Admin.Startup

* [EC-428] Modified Provider views to use DisplayName attribute values

* [EC-428] Moved ICreateProviderCommand to Core project

* [EC-428] Adding ICreateProviderCommand injection next to IProviderService

* [EC-428] Moved CreateProviderCommand to Commercial.Core project

* [EC-459] Added Type column to Providers list

* [EC-428] Added Type, BusinessName and BillingEmail to CreateProviderModel

* [EC-428] Updated Create Provider view to include new fields

* [EC-428] Updated ProviderService to not create a ProviderUser for the type Reseller

* [EC-428] Added custom validation for Provider fields depending on selected Type

* [EC-428] Redirect to Edit after creating Provider

* [EC-428] Setting Provider status as Created for Resellers

* [EC-428] Redirect on Provider creation depending if self host server

* [EC-428] Split ProviderService.CreateAsync into two methods: CreateMspAsync and CreateResellerAsync

* [EC-428] Created ICreateProviderCommand and added service for injection on Admin.Startup

* [EC-428] Modified Provider views to use DisplayName attribute values

* [EC-428] Moved ICreateProviderCommand to Core project

* [EC-428] Adding ICreateProviderCommand injection next to IProviderService

* [EC-428] Moved CreateProviderCommand to Commercial.Core project

* [EC-428] Moved CreateProviderCommand to namespace Bit.Commercial.Core.Providers

* [EC-429] Provider details screen updated with Type, BillingPhone and Organization details (#2666)

* [EC-430] Admin portal: Update organization information screen (#2672)

* [EC-430] Added ProviderOrganizationProviderDetailsView to get Provider details for an Organization

* [EC-430] Added Provider information to Organization Edit/View on Admin panel

* [EC-430] Remove "Add to Reseller" button

* [EC-430] Removed unused property OrganizationEditModel.ClientOwnerEmail

* [EC-430] Replaced IProviderOrganizationRepository.GetProviderDetailsByOrganizationAsync with IProviderRepository.GetByOrganizationIdAsync

* [EC-430] Deleted ProviderOrganizationProviderDetails and ProviderOrganizationProviderDetailsReadByOrganizationIdQuery

* [EC-429] Only show Create/Add Existing Organization buttons for Reseller providers (#2723)

* [EC-432] Add existing Organizations to Provider (#2683)

* [EC-432] Added ProviderOrganizationUnassignedOrganizationDetails_Search stored procedure

* [EC-432] Added IProviderOrganizationRepository.SearchAsync

* [EC-432] Created controller ProviderOrganizationsController to assign Organizations to a Provider

* [EC-432] Filter existing organizations by plans Enterprise or Team

* [EC-432] Existing Organization name links to edit page

* [EC-432] EF filtering out existing organizations by plan type enterprise or teams

* [EC-432] Creating multiple ProviderOrganization records

* [EC-432] Added ProviderOrganizationUnassignedOrganizationDetails_Search stored procedure

* [EC-432] Added IProviderOrganizationRepository.SearchAsync

* [EC-432] Created controller ProviderOrganizationsController to assign Organizations to a Provider

* [EC-432] Filter existing organizations by plans Enterprise or Team

* [EC-432] Existing Organization name links to edit page

* [EC-432] EF filtering out existing organizations by plan type enterprise or teams

* [EC-432] Creating multiple ProviderOrganization records

* [EC-432] Renamed migration script and added missing sproc

* [EC-432] Saving multiple events for the created ProviderOrganizations

* [EC-432] Included unit testing for ProviderService.AddOrganizations and EventService.LogProviderOrganizationEventsAsync

* [EC-432] Removed async from NoopEventService.LogProviderOrganizationEventsAsync

* [EC-432] Remove unused dependency setup in ProviderServiceTests.AddOrganizations_Success

* [EC-432] Renamed AddOrganizations to AddOrganizationsToReseller and removed addingUserId and key arguments

* [EC-432] Added DisplayName attributes to ProviderOrganizationViewModel and used them in the view

* [EC-432] Reverted changes to input fields

* [EC-432] Moved unassigned organizations search to Organizations repo

* [EC-432] Moved AddExistingOrganization action to ProvidersController

* [EC-432] dotnet format

* [EC-432] Fixed unit test issues

* [EC-432] Removed unnecessary Html.DisplayNameFor for labels

* [EC-432] Renamed OrganizationSearchViewModel to OrganizationUnassignedToProviderSearchViewModel

* [EC-432] Modified IEventService.LogProviderOrganizationEventsAsync to receive an IEnumerable as parameter

* [EC-432] Updated IProviderOrganizationRepository and replaced CreateWithManyOrganizations method with CreateManyAsync

* [EC-432] Deleted ProviderOrganization_CreateWithManyOrganizations

* [AC-432] Simplified Organization_UnassignedToProviderSearch query

* [AC-432] Removed unnecessary setup

* [EC-432] Checking if stored procedure exists before creating

* [EC-432] Renamed migration file to recent date

* [EC-435] Admin Portal: Add new Organization creation flow UI (#2707)

* [EC-435] Created _OrganizationForm partial view. Added actions for creating an Organization assigned to a provider

* [EC-435] Remove logic for creating an organization

* [EC-435] Created partial view _OrganizationFormScripts

* [EC-435] Remove unused ReferenceEventType

* [EC-435] Added TODO comment on Organization Create

* [EC-435] Checking if Provider type is Reseller on creating new assigned organization

* [EC-435] Setting the Organization plan type as TeamsMonthly by default when adding to a provider

* [EC-435] Removing unused buttons

* [EC-435] Switched hidden fields to form submit route value

* [EC-435] Moved _OrganizationForm and _OrganizationFormScripts to Shared folder

* [EC-435] Moved Create organization actions from OrganizationsController to ProvidersController

* [EC-435] Fixing bug on saving Organization that would have BillingEmail as null

* [EC-435] Added null check to Provider

* [EC-435] Moved trial buttons script logic to Edit view

* [AC-431] Add new organization invite process (#2737)

* [EC-435] Created _OrganizationForm partial view. Added actions for creating an Organization assigned to a provider

* [EC-435] Remove logic for creating an organization

* [EC-435] Created partial view _OrganizationFormScripts

* [EC-435] Remove unused ReferenceEventType

* [EC-435] Added TODO comment on Organization Create

* [EC-435] Checking if Provider type is Reseller on creating new assigned organization

* [EC-435] Setting the Organization plan type as TeamsMonthly by default when adding to a provider

* [EC-435] Removing unused buttons

* [EC-435] Switched hidden fields to form submit route value

* [EC-435] Moved _OrganizationForm and _OrganizationFormScripts to Shared folder

* [EC-435] Moved Create organization actions from OrganizationsController to ProvidersController

* [AC-431] Added new ReferenceEventType OrganizationCreatedByAdmin

* [AC-431] Added method IOrganizationService.CreateOrganization

* [AC-431] Creating new Organization with Pending status and assigning to Provider

* [AC-431] Added method to IMailService to send invitation to initialize org

* [AC-431] Added methods CreatePendingOrganization and InitPendingOrganization to IOrganizationService

* [AC-431] Org invite includes initOrganization parameter

* [AC-431] Modified existing Accept organization user action to initialize org

* [AC-431] Updated ProvidersController method name

* [AC-431] Created OrganizationUserInitInvitedViewModel to link to 'accept-init-organization' url

* [AC-431] Added action AcceptInit to OrganizationUsersController

* [AC-431] Resend owner invite

* [AC-431] dotnet format

* [AC-431] Removed unused parameter 'addingUserId' from IProviderService.AddOrganization

* [AC-431] Removed setting manual values for CreationDate and RevisionDate

* [AC-431] Updated OrganizationService.InitPendingOrganization to throw exceptions when the Organization does not meet the required criteria

* [AC-431] Modified OrganizationUserInitInvitedViewModel to inherit properties from OrganizationUserInvitedViewModel

* [AC-431] Removed unecessary parameter check

* [AC-431] Moved method description to IOrganizationService.InitPendingOrganization

* [AC-431] Moved ApplicationCacheService.UpsertOrganizationAbilityAsync and ReferenceEventService.RaiseEventAsync to OrganizationService

* [AC-431] Creating collection after creating organization

* [EC-435] Fixing bug on saving Organization that would have BillingEmail as null

* [AC-431] Deleted OrganizationUserInitInvitedViewModel and added parameter InitOrganization to OrganizationUserInvitedViewModel.cs

* [AC-431] Checking if the user has any existing SingleOrg policies before initializing an Org

* [AC-431] Remove commented code

* [EC-435] Added null check to Provider

* [EC-435] Moved trial buttons script logic to Edit view

* [AC-431] Added EncryptedString attribute to OrganizationUserAcceptInitRequestModel.CollectionName

* [AC-431] Refactored plan check condition

* [AC-431] Remove duplicate _applicationCacheService.UpsertOrganizationAbilityAsync call

* [AC-431] Removed IMailService.SendOrganizationInitInviteEmailAsync

* [AC-431] Added parameters ClaimsPrincipal and IUserService to IOrganizationService.CreatePendingOrganization

* [AC-434] Hide Billing screen for Reseller clients (#2783)

* [AC-434] Added ProviderType to ProfileOrganizationResponseModel

* [AC-434] Migration script

* [AC-434] Fixed indentation on migration script

* [AC-434] Hiding sensitive subscription data if the user does not have permissions

* [AC-434] Fixed missing dependency in unit test

* [AC-434] Altered BillingSubscription.Amount and BillingSubscriptionUpcomingInvoice.Amount to nullable

* [AC-434] Replaced CurrentContext.ManageBilling with ViewBillingHistory, ViewSubscription, EditSubscription and EditPaymentMethods

* [AC-434] Reverted change on BillingSubscription.Amount and now setting Subscription.Items = null when User does not have permission

* [AC-434] Added ProviderOrganizationProviderDetails_ReadByUserId

* [AC-434] Added IProviderOrganizationRepository.GetManyByUserAsync

* [AC-434] Added CurrentContext.GetOrganizationProviderDetails

* [AC-434] Remove unneeded join Organization table

* [AC-1255] Search Existing Organizations by partial Email (#2830)

* [AC-1255] Added email search field input validation

* [AC-1255] Reverted added email pattern

* [AC-1255] Modified Organization search by Email to search using substring

* [AC-1276] Displaying an Organizations pending owners if the Organization is in a Pending status (#2834)

* [AC-432] Checking that an existing Organization is not assigned to any Provider before being assigned (#2840)

* [AC-432] Checking if any of the selected Organizations is already assigned to a Provider

* [AC-432] Changed ProviderOrganization_ReadByOrganizationIds to only get count

* [AC-432] Replaced IProviderOrganizationRepository.GetCountByOrganizationIdsAsync with call to IProviderOrganizationRepository.GetByOrganizationId

* [AC-432] undo new line

* [AC-432] Fixed unit test

* Revert "[AC-432] Replaced IProviderOrganizationRepository.GetCountByOrganizationIdsAsync with call to IProviderOrganizationRepository.GetByOrganizationId"

This reverts commit ee6e095e88.

# Conflicts:
#	util/Migrator/DbScripts/2023-03-22_00_ProviderAddExistingOrganizations.sql

* [AC-432] Created new migration script for ProviderOrganization_ReadCountByOrganizationIds
2023-04-14 11:13:16 +01:00
Justin Baur
ecf885f4d6
Update Azure.Extensions.AspNetCore.DataProtection.Blobs (#2821) 2023-04-10 12:10:11 -04:00
cyprain-okeke
141c6862ca
[AC 482]automatically apply discounts to provider portal orgs (#2801)
* Adding discount coupon on provider org creation

* Change the provider discount Id

* Fixing the whitespace format

* Remove discount at subscription and apply to customer

* resolving a failing test

* Remove white spaces
2023-04-10 14:40:04 +01:00
cyprain-okeke
6d7bcd98a9
[AC 480]Add the organization name to the stripe invoice (#2772)
* Adding organization name on subscription and update

* Changes after running  dotnet format -v diag

* Change the OrganizationName to GetName

* Change GetName to OwnerName

* Change the OwnerName to SubscriberName

* Reverting the changes made by dotnet format-v diag

* Removing extract space

* resolve the lint issue

* Fix whitespace formatting issue

* Resolving pr comment on changing organization

* Fixing the failing test

* Using the ISubscriber interface for consistent

* fixing the whitescapes

* Resolving the PR comments

* resolving the whitespace format

* Remove unnecessary directive

* Resolving the whitespace issue

* changes for organization instead of subscriber

* resolving the failing test

* Resolve lint issue by removing unnecessary directive

* Resolve the PR comment

* remove these blank lines

* Fixing whitespace formatting
2023-04-07 10:45:18 +01:00
Oscar Hinton
60bdf77e8b
[SM-574] Wire up read/write for secret list and secret response (#2767)
* Wire up read/write for secret list and secret response

* Fix trash

* Remove UserHasReadPermission

* Fix list by project

* Implement admin and service accounts for AccessToSecretAsync

* Resolve feedback

* Fix tests

* Rename function

* Change create to return true, true

* Remove duplicated access check
2023-03-30 16:51:46 +02:00
Oscar Hinton
60fcc79f97
[SM-680] Add reference event logging to secrets (#2824)
* Add reference event logging to secrets

* Change to IHostEnvironment

* Fix namespace for ef service collection
2023-03-30 15:37:19 +02:00
Matt Bishop
39f884ddcc
Provide anonymous user context for unauthenticated requests using LaunchDarkly (#2819) 2023-03-22 11:05:09 -04:00
Colton Hurst
d7b091d7d6
SM-662: Make sm controller test class names plural (#2816) 2023-03-22 11:04:50 -04:00
Thomas Avery
56d3c3a5d1
Add in integration tests (#2806) 2023-03-21 17:12:13 -05:00
André Bispo
2e3e96a25c
[PM-1095][PM-1104] Update email template (#2746)
* [SG-994] Add import Open Sans font to full template

* [SG-994] Update organization user invite email template to new UI

* [SG-994] update alt text for mobile app download buttons

* [SG-994] Update copy. Add hyperlinks to stores.

* [SG-944] Improve layout responsiveness

* [PM-1095][PM-1104] Add new template for title and contact us. Add new template for user organization invite

* [PM-1095][PM-1104] Remove wrong text from free invite

* [PM-1104][PM-1095] Add bold class. Add margin.

* [PM-1104][PM-1095] Change font type to previously used

* [PM-1104][PM-1095] Remove Open Sans font

* [PM-1104][PM-1095] Improve browsers rendering compatibility

* [PM-1104][PM-1095] Fixed margins

* [PM-1095][PM-1104] Remove unnecessary string sanitise.
2023-03-21 14:44:58 +00:00
Matt Bishop
3d0ca908ff
Use all organization memberships for LaunchDarkly user context, better separate context kinds (#2807)
* Use all organization memberships for LaunchDarkly context

* Use simpler null check

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* Remove unnecessary interpolation

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* Remove unnecessary interpolation

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* Fully spell out organizations

* Use client type for context separation decisions

---------

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>
2023-03-20 11:48:45 -04:00
Colton Hurst
1dc9aad1f1
SM-655: Add Authorizations and Tests for the SM Porting Controller (#2802)
* SM-655: Add Authorize attribute for secrets on the SM Porting Controller

* SM-655: Add access secrets manager check to SM Import and Export

* SM-655: Add tests for export and import endpoints
2023-03-15 11:51:01 -04:00
Justin Baur
388caa28f8
Remove Visual Studio Code Generation Package (#2749) 2023-03-14 15:44:53 -04:00
André Bispo
3008759e8a
[PM-1317] Make fingerprint phrase property optional. (#2796) 2023-03-13 15:43:44 +00:00
Jake Fink
dafcdde715
[AC-1110] add deleteAnyCollection permission to bulk delete (#2766)
* [AC-1110] add deleteAnyCollection permission to bulk delete

* [AC-1110] call collection service instead of repo for user collections

* [AC-1110] fix tests

* [AC-1110] fix more tests
2023-03-10 12:53:22 -05:00
Colton Hurst
397f3d6865
SM-561: Update Secret Revision Dates (#2770)
* SM-561: Update secret revision date on restore

* SM-561: Update secret revision dates when a project is deleted

* SM-561: Fix bug when updating revision dates for secrets when their parent project is deleted

* SM-561: Handle case when there are no secrets in the projects that are being deleted

* SM-561: Rename func to GetManyWithSecretsByIds and move UpdateRevisionDates call from ProjectsController to projects delete command

* SM-561: update secret ids before project deletion

* SM-561: Refactor out command in command call to follow CQRS pattern

* SM-561: Remove null check
2023-03-10 11:54:19 -05:00
Matt Bishop
bd666841a5
All feature state access through config API (#2785) 2023-03-10 08:11:11 -05:00
Oscar Hinton
6a6b15fada
[SM-567] Change how project permission is resolved (#2791)
* Change how project permission is resolved

* Fix tests

---------

Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>
2023-03-09 11:23:50 -06:00
Matt Bishop
11c59addf4
[PM-1012] Feature access using context (#2764)
* Document online method

* Feature accessors with context

* Direct null assertion

* Establish a constants class for flag keys
2023-03-07 13:46:52 -05:00
Thomas Avery
c27b323ef2
[SM-604] Filter for only confirmed Org users in potential grantees (#2773)
* Filter for only confirmed users

* Take out assert.recent for long running test
2023-03-07 09:03:09 -06:00
Oscar Hinton
2c8f23ec9b
[SM-579] Prevent creating secrets not attached to projects (#2754)
* Prevent creating secrets not attached to projects, and prevent updating secrets to remove project relation

* Fix test
2023-03-07 10:13:49 +01:00
Oscar Hinton
a0df350ea3
[SM-568] Delete service accounts (#2748) 2023-03-06 20:25:27 +01:00
Thomas Avery
de559e80f4
[SM-581] Adding support for warning dialogs (#2762)
* Adding support for warning dialogs

* Swap to repository layer implementation
2023-03-06 11:31:56 -06:00
Matt Bishop
27adaf59b4
[PM-1011] LaunchDarkly service (#2726)
* LaunchDarkly service

* Load file-based flag values, properly support offline only when self-host

* Simplify tests

* Use interface for LD settings

* Remove tests that will provide inconsistent results depending on machine setup and file fallback

* Fall back to offline mode more actively

* Drive fallback file path with setting
2023-03-02 14:04:23 -05:00
Robyn MacCallum
3289a8c35e
[SG-998] Move files to Vault folders (#2724)
* Move Api files

* Move Core files

* Move Infrastructure files

* Move Sql Files

* Move Api Sync files to Vault

* Move test vault files

* Update Sql.sqlproj paths

* Update Codeowners

* Fix vault file paths in sqlproj

* Update CipherDetails.sql path in sqlproj

* Update Core models and entities namespaces

* Update namespaces Core Services and Repositories

* Missed service namespaces

* Update Api namespaces

* Update Infrastructure namespaces

* Move infrastructure queries that were missed

* Tests namespace updates

* Admin and Events namespace updates

* Remove unused usings

* Remove extra CiphersController usings

* Rename folder

* Fix CipherDetails namespace

* Sqlproj fixes

* Move stored procs into folders by table

* using order fix
2023-03-02 13:23:38 -05:00
Thomas Avery
05f5d79938
[SM-572] Modify project endpoint to return current user's permission (#2752)
* Add endpoints to check current user's permission

* Swap to adding current user permission onto GET

* Cleanup DI

* Add ProjectPermissionDetails DTO and query

* code review updates

* Remove assert recent for longer running creates
2023-03-02 09:02:42 -06:00
Thomas Rittson
4643f5960e
[EC-635] Extract organizationService.UpdateLicenseAsync to a command (#2408)
* move UpdateLicenseAsync from service to command
* create new SelfHostedOrganizationDetails view model and move license validation logic there
* move occupied seat count logic to database level
2023-02-24 07:54:19 +10:00
Colton Hurst
16bdd67cad
SM-281: Secrets Manager Trash (#2688) 2023-02-20 13:01:49 -05:00
Federico Maccaroni
69511160cb
[EC-400] Code clean up Device Verification (#2601)
* EC-400 Clean up code regarding Unknown Device Verification

* EC-400 Fix formatting
2023-02-17 10:15:28 -03:00
cd-bitwarden
ec8476912d
[SM-381] New secrets access (#2629)
* [SM-66] Create Secret Database Table (#2144)

Objective
The purpose of this PR is to create a database table, entity, and repository for the new Secret database table.

The new Secret table will use entity framework for all database providers.

* [SM-67] Get all secrets by org ID (#2163)

Add a controller to fetch secrets associated with an organization ID.

To note, the [SecretsManager] attribute makes this controller only available for local development.

* [SM-68] Add API endpoints for getting, creating, and editing secrets (#2201)

The purpose of this PR is to add API endpoints for getting, creating, and editing secrets for the Secrets Manager project.

* Move interfaces to core (#2211)

* [SM-63] Read UTC DateTimes from databases via EF and order by revision date (#2206)

* Read UTC DateTimes from db and order by revision

* Move orderby to repo layer

* [SM-185] Add EE_Testing_env to server (#2222)

* Sm 104 project Database (#2192)

* Project DB addition and sprocs

* Adding spaces to the end of each file, fixing minor issues

* removing useless comments

* Adding soft delete proc to migration

* Project EF Scaffold

* Additional changes to use EF instead of procedures

* Adding dependency injection

* Fixing lint errors

* Bug fixes

* Adding migration scripts, removing sproc files, and setting up Entity framework code

* Adding back accidentally deleted sproc

* Removing files that shouldn't have been created

* Lint

* Small changes based on Oscar's rec (#2215)

* Migrations for making CreateDate not null

* adding space to end of file

* Making Revision date not null

* dotnet format

* Adding nonclustered indexes to SQL

* SM-104: Update PR with changes Thomas proposed

Co-authored-by: CarleyDiaz-Bitwarden <103955722+CarleyDiaz-Bitwarden@users.noreply.github.com>
Co-authored-by: Thomas Avery <tavery@bitwarden.com>
Co-authored-by: Colton Hurst <colton@coltonhurst.com>

* Removing org ID from create request body (#2243)

* SM-114: Add create & update project endpoints (#2251)

* SM-114: Initial commit with create project endpoint (for SM)

* SM-114: Add Update Project route (for SM)

* SM-114: Fix file encodings

* Fix DI issue for SM Project Create/Update commands

* Fix import ordering for linter

* SM-114: Remove unneeded lines setting DeletedDate, as it should already be null

* SM-114: Only have OrgId in route for CreateProject

* Remove unneeded using

* SM-114: Initial commit with create project endpoint (for SM)

* SM-114: Add Update Project route (for SM)

* SM-114: Fix file encodings

* Fix DI issue for SM Project Create/Update commands

* Fix import ordering for linter

* SM-114: Remove unneeded lines setting DeletedDate, as it should already be null

* SM-114: Only have OrgId in route for CreateProject

* Remove unneeded using

* Fully remove OrgId from ProjectCreateRequestModel

* [SM-64] Soft Delete Secrets (#2253)

* Bulk delete secrets with command unit tests

* Controller unit tests

* Optimize conditionals

* SM-64 bulk delete integration test

* fix test

* SM-64 code review updated

* [SM-65] Fix return empty secrets list (#2281)

* Secrets return empty list

* [SM-246] Use repository in integration test (#2285)

* [SM-190] Add integration tests to Secrets (#2292)

* Adding integration tests for the SecretsController

Co-authored-by: Hinton <hinton@users.noreply.github.com>

* Sm 95 - Adding GetProjects endpoint (#2295)

* SM-114: Initial commit with create project endpoint (for SM)

* SM-114: Add Update Project route (for SM)

* SM-114: Fix file encodings

* Fix DI issue for SM Project Create/Update commands

* Adding GetProjectsByOrg

* fixing merge conflicts

* fix

* Updating to return empty list

* removing null check

Co-authored-by: Colton Hurst <colton@coltonhurst.com>
Co-authored-by: CarleyDiaz-Bitwarden <103955722+CarleyDiaz-Bitwarden@users.noreply.github.com>

* [SM-191] Create ServiceAccount Table (#2301)

* SM-191 Create ServiceAccount Table

* [SM-207] API for listing service accounts by organization (#2307)

* SM-207 list service accounts by org

* SM-96: Add ability to get project by id (#2314)

* SM-96: Small change to allow getting project by id

* Fix whitespace issue

* Add first integration test and fix date bug

* Ensure tests are consistent

* Add more project controller integration tests

* Remove commented delete for now

* [SM-187] Create ServiceAccounts (#2323)

* SM-187 Create & Update ServiceAccounts

* Remove extra new line src/Api/Controllers/ServiceAccountsController.cs

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* [SM-218] [SM-219] SM Auth flow (#2297)

* SM-282 Delete Projects (#2335)

* SM-282 delete & bulk delete projects

* Have delete commands return tuple with object

* Fix admin project not working after secrets manager changes (#2339)

* [SM-150] proj and secrets mapping (#2286)

* Beggining of changes for Project Secrets mapping

* Beggining of changes for project and secrets mapping

* Inital changes to add Mapping table for Project Secrets

* Resolve migration not working properly

* Indent sql

* Changes to try and return projects in the GetManyByOrganizaationIDAsync on SecretRepository.

* Changes made with Oscar

* Add reversemap

* running lint and removing comments

* Lint fixes

* fixing merge issues

* Trying to fix the DB issue

* DB fixes

* fixes

* removing unused space

* fixing lint issue

* final lint fix I hope

* removing manually added sql.sqlproj

* Lint changes and fixing the sql proj issues

* adding ServiceAccount to sql proj

* Removing ON DELETE CASCADE

* remove On delete cascade

* changes for deleting project and secret inside of the Organization_DeleteById procedure.

* changes for deleting project and secret inside of the Organization_DeleteById procedure.

* migration changes

* Updating constraints

* removing void

* remove spaces

* updating cipherRepo tests to be task instead of void

* fixing

* fixing

* test

* fix

* fix

* changes to remove circular dependency

* fixes

* sending guid and string name of the project over

* Update src/Sql/dbo/Tables/Secret.sql

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* Update src/Sql/dbo/Tables/Project.sql

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* removing unused code

* Potential refactor (#2340)

* migrations

* Postgres migraiton

* Update src/Api/SecretManagerFeatures/Models/Response/SecretResponseModel.cs

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* rename file

* Update util/Migrator/DbScripts/2022-09-19_00_ProjectSecret.sql

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* Lint fixes

* removing extra semi colon

* removing circular references with projects and secrets

* adding back projects

* Add ProjectFixture

* Update util/Migrator/DbScripts/2022-09-19_00_ProjectSecret.sql

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* Update util/Migrator/DbScripts/2022-09-19_00_ProjectSecret.sql

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

Co-authored-by: CarleyDiaz-Bitwarden <103955722+CarleyDiaz-Bitwarden@users.noreply.github.com>
Co-authored-by: Hinton <hinton@users.noreply.github.com>

* [SM-300] Access token endpoint (#2377)

* [SM-324] Add Organization to JWT claim (#2379)

* [SM-259] Add create access token endpoint for service accounts (#2411)

* Add create access token for service accounts

* [SM-259] Fix create access token scope initialization (#2418)

* Fix namespace for ServiceAccount command tests

* Remove "this" from SecretsManager requests

* Fix have scope be assigned a JSON list

* SM-99: Individual Project / Secrets Tab (#2399)

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* [SM-361] Add Support for never expiring ApiKeys (#2450)

* Update database to support never expiring ApiKey

* Update Api to support never expiring ApiKeys

* Fix unit test variable naming

* Remove required from model

* Fix spacing

* Add EF migrations

* Run dotnet format

* Update util/Migrator/DbScripts/2022-11-29_00_ApiKey_Never_Expire.sql

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>

* [SM-359] Fix project secrets migration (#2443)

* [SM-299] Add UseSecretsManager flag (#2413)

* [SM-193] Access Policy (#2359)

* [SM-371] Fix and re-enable parallel integration tests (#2460)

* Fix and re-enable parallel integration tests

* Fix package lock files

* Move fix to ApiApplicationFactory

* Run dotnet restore --force

* Run dotnet format

* Reset packages.lock.json files

* Add project access checks for listing

* SM-99: Add CreateSecretWithProject Integration Test (#2452)

* Add GetSecretsByProjectAsync endpoint

* Add GetManyByProjectIdAsync endpoint

* Update response model for GetSecretsByProjectAsync

* Include projects when returning secrets by project id

* SM-99: Add ability to specify projectId when creating a secret

* SM-99: Update tests to accomodate for new create secret parameter

* Fix failing test

* SM-99: Handle optional projectId for new secret in ToSecret()

* SM-99: Filter out deleted secrets on GetManyByProjectIdAsync() and small refactorings

* SM-99: make CreateAsync for secret more clear

* Add CreateSecretWithProject integration test

* Fix CreateSecretWithProject integration test for SM-99

* Run dotnet format

* Undo added space

* Refactor test

* Refactor CreateSecretWithProject API Integration test again

* Change to boolean flag

* [SM-379] Add SDK device type (#2486)

* Add support for service accounts

* Improve logic for project repository

* Add remaining client types

* Experiment with separate enum for access control

* Add access checks to update project

* Rework AccessClientType

* Add access checks to fetching project

* Add checks to delete project command (untested)

* Remove some service account stuff

* Add ServiceAccount to AccessClientType

* Change CS8509 to error and 8424 to ignore

* Remove unused utcNow

* Fix delete tests

* SM-73 changes (#2422)

* testing

* test2

* testing

* trying to save the projects associated with the secret

* changes

* more changes

* Fix  EF error

* Second attempt

* Replace AddIfNotExists with Add.

* changes

* fixing await issue

* lint

* lint fixes

* suggested changes

* suggested changes

* updating tests

* fixing tests 2

* fixing tests

* fixing test

* fixing test

* fixing tests

* test

* testing

* fixing tests for the millionth time

* fixing tests

* allowing nulls for projectIds, fixing lint

* fixing tests

Co-authored-by: Hinton <hinton@users.noreply.github.com>

* fixing tests

* fixing tests

* [SM-222] [SM-357] Squash Secrets Manager migrations (#2540)

* Fix tables not being cleaned up

* Fix migration

* Squash secrets manager migrations

* Reset EF to pre SM state

* Add EF migrations

* Fix unified docker

* Add missed copy

* Fix all unit tests

* draft changes to add access checks to secrets

* updating code

* more changes

* fixing issues

* updating logic for access checks

* updating secrets controller

* changes

* changes

* merging more

* changes

* updateS

* removing unused comment

* changes requested by Thomas

* more changes suggested by Thomas

* making thomas's suggested changes

* final changes

* Run dotnet format

* fixes

* run dotnet format

* Updating tests

* Suggested changes

* lint fixes

* Test updates

* Changes

* Fixes for tests, and dotnet format

* Fixes

* test fixes

* changes

* fix

* fix

* test fix

* removing duplicate

* Removing dupe

---------

Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>
Co-authored-by: Oscar Hinton <Hinton@users.noreply.github.com>
Co-authored-by: CarleyDiaz-Bitwarden <103955722+CarleyDiaz-Bitwarden@users.noreply.github.com>
Co-authored-by: Thomas Avery <tavery@bitwarden.com>
Co-authored-by: Colton Hurst <colton@coltonhurst.com>
2023-02-16 11:42:07 -08:00
Thomas Avery
f288787a45
[SM-495] Access Policies - Individual Service Account - Project Tab (#2697)
* New endpoints to support sa projects tab

* Refactor create; Add tests

* Add creation request limit
2023-02-16 09:47:34 -06:00
Oscar Hinton
7a209aa3bb
[SM-501] Add support for revoking access tokens (#2692)
* Add support for revoking access tokens
2023-02-16 10:51:02 +01:00
SmithThe4th
9a484bec07
[SG-147] Organization Domain Claiming Feature (#2704)
* [SG-696] Organization Domain Claiming DB Objects and Migrations (#2394)

* model organization domain claiming

* Added migration scripts and db objects for mssql

* create and implement sql repository abstraction

* Added ef migrations for mysql and postgres. Removed time without timezone in previous migration

* made update on sql migration to use create or alter statement

* removed active column from OrganizationDomain table and decided to go with the hard delete approach

* Ran dotnet restore evaluate

* created DNS service verification using DNSClient (#2401)

* [SG-678] Api Endpoints for Domain Claiming (#2430)

* Added stored procedure to read claimed domains

* Updated Organization Domain Repository to include method to get claimed domains

* Updated domain entity and added request model

* Implemented organization domain respository and regsitered it in the various extensions

* Added create endpoint, request, responses and command

* Added endpoint to get domain by domain entry id

* Ran lint fix

* Added new stored procedure to get domains by organizattion id

* Moved migration scripts to init migration and added new procedure

* Renamed from domainId to Id

* Added and implemented GetDomainByOrganizationId

* Completed GetDomainByOrgId endpoint and started work on verify domain endpoint

* Updated the OrganizationDomain update procedure

* Added delete command and include other endpoints in the controller

* Remove test item from controller

* Remove test item from controller

* Changed access to allow admin, owners and manage sso roles

* changed logic for setting the initial value for the NextRunCount

* Renamed NextRunCount to JobRunCount

* Renamed NextRunCount to JobRunCount on mysql

* Renamed NextRunCount to JobRunCount on postgres

* Removed chaining pattern and added logic to get next run date

* Lint fix

* Added stored procedure to get organization sso details by email address

* Added endpoint to get sso details of an organization with email

* Added organizationDomainRepository to OrganizationController test

* merged with master and fixed conflicts

* [SG-661] Background Domain Verification Service (#2455)

* Added stored procedure to read claimed domains

* Updated Organization Domain Repository to include method to get claimed domains

* Updated domain entity and added request model

* Implemented organization domain respository and regsitered it in the various extensions

* Added create endpoint, request, responses and command

* Added endpoint to get domain by domain entry id

* Ran lint fix

* Added new stored procedure to get domains by organizattion id

* Moved migration scripts to init migration and added new procedure

* Renamed from domainId to Id

* Added and implemented GetDomainByOrganizationId

* Completed GetDomainByOrgId endpoint and started work on verify domain endpoint

* Updated the OrganizationDomain update procedure

* Added delete command and include other endpoints in the controller

* Remove test item from controller

* Remove test item from controller

* Changed access to allow admin, owners and manage sso roles

* Added stored procedure to get unverified domains by nextrundate

* Renamed stored procedure name

* Added domain verification service interface

* Added GetManyByNextRunDate to repository

* Added verification domain service implementation

* changed logic for setting the initial value for the NextRunCount

* This commit should be signed using my SSH key

* Renamed NextRunCount to JobRunCount

* Renamed NextRunCount to JobRunCount on mysql

* Renamed NextRunCount to JobRunCount on postgres

* Removed chaining pattern and added logic to get next run date

* Lint fix

* Implemented EF core version on the repository

* Created background job implementation and logic

* popped stash

* Updated stored procedure and EF script

* Lint fix

* Added logic to set next job count and the next run date when a verification is false

* Added logic to set next job count and the next run date when a verification is false

* Updated stored procedure name on repository

* Removed test trigger

* Lint fix

* Added trigger for job

* Added job count update after successful domain verification

* Lint fix

* Lint fix

* [SG-682] Add Event Log Entries to Organization Domain (#2492)

* Added domain name property to Event related objects

* Added organization domain claiming event types

* Created migration script and updated related event scripts to include domanName

* Added EF Migrations

* Renamed postres script file extension

* Added DomainName property to response model

* Added abstraction to interface

* Added system name to enum

* dotnet formattinfg fix

* Added events to organization domain actions

* Added LastCheckedDate property to domain

* Migrations and stored procedure updates with new column

* Added new stored procedure to get domain by org id and domain name

* Log organization domain event abstract method

* Ef migrattion to add new LastCheckedDate column

* Added duplicate domain exception

* Modified create command to include domain verification and last checked date and renamed methods used

* removed variable

* changed service lifetime

* Renamed trigger

* Initialed property in constructor

* Ensured domain name is stored as lower case

* Fixed suggestions from review

* Fixed suggestions from review

* Return Conflict Status on Organization Domain APIs (#2498)

* Added conflict response to end point to help translate error message on the client better

* Added conflict response to end point to help translate error message on the client better

* Set message with exception message or generic message

* Added last check date to response model (#2499)

* Fix/Check to throw exception when domain is claimed by another organization (#2503)

* Added check to ensure domain claimed by another organization cannot be verified

* Made error message consistent

* [SG-660] Organization Domain Maintenance (#2502)

* Added email template

* Mail service abstraction and implementation

* Mail template model

* Initial delete job commit

* Added SPs to get all unverifed domains after 72 hours and another to delete unverified domains after 7 days

* Moved all organization domain scripts to single file

* Added new scripts implementation for sqlserver and EF core

* Renamed service

* Formatting fix

* Added background service to send warning email and delete expired domains

* Renamed variable

* Added implementation for email warning to organization admins and for deleting expired domains after 7 days

* Added formatting

* Modified read if expired script to limit result to 4 days

* Added send mail abstract method and implementation

* Model used in build mail body

* Completed maintenace service

* Added comment to make logic clear

* Fixed cron expression (#2505)

* Modified procedure and methods to handle flexible verification adn expiration period (#2517)

* Merged with master

* [SG-908] Unit Tests for Organization Domain Claiming Feature (#2522)

* added test controlleer class

* added unit test for create command

* Added query tests

* Added tests for delete and verify command

* Formated code and added some more unit tests

* Fixed lint

* Added log event assertion to create command tests

* Added log event assertion to delete command tests

* Added unit tests for organization domain controller

* Added unit tests for organization domain service

* Modified test after merge

* fixed comment

* fixed comment

* fixed lint

* Defect/SG-977 - Org domain event logs missing details (#2573)

* SG-977 - (1) Refactor EventSystemUser.SSO to be EventSystemUser.DomainVerification to better match SCIM property and for easier display and translation on web client (2) Add new DeviceType of Server to be used on SCIM and Domain Verification logs so event log will show Server as client.

* SG-977 - SCIM bugfix - Restoring / Revoking user access via Jumpcloud activation / suspension did not properly log the events as SCIM events so the client side showed Unknown for both Client and Member.

* Run autoformat to fix lint errors

* SG-977 - Fixed broken test due to new device type logic in event service

* SG-976 - Add admin log and clean up log verbiage for domain verification (#2574)

* SG-976 - Add admin log and clean up log verbiage for domain verification

* SG-976 - (1) Use logInformation extension without exception (2) Clarify verbiage of logs

* SG-955 - On domain verification error or failure, set last checked da… (#2541)

* SG-955 - On domain verification error or failure, set last checked date on the org domain.

* SG-955 - Refactoring VerifyOrganizationDomain event logging to avoid duplication and increase efficiency (based on Gbubemi's PR feedback)

* Org Domain Background Verification service - set last checked date (#2599)

* Refactored OrganizationDomain repository to work with latest changes on code base

* Fixed formatting

* [SG-957] Cannot Delete Organizations due to FK Constraint (#2602)

* Added stored procedure to fix FX contstraint issue when deleting an organization

* Update stored procedures related to organization delete with OrganizationDomain_OrganizationDelete SP

* Fixed formatting

* Updated SP

* SG-990 - Log expired domains that are going to be deleted.

* Fix lint errors with auto format

* /home/runner/work/server/server/src/Core/OrganizationFeatures/OrganizationServiceCollectionExtensions.cs(107,2): error FINALNEWLINE: Fix final newline. Insert '\n'.

* Added missing bracket to fix compile error.

* Added imports for Domain Claiming classes that were lost on merge.

* Fixing broken unit tests + adding proper behavior for newly added SCIM logic changing device type

* Fix lint errors again

* Included domain name set in constructor (#2618)

* [SG-1001] Error Thrown When Verifying Sub Domains (#2621)

* Renamed exception to a more generic name that receives error message from the dns client and also added updates to job count and next run date

* Improved error logs by adding dns client error message

* Fixed formatting

* [SG-1001] Added event logs when a domain is not verified due to thrown exception (#2623)

* Added eevent logs when a domain is not verified due to thrown exception

* Fixed formatting

* Org Domain Verification - Small refactor to improve method/model name… (#2641)

* Org Domain Verification - Small refactor to improve method/model names and method locations - required refactoring of controller routes (I confirmed all behavior still functional)

* Fixed organization test controller issue

* Fixed lint

* Autoformat org domain controller

* Removing whitespace for lint argh, why does Rider not do this.

---------

Co-authored-by: gbubemismith <gsmithwalter@gmail.com>

* Tweak name of Request model to match Response model for ClaimedOrgDomain call

* [SG-1009] Users with Custom Role and "Manage SSO" permission don't receive verification failed email (#2645)

* Modified condition to pick up unverified domains after said period

* Fix to get emails of custom users with manage sso rights

* Formatted code

* Removed return that made background job exit on successful validation (#2648)

* [SG-1014] Unit Tests for Get Organization Sso Details (#2655)

* Added unit tests for GetOrgDomainSsoDetails

* renamed variable

* Adjust OrganizationDomainSsoDetails_ReadByEmail to use outer join so … (#2657)

* Adjust OrganizationDomainSsoDetails_ReadByEmail to use outer join so that claimed domain results will come back if an org has not yet setup a policy

* Removed migration as not needed

* Updated OrganizationDomainSsoDetails_ReadByEmail from original creation migration to use outer join & handle null policy results (and still return results)

* Fixed lint formatting

---------

Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com>
Co-authored-by: Jared Snider <jsnider@bitwarden.com>
Co-authored-by: Todd Martin <tmartin@bitwarden.com>
2023-02-15 14:26:41 -05:00
Oscar Hinton
109d915d9e
Disable storage in tests (#2689) 2023-02-13 18:10:53 +01:00
Thomas Avery
35b832dbc9
[SM-485] Add access policy on project creation (#2678)
* Add bootstrap access policy on create

* Update project integration tests
2023-02-09 08:58:05 -06:00
Stepan Goremykin
d32cd79535
[PS-2425] Upgrade vulnerable packages (#2669)
* Upgrade vulnerable packages

* Added packages.lock.json files

---------

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>
2023-02-07 17:44:40 -06:00
Thomas Avery
1ee14d93e6
[SM-473] Access Policies - Service Accounts (#2658)
* Add service account access policy endpoints

* Add unit & integration tests for new endpoints

* Fix formatting on response models

* Cleanup unit tests
2023-02-07 14:30:22 -06:00
Thomas Avery
cf669286ed
[SM-429] Add permission checks to access policy endpoints (#2628)
* Add permission checks to access policy endpoints

* Fix unit tests

* Add service account grant permission checks

* Add service account grant tests

* Add new endpoint unit tests

* Cleanup unit tests add integration tests

* User permission enum in create tests

* Swap to NotFoundException for access checks

* Add filter for potential grantees

* Add in AccessSecretsManager check and test it

* Add code review updates

* Code review updates

* Refactor potential grantees endpoint

* Code review updates
2023-02-06 11:26:06 -06:00
Andreas Coroiu
55cc022d9b
[EC-1003] feat: remove externalId from PUT/POST (#2589) 2023-02-06 10:27:40 +01:00
Thomas Avery
0ce95ec147
[SM-465] Add access policy on service account creation (#2649)
* Add access policy on service account creation
2023-02-02 12:25:14 -06:00
Justin Baur
6390aaa011
Send in Guid instead of Cipher (#2662) 2023-02-02 12:12:41 -05:00
Michael Zimmermann
e019f0191d
fix bumping AccountRevisionDate when creating and updating ciphers (#2634)
When the user is not part of an organization,
`UserBumpAccountRevisionDateByCipherIdQuery` doesn't work. In that case
we have to use `UserBumpAccountRevisionDateAsync` instead.

This was already done by most parts of the code but a few more were
missing.

Fixes #2615
2023-02-02 09:33:35 -05:00
Oscar Hinton
cf25d55090
[SM-378] Enable SM on a user basis (#2590)
* Add support for giving individual users access to secrets manager
2023-01-31 18:38:53 +01:00
Thomas Rittson
82908b1fb7
[EC-826] Merge license sync feature branch to master (#2587)
* [EC-634] Extract GenerateLicenseAsync to a query (#2373)

* [EC-637] Add license sync to server (#2453)

* [EC-1036] Show correct license sync date (#2626)

* Update method name per new pattern
2023-01-31 07:42:10 +10:00
Rui Tomé
28e6275063
[EC-1015] Fixed OrganizationService InviteUser unit tests to not depend on random Org seat number (#2607) 2023-01-30 10:54:44 +00:00
Oscar Hinton
9ea520e038
Move CI testing to Ubuntu (#2638)
Change the CI for testing job from Windows to Ubuntu
2023-01-30 11:07:20 +01:00
Jared Snider
b412a01d2a
Defect/SG-992 ProviderOrgs Missing Plan Type & EC-591/SG-996 - Provider Org Autoscaling Email Invites Working (#2596)
* SG-992 - Provider receives free org prompt when trying to auto scale org seats because plan type was missing and defaulting to free. PlanType has now been added to provider orgs returned as part of the profile sync.

* SG-992 - Updated Stored proc name to match convention

* EC-591 / SG-996 - (1) Update ProviderUserRepo.GetManyDetailsByProviderAsync to accept optional ProviderUserStatusType (2) Update OrganizationService.cs autoscaling user logic to check if an org is a provider org and send owner emails to the confirmed provider users instead of the managed org owners. Prevents scenario where newly created, managed orgs would not have an owner yet, and ownerEmails would be null and the email service would explode.

* EC-591 / SG-996 - Remove comments

* EC-591 / SG-996 - ES lint fix.

* SG-996 - SQL files must have SQL extensions.

* SG-996 / EC-591 - Update alter sql to be actually backwards compatible

* SG-996 - Make Status actually optional and backwards compatible for ProviderUserUserDetails_ReadByProvider.sql

* SG-992 - Update migrations to meet standards - (1) use CREATE OR ALTER and (2) Update view metadata after change if necessary

* EC-591 / SG-996 - Update Stored Proc migration to use proper standards: (1) Remove unnecessary code and (2) Use CREATE OR ALTER instead of just ALTER

* SG-992 / EC-591 / SG-996 - Refactor separate migrations into single migrations file per PR feedback

* SG-992/SG-996 - Add SyncControllerTests.cs with basic test suite + specific test suite to ensure provider orgs have plan type mapped to output product type properly.

* Fix lint issues by removing unnecessary using statements

* SG-992 - Refresh of view metadata has to target the stored procs that reference the view -- not the view itself.
2023-01-26 11:51:26 -05:00
Jake Fink
64c15ed8cd
[EC-1032] if name is Empty, set to null before saving (#2619) 2023-01-25 11:07:33 -05:00
Bernd Schoolmann
cb1ba50ce2
[PS-2267] Add KdfMemory and KDFParallelism fields (#2583)
* Add KdfMemory and KDFParallelism fields

* Revise argon2 support

This pull request makes the new attribues for argon2, kdfMemory and
kdfParallelism optional. Furthermore it adds checks for the argon2
parametrs and improves the database migration script.

* Add validation for argon2 in RegisterRequestModel

* update validation messages

* update sql scripts

* register data protection with migration factories

* add ef migrations

* update kdf option validation

* adjust validation

* Centralize and Test KDF Validation

Co-authored-by: Kyle Spearrin <kspearrin@users.noreply.github.com>
Co-authored-by: Kyle Spearrin <kyle.spearrin@gmail.com>
Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2023-01-25 07:56:54 -05:00
Oscar Hinton
59f5285c88
[SM-460] Isolate SecretsManager files (#2616)
Move SecretsManager files to directories called SecretsManager and add CodeOwners
2023-01-24 19:57:28 +01:00
Matt Bishop
0e32cb944a
Upgrade Swagger (#2611) 2023-01-24 12:10:00 -05:00
Thomas Avery
aa9f859306
[SM-382] Service Account access policy checks (#2603)
The purpose of this PR is to add access policy checks to service account endpoints.
2023-01-24 09:50:04 -06:00
Jake Fink
7b4c9b0e59
[EC-943] remove deprecated permissions (#2578) 2023-01-20 11:36:17 -05:00
Oscar Hinton
5cd571df64
[SM-380] Access checks for listing projects (#2496)
* Add project access checks for listing
2023-01-20 16:33:11 +01:00
Thomas Avery
53ba2eeb18
[SM-390] Project Access Policies (#2507)
The purpose of this PR is to create server endpoints for creating, reading, updating, and deleting access policies for projects.
2023-01-19 17:31:19 -06:00
Thomas Avery
41d1e48823
Use response models in Api integration tests (#2592) 2023-01-19 15:20:59 -06:00
Matt Bishop
352b42b535
Upgrade FIDO2 library usage out of beta (#2579) 2023-01-19 11:06:51 -05:00
Andreas Coroiu
354caa3063
[EC-647] OAVR v2 Feature Branch Merge (#2588)
* [EC-19] Move SSO Identifier to Org SSO endpoint (#2184)

* [EC-19] Move SSO identifier to Org SSO config endpoint

* [EC-19] Add Jira tech debt issue reference

* [EC-542] Update email communications (#2348)

* [EC-73] Add users alongside groups for collection details (#2358)

* [EC-73] feat: add new stored procedures

* [EC-73] feat: add migration

* [EC-73] chore: rename collection group details

* [EC-73] fix: migration

* [EC-73] feat: return users from dapper repo

* [EC-73] feat: EF support for collection users

* [EC-73] feat: implement updating users in EF

* [EC-73] feat: new collections with users in EF

* [EC-73] feat: create with users in dapper

* [EC-73] feat: update with users in dapper

* [EC-73] fix: collection service tests

* [EC-73] fix: lint

* [EC-73] feat: add new data model and rename for clarity

* [EC-73] chore: add future migrations

* [EC-16 / EC-86] Implement Groups Table Endpoints (#2280)

* [EC-16] Update Group endpoints/repositories to include necessary collection info

* [EC-16] Add delete many groups endpoint and command

* [EC-16] Add DeleteGroupCommand unit tests

* [EC-16] Update migration script

* [EC-16] Formatting

* [EC-16] Support modifying users via Post Group endpoint

- Add optional Users property to GroupRequestModel
- Add users parameter to the GroupService.SaveAsync() method
- Use the users argument to update the Group via the GroupRepository if present.

* [EC-16] Add/update Sprocs for bulk group deletion

- Add a new bump account revision date by multiple org ids sproc to be used by the delete many group sproc.
- Update the delete many group sproc to no longer require the organization Id as authorization is a business concern.

* [EC-16] No longer require org Id in delete many GroupRepository

The group repository should not care about which organization a group belongs to when being deleted. That is a business logic concern and is not necessary at the repository level.

* [EC-16] Remove org Id from delete many group command

- Remove the organization Id from the delete many method.
- Require Group entities instead of just group Ids so that group retrieval is completed outside the command.
- No longer return deleted groups as they are now being passed into the command.
- Update unit tests

* [EC-16] Remove org id from bulk delete group endpoint

- Remove the Org Id from the endpoint and make use of the updated delete many command

* [EC-16] Rename delete many groups sproc

* [EC-16] Update migration script

* [EC-16] Fix typo in migration script

* [EC-16] Fix order of operations in Group_DeleteByIds sproc

* [EC-16] Formatting

* [EC-86] Fix DeleteManyAsync parameter name

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* [EC-16] Add missing sproc to sqlproj file

* [EC-16] Improve GroupRepository method performance

Use GroupBy before marrying Groups and Collections to avoid iterating over all collections for every group)

* [EC-16] Use ToListAsync() to be consistent in the repository

* [EC-16] Fix collection grouping in the EF repository

* [EC-16] Adjust DeleteGroup command namespace to be less verbose

* [EC-16] Cleanup DeleteGroupCommandTests

* [EC-16] Formatting

* [EC-16] Ensure a non-null group collection list is provided

* [EC-16] Add bulk GroupEvents method to EventService

- Use the new method in the DeleteGroups command

* [EC-16] Remove bulk delete group Api response

The response is unnecessary and not used by the client

* [EC-16] Log OrganizationUser_UpdateGroups event in GroupService

Events are logged for users during both Group creation (all added users) and modification (only changed users).

* [EC-16] Fix failing unit test

* [EC-16] Rename newUsers variable per feedback

* [EC-16] Assert delete many group log events

Explicitly check for the event type and groups that are logged to the event service.

* [EC-16] Update DeleteManyAsync signature

Use ICollection<> instead of IEnumerable<> to avoid ambiguity of possible multiple enumeration

* [EC-16] Increment migration script name

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* Add missing GO command to EC-73 migration script (#2433)

* [EC-15] Members Grid Api Support (#2485)

* [EC-15] Update OrganizationUser models to support list of collections and groups

* [EC-15] Add sprocs to query GroupUser and CollectionUser entities

* [EC-15] Update the OrganizationUserRepository to optionally fetch groups/collections

* [EC-15] Formatting

* [EC-15] Remove leftover repository method

* [EC-15] Fix table identifier inconsistency in sproc/migration

* Formatting

* [EC-14]: Server changes for Collection rows in Vault (#2360)

* [EC-14] add collection management methods to repo
- delete many, get many by ids, and get many with groups by org

* [EC-14] connection command tests had wrong folder name

* [EC-14] add collection repo methods to interface

* [EC-14] create DeleteCollectionCommand

* [EC-14] add getManyWithDetails collections endpoint

* [EC-14] add GetManyWithGroupsByUserId

* [EC-14] add call to interface

* [EC-14] add GetOrganizationCollectionsWIthGroups
- gets groups with collections
- add tests as well

* [EC-14] add call to interface

* [EC-14] add new coll call to controller
- gets collections with groups

* [EC-14] use new delete collection command

* [EC-14] add CollectionBulkDeleteRequestModel

* [EC-14] remove org from delete collection cmd
- move all permission checks to controller
- add tests to controller
- remove org check from repository method

* [EC-14] add migration and sprocs

* [EC-14] formatting

* [EC-14] revert delete permission check changes

* [EC-14] rename SelectionReadOnly to CollectionAccessSelection

* [EC-14] move GetOrganizationCollectionsWithGroups to controller
- there's no reason to have this logic in the service layer
- we can still test the permission check in the controller
- also renamed repo methods and changed return types

* [EC-14] include users in collection access details

* [EC-14] fix migration names

* [EC-14] bumpAccountRevisionDate when deleting collections

* [EC-14] new line in collection service

* [EC-14] formatting and add .sql to proc file

* [EC-14] more formatting

* [EC-14] formatting

* [EC-14] fix whitespace

* [EC-14] add datetime to event log of single delete

* [EC-14] remove ToList() from enumerables not returned

* [EC-14] fix permissions on "Create new collection"
- a custom user with "Create new collections" should see all collections

* [EC-14] add bulk events for collections

* [EC-14] group collections from db before iterating

* [EC-14] sql formatting and missing GO

* [EC-14] fix tests

* [EC-14] add null handling to repo methods

* [EC-14] fix account revision call

* [EC-14] formatting

* [EC-548] Member Details Group Tab (#2508)

* [EC-548] Update models to support groups

* [EC-548] Include groups in invite and save organization user methods

* [EC-548] Pass groups to service methods in member/user controllers

* [EC-548] Fix failing tests

* [EC-548] Add option to include groups for GET org user query

* Formatting

* [EC-887] Server fix for managers seeing options to edit/delete Collections they aren't assigned to (#2542)

* [EC-887] Add Assigned property to CollectionResponseModel

A new property to determine if a collection is assigned to the acting user; as some users, have the view all collections permission, but cannot see every collection's items

* [EC-887] Update logic for retrieving GET all collection details

- Only need to check the ViewAllCollections permission
- Calculate new Assigned response property based on the assignedOrgCollections list

* Formatting

* [EC-887] Update unit tests

Co-authored-by: Shane Melton <smelton@bitwarden.com>
Co-authored-by: Jacob Fink <jfink@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
2023-01-19 11:00:54 -05:00
Kyle Spearrin
6f04298e17
Data protection for user columns at rest (#2571)
* ServerProtectedData for user entity

* remove using statements

* formatting

* use data protection libs

* no async

* add data protection to ef user repo

* switch to `SetApplicationName` per ASPNET docs

* null checks

* cleanup

* value converter for EF

* new line at eof

* fix using

* remove folder ref

* restore ctor

* fix lint

* use global constant

* UseApplicationServiceProvider for integration tests

* implement constant for DatabaseFieldProtectedPrefix

* Fix EF IntegrationTest

* restore original values after protect and save

* lint fixes

* Use Constants

Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2023-01-18 13:16:57 -05:00
Rui Tomé
119c815c16
[EC-912] Updated IdentityServerTests to reinitialize the database on constructor (#2538)
* [EC-912] Updated IdentityServerTests to reinitialize the database on constructor

* [EC-912] dotnet format
2023-01-17 15:21:36 +00:00
Oscar Hinton
1f0fc43278
[SM-394] Secrets Manager (#2164)
Long lived feature branch for Secrets Manager

Co-authored-by: Thomas Avery <43214426+Thomas-Avery@users.noreply.github.com>
Co-authored-by: cd-bitwarden <106776772+cd-bitwarden@users.noreply.github.com>
Co-authored-by: CarleyDiaz-Bitwarden <103955722+CarleyDiaz-Bitwarden@users.noreply.github.com>
Co-authored-by: Thomas Avery <tavery@bitwarden.com>
Co-authored-by: Colton Hurst <colton@coltonhurst.com>
2023-01-13 15:02:53 +01:00
Matt Bishop
df2edcfb8c
Migrate to Microsoft.Data.SqlClient (#2548) 2023-01-10 15:58:41 -05:00
cyprain-okeke
e7958609b6
[PS 2020] Fixing value cannot be null, parameter source (#2554)
* Fixing value cannot be null, parameter source

* Running the dotnet format -v diag
2023-01-09 14:51:34 +01:00
Matt Bishop
452891b39e
Upgrade to the latest System.Data.SqlClient (#2546) 2023-01-06 14:36:12 -05:00
Kyle Spearrin
c39fb8f7af
update ef core libraries (#2515)
* update ef core libraries

* lock file updates
2022-12-25 20:49:14 -05:00
Rui Tomé
4adc4b0181
[EC-758] Add environment variable to enforce SSO Policy for all users (#2428)
* [EC-758] Add environment variable GlobalSettings.Sso.EnforceSsoPolicyForAllUsers to enforce SSO Policy for all users

* [EC-758] Add integration tests

* [EC-758] Add Entities namespace to resolve ambiguous reference

* [EC-758] dotnet format

* [EC-758] Updated integration tests to check for logins with all user types

* [EC-758] Create new TestServer for each test

* [EC-758] Combine unit tests and refactor to use BitAutoData
2022-12-20 13:08:29 +00:00
Matt Gibson
7cbc4a8970
Add Sqlite as EF DB provider (#2487)
* Add Sqlite as EF DB provider

Note: In-memory sqlite does not work across projects, since the migrator
only runs on the Admin project

Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com>

* Include example sqlite connection string

* Add migrator assembly to sqlite connection

* Update initial migration to current schema state

* dotnet format 🤖

* Update package locks

* Respect name set in BW_SSL_KEY for cert generation (#2490)

(cherry picked from commit 2469e10110)

* [PS-2016] Add ability to change UID/GID for Bitwarden unified (#2495)

(cherry picked from commit c6fbe8cc44)

* Add SqliteMigrations project to unified Dockerfile

Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com>
Co-authored-by: accolon <mail@accolon.net>
Co-authored-by: Vince Grassia <593223+vgrassia@users.noreply.github.com>
2022-12-14 08:28:51 -06:00
Alena N
456cc6773e
Fix bug #2317: add deletion date validation for file Sends (#2342)
Co-authored-by: cyprain-okeke <108260115+cyprain-okeke@users.noreply.github.com>
2022-12-13 20:30:01 +01:00
Rui Tomé
e042360c00
[EC-654] Create commands for Group Create and Group Update (#2442)
* [EC-654] Add CreateGroupCommand and UpdateGroupCommand

Added new CQRS commands CreateGroupCommand and UpdateGroupCommand
Updated GroupService to use new commands
Edited existing GroupServiceTests and added new tests for the new commands

* [EC-654] dotnet format

* [EC-654] Replace GroupService.SaveAsync with CreateGroup and UpdateGroup commands

* [EC-654] Add assertions to check calls on IReferenceEventService

* [EC-654] Use AssertHelper.AssertRecent for DateTime properties

* [EC-654] Extracted database reads from CreateGroupCommand and UpdateGroupCommand. Added unit tests.

* [EC-654] Changed CreateGroupCommand and UpdateGroupCommand Validate method to private
2022-12-12 09:59:48 +00:00
Rui Tomé
ae280a313c
[EC-343] Gate custom permissions behind enterprise plan (#2352)
* [EC-343] Added column 'UseCustomPermissions' to Organization table

* [EC-343] Added 'UseCustomPermissions' to Api responses

* [EC-343] Added 'UseCustomPermissions' to Admin view

* [EC-343] Add constraint to Organization table to have default UseCustomPermissions value

* [EC-343] Recreate OrganizationView to include UseCustomPermissions column

* [EC-343] Add MySql EF migrations

* [EC-343] Add Postgres EF migrations

* Revert "[EC-343] Add Postgres EF migrations"

This reverts commit 8f1654cb7d.

* [EC-343] Add Postgres migrations and script

* [EC-343] dotnet format

* [EC-343] Set 'Custom Permissions' feature as unchecked for teams plan

* [EC-343] Add CustomPermissions to plan upgrades

* [EC-343] Update CURRENT_LICENSE_FILE_VERSION

* [EC-343] Enable 'Custom Permissions' on Enterprise 2019 plan

* [EC-343] Updated migration script to include Enterprise 2019 plan

* [EC-343] Update CURRENT_LICENSE_FILE_VERSION to 10

* [EC-343] Move logic checking if Organization can use custom permissions to OrganizationService

* [EC-343] Add unit tests to validate UseCustomPermissions check

* [EC-343] Revert UseCustomPermissionsFlag migration

* [EC-343] Fix typo in OrganizationUserOrganizationDetailsViewQuery

* [EC-343] Add Postgres migrations without affecting other datetime column

* [EC-343] Create ValidateOrganizationCustomPermissionsEnabledAsync. Add more unit tests around CustomPermissions check

* [EC-343] Add curly brackets to if condition

* [EC-343] Rename unit tests
2022-12-06 09:50:08 +00:00
Justin Baur
efe91fd0d8
[PS-1928] Add BumpAccountRevisionDate methods (#2458)
* Move RevisionDate Bumps to Extension Class

* Add Tests against live databases

* Run Formatting

* Fix Typo

* Fix Test Solution Typo

* Await ReplaceAsync
2022-12-02 14:24:30 -05:00
Gbubemi Smith
f74730dd2f
[SG-841] Refactor GetOrganizationApiKeyCommand (#2436)
* Renamed and split up class to only query for an organization key

* Added a command class to create an organization api key

* Updated service registration and controller to include new changes

* Updated test cases to reflect refactor

* fixed lint issues

* Fixed PR comment
2022-11-28 19:39:09 -05:00
Todd Martin
24469e2267
Update push token on login to allow multiple users on mobile devices (#2404)
* Changed query for device to include userId

(cherry picked from commit 5e3f6db64b)

* Refactored push registration to allow notification on multiple clients

(cherry picked from commit 75d299ae269eeb8ac272c96458815a359ea6d085)

* Linting

(cherry picked from commit f1cf54ebef2019743834f667861f9b34c1661e11)

* Fixed compile error.

* Removed class that I created when refactoring.

* Removed references to PushNotification from DeviceService tests.

* Refactored to not pass back a result on Save

* Refactored to send requestDevice to push notifications.

* Fixed whitespace.

* Added missing Noop services.

(cherry picked from commit bdad6cfadaf2779c2e672027122c95ea64e3cf0b)

* Linting.

* Refactored to put the push token back in SaveAsync.

* Removed constructor parameter.

* Added back in ClearTokenAsync to reduce risk.

* Updated tab for linting.
2022-11-16 15:30:28 +00:00
Rui Tomé
37ed4f43b2
[EC-449] Event log user for SCIM events (#2306)
* [EC-449] Added new Enum EventSystemUser

* [EC-449] Added SystemUser property to Event model

* [EC-449] Added SQL migration to add new column 'SystemUserType' to Event

* [EC-449] EF migrations

* [EC-449] Added EventSystemUser to EventResponseModel

* [EC-449] Saving EventSystemUser.SCIM on SCIM controller actions

* [EC-449] Updated Event_Create stored procedure on Sql project

* [EC-449] Fixed SystemUser column name on Event table

* [EC-507] SCIM CQRS Refactor - Groups/Put (#2269)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-531] Implemented CQRS for Groups Put and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions

* [EC-507] Renamed AddScimCommands to AddScimGroupCommands

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Update PutGroupCommand to return Group

PutGroupCommand returns Group and GroupsController creates ScimGroupResponseModel response

* [EC-507] Remove Queries/Commands folders from Scim and Scim.Tests

* [EC-507] Remove unneeded check on empty provided memberIds

* [EC-507] SCIM CQRS Refactor - Groups/GetList (#2272)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-508] Implemented CQRS for Groups GetList and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions and renamed GetGroupsListCommand to GetGroupsListQuery

* [EC-507] Renamed AddScimCommands to AddScimGroupQueries

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Remove 'Queries' folder from Scim and Scim.Test

* [EC-507] Move ScimListResponseModel from GetGroupsListQuery to Scim.GroupsController

* [EC-507] Remove asserts on IGroupRepository.GetManyByOrganizationIdAsync from unit tests

* [EC-507] SCIM CQRS Refactor - Groups/Get (#2271)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-507] Implemented CQRS for Groups Get and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions and renamed GetGroupCommand to GetGroupQuery

* [EC-507] Renamed AddScimCommands to AddScimGroupQueries

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Sorted order of methods

* [EC-507] Removed GetGroupQuery and moved logic to controller

* [EC-507] Remove 'Queries' folder from Scim and Scim.Test

* [EC-507] SCIM CQRS Refactor - Groups/Patch (#2268)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-532] Implemented CQRS for Groups Patch and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions

* [EC-507] Renamed AddScimCommands to AddScimGroupCommands

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Remove Queries/Commands folders from Scim and Scim.Tests

* [EC-507] Assert group.Name after saving. Assert userIds saved.

* [EC-508] SCIM CQRS Refactor - Users/Delete (#2261)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-539] Implemented CQRS for Users Delete and added unit tests

* [EC-508] Created ScimServiceCollectionExtensions

* [EC-508] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-508] Removed unneeded model from DeleteUserCommand. Removed unneeded dependencies from UsersController

* [EC-508] Removed Bit.Scim.Models dependency from DeleteUserCommandTests

* [EC-508] Deleted 'DeleteUserCommand' from SCIM; Created commands on Core 'DeleteOrganizationUserCommand', 'PushDeleteUserRegistrationOrganizationCommand' and 'OrganizationHasConfirmedOwnersExceptQuery'

* [EC-508] Changed DeleteOrganizationUserCommand back to using IOrganizationService

* [EC-508] Fixed DeleteOrganizationUserCommand unit tests

* [EC-508] Remove unneeded obsolete comments. Update DeleteUserAsync Obsolete comment with ticket reference

* [EC-508] Move DeleteOrganizationUserCommand to OrganizationFeatures folder

* [EC-508] SCIM CQRS Refactor - Users/Post (#2264)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-536] Implemented CQRS for Users Post and added unit tests

* [EC-508] Created ScimServiceCollectionExtensions

* [EC-508] Renamed AddScimCommands to AddScimUserCommands

* [EC-508] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-508] Catching NotFoundException on ExceptionHandlerFilter

* [EC-508] Remove Queries/Commands folders from Scim and Scim.Tests

* [EC-508] SCIM CQRS Refactor - Users/Patch (#2262)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-538] Implemented CQRS for Users Patch and added unit tests

* [EC-508] Added ScimServiceCollectionExtensions

* [EC-508] Removed HandleActiveOperationAsync method from UsersController

* [EC-508] Renamed AddScimCommands to AddScimUserCommands

* [EC-508] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-508] Removed unneeded dependencies from UsersController

* [EC-508] Remove 'Query' folder from Scim and Scim.Test

* [EC-507] SCIM CQRS Refactor - Groups/Post (#2270)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-530] Implemented CQRS for Groups Post and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions

* [EC-507] Renamed AddScimCommands to AddScimGroupCommands

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Remove Queries/Commands folders from Scim and Scim.Test

* [EC-507] Remove unneeded skipIfEmpty argument. Updated unit test to check provided userIds

* [EC-507] Remove UpdateGroupMembersAsync from GroupsController

* [EC-508] SCIM CQRS Refactor - Users/GetList (#2265)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-535] Implemented CQRS for Users GetList and added unit tests

* [EC-508] Created ScimServiceCollectionExtensions and renamed GetUsersListCommand to GetUsersListQuery

* [EC-508] Renamed AddScimCommands to AddScimUserQueries

* [EC-508] Removed unneeded IUserRepository and IOptions<ScimSettings> from UsersController

* [EC-508] Sorted UsersController properties and dependencies

* [EC-508] Remove 'Queries' folder from Scim and Scim.Test

* [EC-508] Move ScimListResponseModel creation to Scim.UsersController

* [EC-508] Move ScimUserResponseModel creation to Scim.UsersController

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* [EC-507] SCIM CQRS Refactor - Groups/Delete (#2267)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-533] Implemented CQRS for Groups Delete and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions

* [EC-507] Renamed AddScimCommands to AddScimGroupCommands

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Move DeleteGroupCommand to OrganizationFeatures/OrganizationUsers

* [EC-507] Remove IGetUserQuery and move logic to UsersController. Remove unused references.

* [EC-449] Add overloads for EventService and GroupService methods that accept EventSystemUser as an argument

* [EC-507] Move IDeleteGroupCommand to Groups folder

* [EC-449] Add method overloads in IOrganizationService without EventSystemUser

* [EC-449] Add RevokeUserAsync overload without EventSystemUser

* [EC-449] Reverted OrganizationUsersController to not pass EventSystemUser argument

* [EC-449] Uncomment assertion in GroupServiceTests

* [EC-449] Update method overloads to not have nullable EventSystemUser

* [EC-449] Add unit tests around events that can store EventSystemUser

* [EC-449] Deleted private method GroupService.GroupRepositoryDeleteAsync

* [EC-449] Move Event log call to public DeleteUserAsync methods

* [EC-449] Move call to EventService log to public OrganizationService.InviteUsersAsync methods

* [EC-449] Move EventService call to public OrganizationService.DeleteUserAsync methods

* [EC-449] Move EventService call to OrganizationService.RevokeUserAsync methods

* [EC-449] Move EventService call to OrganizationService.RestoreUserAsync methods

* [EC-449] Add missing comma in SQL script for new SystemUser column on the Event table

* [EC-449] Remove Autofixture hack from OrganizationServiceTests

* [EC-449] Remove invitingUser param when methods expect an EventSystemUser param

* [EC-449] Move DeleteUserAsync validation to private method

* [EC-449] Move revokingUserId from RevokeUserAsync private method

* [EC-449] Move restoringUserId to RestoreUserAsync public method

* [EC-449] Set up OrganizationServiceTest Restore and Revoke tests on a single method

* [EC-449] SaveUsersSendInvitesAsync to return both OrganizationUsers and Events list

* [EC-449] Undo unintended change on CipherRepository

* [EC-449] Add SystemUser value to EventTableEntity

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
2022-11-09 12:13:29 +00:00
Rui Tomé
0a01051d83
[EC-507 / EC-508] SCIM CQRS Refactor - Groups/Users (#2344)
* [EC-507] SCIM CQRS Refactor - Groups/Put (#2269)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-531] Implemented CQRS for Groups Put and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions

* [EC-507] Renamed AddScimCommands to AddScimGroupCommands

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Update PutGroupCommand to return Group

PutGroupCommand returns Group and GroupsController creates ScimGroupResponseModel response

* [EC-507] Remove Queries/Commands folders from Scim and Scim.Tests

* [EC-507] Remove unneeded check on empty provided memberIds

* [EC-507] SCIM CQRS Refactor - Groups/GetList (#2272)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-508] Implemented CQRS for Groups GetList and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions and renamed GetGroupsListCommand to GetGroupsListQuery

* [EC-507] Renamed AddScimCommands to AddScimGroupQueries

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Remove 'Queries' folder from Scim and Scim.Test

* [EC-507] Move ScimListResponseModel from GetGroupsListQuery to Scim.GroupsController

* [EC-507] Remove asserts on IGroupRepository.GetManyByOrganizationIdAsync from unit tests

* [EC-507] SCIM CQRS Refactor - Groups/Get (#2271)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-507] Implemented CQRS for Groups Get and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions and renamed GetGroupCommand to GetGroupQuery

* [EC-507] Renamed AddScimCommands to AddScimGroupQueries

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Sorted order of methods

* [EC-507] Removed GetGroupQuery and moved logic to controller

* [EC-507] Remove 'Queries' folder from Scim and Scim.Test

* [EC-507] SCIM CQRS Refactor - Groups/Patch (#2268)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-532] Implemented CQRS for Groups Patch and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions

* [EC-507] Renamed AddScimCommands to AddScimGroupCommands

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Remove Queries/Commands folders from Scim and Scim.Tests

* [EC-507] Assert group.Name after saving. Assert userIds saved.

* [EC-508] SCIM CQRS Refactor - Users/Delete (#2261)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-539] Implemented CQRS for Users Delete and added unit tests

* [EC-508] Created ScimServiceCollectionExtensions

* [EC-508] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-508] Removed unneeded model from DeleteUserCommand. Removed unneeded dependencies from UsersController

* [EC-508] Removed Bit.Scim.Models dependency from DeleteUserCommandTests

* [EC-508] Deleted 'DeleteUserCommand' from SCIM; Created commands on Core 'DeleteOrganizationUserCommand', 'PushDeleteUserRegistrationOrganizationCommand' and 'OrganizationHasConfirmedOwnersExceptQuery'

* [EC-508] Changed DeleteOrganizationUserCommand back to using IOrganizationService

* [EC-508] Fixed DeleteOrganizationUserCommand unit tests

* [EC-508] Remove unneeded obsolete comments. Update DeleteUserAsync Obsolete comment with ticket reference

* [EC-508] Move DeleteOrganizationUserCommand to OrganizationFeatures folder

* [EC-508] SCIM CQRS Refactor - Users/Post (#2264)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-536] Implemented CQRS for Users Post and added unit tests

* [EC-508] Created ScimServiceCollectionExtensions

* [EC-508] Renamed AddScimCommands to AddScimUserCommands

* [EC-508] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-508] Catching NotFoundException on ExceptionHandlerFilter

* [EC-508] Remove Queries/Commands folders from Scim and Scim.Tests

* [EC-508] SCIM CQRS Refactor - Users/Patch (#2262)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-538] Implemented CQRS for Users Patch and added unit tests

* [EC-508] Added ScimServiceCollectionExtensions

* [EC-508] Removed HandleActiveOperationAsync method from UsersController

* [EC-508] Renamed AddScimCommands to AddScimUserCommands

* [EC-508] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-508] Removed unneeded dependencies from UsersController

* [EC-508] Remove 'Query' folder from Scim and Scim.Test

* [EC-507] SCIM CQRS Refactor - Groups/Post (#2270)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-530] Implemented CQRS for Groups Post and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions

* [EC-507] Renamed AddScimCommands to AddScimGroupCommands

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Remove Queries/Commands folders from Scim and Scim.Test

* [EC-507] Remove unneeded skipIfEmpty argument. Updated unit test to check provided userIds

* [EC-507] Remove UpdateGroupMembersAsync from GroupsController

* [EC-508] SCIM CQRS Refactor - Users/GetList (#2265)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-535] Implemented CQRS for Users GetList and added unit tests

* [EC-508] Created ScimServiceCollectionExtensions and renamed GetUsersListCommand to GetUsersListQuery

* [EC-508] Renamed AddScimCommands to AddScimUserQueries

* [EC-508] Removed unneeded IUserRepository and IOptions<ScimSettings> from UsersController

* [EC-508] Sorted UsersController properties and dependencies

* [EC-508] Remove 'Queries' folder from Scim and Scim.Test

* [EC-508] Move ScimListResponseModel creation to Scim.UsersController

* [EC-508] Move ScimUserResponseModel creation to Scim.UsersController

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>

* [EC-507] SCIM CQRS Refactor - Groups/Delete (#2267)

* [EC-390] Added Scim.Test unit tests project

* [EC-390] Added ConflictException type. Updated BadRequestException to have parameterless constructor. Updated NotFoundException to have constructor with a message parameter

* [EC-533] Implemented CQRS for Groups Delete and added unit tests

* [EC-507] Created ScimServiceCollectionExtensions

* [EC-507] Renamed AddScimCommands to AddScimGroupCommands

* [EC-507] Created ExceptionHandlerFilterAttribute on SCIM project

* [EC-507] Removed unneeded dependencies from GroupsController

* [EC-507] Move DeleteGroupCommand to OrganizationFeatures/OrganizationUsers

* [EC-507] Remove IGetUserQuery and move logic to UsersController. Remove unused references.

* [EC-507] Move IDeleteGroupCommand to Groups folder

Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
2022-10-31 09:58:21 +00:00
dgoodman-bw
b938abab65
Ps 976 moving of read only organization collection items to different folder not possible (#2257)
* PS-976 - update PutPartial endpoint to return cipher info, update Cipher_Move sproc to allow users to update a cipher's folder even if they don't have edit permissions

* PS-976- fix formatting errors

* PS-976 - per cr feedback updated EF query to match cipher_move sproc update, and updated cipher tests to align with existing tests
2022-10-25 12:23:49 -07:00
Justin Baur
a349f28840
[PS-1471] Create Allocation Free EncryptedStringAttribute validation (#2273)
* Add new logic for validating encrypted strings

* Add benchmarks

* Formatting & Comments

* Move Debug assertion to just be a test

* Address PR feedback pt.1

* Address more PR feedback

* Formatting

* merge branch 'master' into 'encrypted-string-perf'

* Revert "merge branch 'master' into 'encrypted-string-perf'"

This reverts commit a20e127c9c.
2022-10-20 16:10:02 -04:00
Todd Martin
63ae7c8b66
[SG-419] Added logging to mobile push notifications (#2332)
* Added logging to push notifications.

* Added additional logging for testing push notifications.

* Removed package lock changes.

* Removed package lock changes.

* Renamed the property and added a description.

* Undid changes to LoggerFactory.

* Removed filter on Microsoft library logging.

Co-authored-by: Todd Martin <>
2022-10-19 10:22:40 -04:00
Oscar Hinton
07a091503c
[SM-244] Resolve dotnet warnings (#2283) 2022-10-18 22:12:26 +02:00
Oscar Hinton
c11a179332
[SM-220] Move identity specific files to identity (#2279) 2022-09-27 18:30:37 +02:00
Addison Beck
02bea3c48d
[SG-167] Implement Passwordless Authentication via Notifications (#2276)
* [SG-549] Commit Initial AuthRequest Repository (#2174)

* Model Passwordless

* Scaffold database for Passwordless

* Implement SQL Repository

* [SG-167] Base Passwordless API (#2185)

* Implement Passwordless notifications

* Implement Controller

* Add documentation to BaseRequestValidator

* Register AuthRequestRepo

* Remove ExpirationDate from the AuthRequest table

* [SG-407] Create job to delete expired requests (#2187)

* chore: init

* remove exp date

* fix: log name

* [SG-167] Added fingerprint phrase to response model. (#2233)

* Remove FailedLoginAttempt logic

* Block unknown devices

* Add EF Support for passwordless

* Got SignalR working for responses

* Added delete job method to EF repo

* Implement a GetMany API endpoint for AuthRequests

* Ran dotnet format

* Fix a merge issues

* Redated migration scripts

* tried sorting sqlproj

* Remove FailedLoginAttempts from SQL

* Groom Postgres script

* Remove extra commas from migration script

* Correct isSpent()

* [SG-167] Adde identity validation for passwordless requests. Registered IAuthRepository.

* [SG-167] Added origin of the request to response model

* Use display name for device identifier in response

* Add datetime conversions back to postgres migration script

* [SG-655] Add anonymous endpoint for checking if a device & user combo match

* [review] Consolidate error conditions

Co-authored-by: Brandon Maharaj <107377945+BrandonM-Bitwarden@users.noreply.github.com>
Co-authored-by: André Filipe da Silva Bispo <andrefsbispo@hotmail.com>
Co-authored-by: André Bispo <abispo@bitwarden.com>
2022-09-26 13:21:13 -04:00
Thomas Rittson
7c3637c8ba
[EC-387] Don't count revoked users towards occupied seat count (#2256)
Also autoscale seats when restoring user if required
2022-09-23 14:30:39 +10:00
Addison Beck
d0c793c951
Update API endpoint to use RegisterResponseModel (#2282) 2022-09-19 09:35:57 -04:00
Addison Beck
287dc2e06b
[SG-656] Send a captcha bypass token back from the register endpoint (#2278)
* Send a captcha bypass token back from the register endpoint

* [review] Use existing user

* [review] Introduce ICaptcheProtectedResponseModel
2022-09-15 10:02:37 -04:00
Justin Baur
735ad264f1
Remove Batch (#2274) 2022-09-14 14:57:05 -04:00
Rui Tomé
5ecf7b9440
[EC-394] SCIM server integration tests (#2197)
* [EC-394] Added ScimApplicationFactory to handle tests for Scim controllers

* [EC-394] Added Scim.IntegrationTest project with GroupsControllerTests

* [EC-394] Fixed getting Guid Id from Operation Path

* [EC-394] Added tests for GroupsController Patch action

* [EC-394] Moved tests mock data setup to ScimApplicationFactory

* [EC-394] Updated IntegrationTestCommon packages.lock.json

* [EC-394] Updated ScimApplicationFactory and GroupsControllerTests; Added UsersController Tests

* [EC-394] dotnet format

* [EC-394] Updated Identity.IntegrationTest packages.lock.json

* [EC-394] Updated Scim.IntegrationTest packages.lock.json

* [EC-394] dotnet format

* [EC-394] Reverted change on getting GUID from GetOperationPathId

* [EC-394] Fixed sending userId on Patch_AddSingleMember_Success and Patch_RemoveSingleMember_Success

* [EC-394] Updated test to send request with two operations

* [EC-394] Removed Scim dependency from IntegrationTestCommon

* [EC-394] Reverted changes to packages.lock.json.
Ran dotnet format

* [EC-394] Updated Scim.IntegrationTest packages.lock.json

* [EC-394] Updated GroupsControllerTests and UsersControllerTests to implement IAsyncLifetime to cleanup database before each test

* [EC-394] Declared variables for GetList parameters

* [EC-394] Updated AssertHelper.AssertPropertyEqual to compare each item in an IEnumerable property

* [EC-394] Updated AssertHelper.AssertPropertyEqual to check if type is comparable

* [EC-394] Removed unused variable from ScimApplicationFactory

* Apply suggestions from code review

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* [EC-394] Changed test users emails to domain example.com

* [EC-394] Restore solution file

* [EC-394] Added Scim.IntegrationTest to sln

* [EC-394] Updated integration tests to be clearer and check responses in detail

* [EC-394] Using NoopMailService to mock sending email invitations in tests

* [EC-394] Removed multiple references to the same variable ScimApplicationFactory.TestOrganizationId1

* [EC-394] Updated const variable names

* [EC-394] Using AssertPropertyEqualPredicate for IEnumerable properties

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
2022-09-08 09:00:59 +01:00
Shane Melton
2bf8438ff7
[EC-502] Rate Limiting Improvements (#2231)
* [EC-502] Add custom Redis IP rate limit processing strategy

* [EC-502] Formatting

* [EC-502] Add documentation and app setting config options

* [EC-502] Formatting

* [EC-502] Fix appsettings.json keys

* [EC-502] Replace magic string for cache key

* [EC-502] Add tests for custom processing strategy

* [EC-502] Formatting

* [EC-502] Use base class for custom processing strategy

* [EC-502] Fix failing test
2022-08-31 14:17:29 -07:00
Rui Tomé
e0f9d99b49
[EC-495] Updated GroupService.SaveAsync to check if collections are supplied and prevent deleting Group-to-Collection associations. Added unit test. (#2234) 2022-08-31 16:03:13 +01:00
Matt Gibson
a6d97118fa
Feature/bit auto data (#2219)
* Update ProviderService tests

* Use BitAutoData in CipherService tests

* Simplify UserCipher fixture

Because we use a single customizer for all ciphers, they all have the same userId.

* Clean up more cipher fixtures

* Swap Cipher Fixtures to BitCustomizeAttribute

* Clean up collection fixtures

* Clean up GroupFixtures

* Move SendService Tests to BitAutoData

* Clean up Organization Fixtures

TODO: The customize attributes should not be customizing more than one class

* Name files after the class they contain

* Clear up usage of CustomAutoDataAttribute in tests

* Clean up usages of InlineCustomAutoData

* format

* Manually merge with file-scoped-namespace changes
2022-08-31 08:38:35 -05:00
Justin Baur
7f5f010e1e
Run formatting (#2230) 2022-08-29 16:06:55 -04:00
Justin Baur
bae03feffe
Revert filescoped (#2227)
* Revert "Add git blame entry (#2226)"

This reverts commit 239286737d.

* Revert "Turn on file scoped namespaces (#2225)"

This reverts commit 34fb4cca2a.
2022-08-29 15:53:48 -04:00
Justin Baur
34fb4cca2a
Turn on file scoped namespaces (#2225) 2022-08-29 14:53:16 -04:00
Oscar Hinton
7c4521e0b4
[SM-153] Add scaffolded API integration test project (#2209) 2022-08-29 16:24:52 +02:00
Oscar Hinton
194c695cd0
[SM-151] Move EF Dapper tests to Infrastructure.EFIntegration.Test (#2204) 2022-08-29 09:40:59 -04:00
Chad Scharf
37641ba08b
Cherry pick/stripe sdk fixes (#2170)
* update stripe sdk (#2166)

* Bump version to 2022.8.1 (#2167)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
(cherry picked from commit eaca9a5864)

* added setting to toggle stripe api version errors (#2168)

* Bump version to 2022.8.2 (#2169)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
(cherry picked from commit 3d7e5e165c)

Co-authored-by: Kyle Spearrin <kspearrin@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-08-09 09:32:18 -04:00
Matt Gibson
dad666fc96
Add Microsoft.Data.SqlClient back as quartz dependency (#2161) 2022-08-02 17:52:34 -05:00
Oscar Hinton
1cad0268c0
[SM-142] Rename CommCore to Commercial.Core (#2158)
* Rename CommCore to Commercial.Core
2022-08-02 20:41:18 +02:00
Shane Melton
4e3d8172ff
Re-evaluate lock files to ensure they match project dependencies (#2132) 2022-07-20 09:10:08 -07:00
Shane Melton
7d40b38352
[PS-93] Distributed Ip rate limiting (#2060)
* Upgrade AspNetCoreRateLimiter and enable redis distributed cache for rate limiting.

- Upgrades AspNetCoreRateLimiter to 4.0.2, which required updating NewtonSoft.Json to 13.0.1.
- Replaces Microsoft.Extensions.Caching.Redis with Microsoft.Extensions.Caching.StackExchangeRedis as the original was deprecated and conflicted with the latest AspNetCoreRateLimiter
- Adds startup task to Program.cs for Api/Identity projects to support AspNetCoreRateLimiters breaking changes for seeding its stores.
- Adds a Redis connection string option to GlobalSettings

Signed-off-by: Shane Melton <smelton@bitwarden.com>

* Cleanup Redis distributed cache registration

- Add new AddDistributedCache service collection extension to add either a Memory or Redis distributed cache.
- Remove distributed cache registration from Identity service collection extension.
- Add IpRateLimitSeedStartupService.cs to run at application startup to seed the Ip rate limiting policies.

Signed-off-by: Shane Melton <smelton@bitwarden.com>

* Add caching configuration to SSO Startup.cs

Signed-off-by: Shane Melton <smelton@bitwarden.com>

* Add ProjectName as an instance name for Redis options

Signed-off-by: Shane Melton <smelton@bitwarden.com>

* Use distributed cache in CustomIpRateLimitMiddleware.cs

Signed-off-by: Shane Melton <smelton@bitwarden.com>

* Undo changes to Program.cs and launchSettings.json

* Move new service collection extensions to SharedWeb

* Upgrade Caching.StackExchangeRedis package to v6

* Cleanup and fix leftover merge conflicts

* Remove use of Newtonsoft.Json in distributed cache extensions

* Cleanup more formatting

* Fix formatting

* Fix startup issue caused by merge and fix integration test

Signed-off-by: Shane Melton <smelton@bitwarden.com>

* Linting fix

Signed-off-by: Shane Melton <smelton@bitwarden.com>
2022-07-19 11:58:32 -07:00
Thomas Rittson
6628dc3336
[EC-315] Record user IP and device type for OrgUser and ProviderUser events (#2119) 2022-07-18 10:24:46 +10:00
Rui Tomé
6e19bfeb22
[EC-307] Fresh desk custom fields integration (#2114)
* Using correct ILogger on FreshdeskController

* Submitting custom fields to Freshdesk

* Set up FreshdeskController to use IHttpClientFactory

* Added unit test for FreshdeskController

* Moved ControllerCustomizeAttribute and ControllerCustomization to Common

* Modified FreshdeskController to use FreshdeskWebhookModel; Edited unit tests to use AutoFixture
2022-07-15 17:10:56 +01:00
Justin Baur
448e255fb6
Fix flaky test (#2121) 2022-07-15 11:52:36 -04:00
Chad Scharf
19b8d8281a
[EC-261] SCIM (#2105)
* scim project stub

* some scim models and v2 controllers

* implement some v2 scim endpoints

* fix spacing

* api key auth

* EC-261 - SCIM Org API Key and connection type config

* EC-261 - Fix lint errors/formatting

* updates for okta implementation testing

* fix var ref

* updates from testing with Okta

* implement scim context via provider parsing

* support single and list of ids for add/remove groups

* log ops not handled

* touch up scim context

* group list filtering

* EC-261 - Additional SCIM provider types

* EC-265 - UseScim flag and license update

* EC-265 - SCIM provider type of default (0)

* EC-265 - Add Scim URL and update connection validation

* EC-265 - Model validation and cleanup for SCIM keys

* implement scim org connection

* EC-265 - Ensure ServiceUrl is not persisted to DB

* EC-265 - Exclude provider type from DB if not configured

* EC-261 - EF Migrations for SCIM

* add docker builds for scim

* EC-261 - Fix failing permissions tests

* EC-261 - Fix unit tests and pgsql migrations

* Formatting fixes from linter

* EC-265 - Remove service URL from scim config

* EC-265 - Fix unit tests, removed wayward validation

* EC-265 - Require self-hosted for billing sync org conn

* EC-265 - Fix formatting issues - whitespace

* EC-261 - PR feedback and cleanup

* scim constants rename

* no scim settings right now

* update project name

* delete package lock

* update appsettings configs for scim

* use default scim provider for context

Co-authored-by: Kyle Spearrin <kyle.spearrin@gmail.com>
2022-07-14 15:58:48 -04:00
Jake Fink
54cf3de11b
[EC-284] Prevent duplicate organization invites (#2113)
* prevent duplicate organization invites with test

* formatting
2022-07-13 09:21:28 -04:00
Thomas Avery
b60357eee9
Fixing missed email template (#2099) 2022-07-11 12:45:55 -05:00
Brandon Maharaj
0a334cc928
[SG-199] Move MP hint to MP change form (#2080)
* chore: backend changes

* fixed: test

* fix: lint
2022-07-11 09:28:14 -04:00
Oscar Hinton
45a005d652
Fix failing tests (#2095) 2022-07-05 18:39:43 +02:00
Oscar Hinton
113627dcd5
Add Swagger generation for Identity (#2058) 2022-07-04 12:05:46 +02:00
Justin Baur
231eb84e69
Turn On ImplicitUsings (#2079)
* Turn on ImplicitUsings

* Fix formatting

* Run linter
2022-06-29 19:46:41 -04:00
Justin Baur
cc21a04801
Address Analyzer Warnings (#2078)
* Address potential errors

* Add tests

* Add clarity

* Run formatting
2022-06-28 12:17:14 -04:00
Justin Baur
daeaa42851
[PS-40] Upgrade to .NET 6 (#2056)
* Bump to .NET 6

* Update Docker images

* Update docs

* Update workflow for linter

* Add all common versions to props file

* Update tools manifest

* Update csproj files

* Update packages.lock.json files

* Switch to setup-dotnet

* Remove msbuild

* Fix deps breaking changes

* Manually install msbuild

* Use msbuild for build

* Fix verbosity switch

* Remove unused exceptions

* Address linter feedback

* Make Obsolete warnings suggestions for now.

* Force Evaluate

* Format on tests

* Run formatting again.

* Use windows 2022

* force evaluate

* Fix restore

* Fix linter

* Skip test

* Update Directory.Build.props

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>

* Address PR feedback

* Add IntegationTest for Rate limiter

* Fix test

* Reenable test

* Reorder test

* Skip test again

* Add tracking link

* Update .github/workflows/build.yml

Co-authored-by: Micaiah Martin <77340197+mimartin12@users.noreply.github.com>

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>
Co-authored-by: Micaiah Martin <77340197+mimartin12@users.noreply.github.com>
2022-06-24 10:39:34 -04:00
Justin Baur
94059a2b06
Fix OrganizationConnection Update (#2071)
* Force CloudOrganizationId to be read only

* Fix tests
2022-06-23 07:50:10 -04:00
Matt Gibson
d918f5aae3
Check for ascii-only in entire local part of emails (#2072) 2022-06-22 17:51:16 -05:00
Thomas Avery
b19cded4f8
[PS-721] Left align all email template text (#2033)
Make all email template text left-aligned, excluding call-to-actions buttons which should remain centered

In the emails needing updates, remove font styling from HTML tags other than <td> and <p>

Add an additional margin above and below each call-to-action button

For emails that include only the “ignore” warning below the call-to-action button move the warning up, so the button is the last item displayed

Fix the unit test that allows developers to locally generate test emails
2022-06-20 09:20:28 -05:00
Thomas Rittson
3360d40592
[EC-243] Grant premium status when member accepts org invite (#2043) 2022-06-17 06:30:50 +10:00
Justin Baur
46b4207ab6
[PS-899] Fix unawaited Task (#2055)
* Fix unawaited task and switch to Guid parameters

* Remove whitespace

* Formatting

* Fix unwanted Assert
2022-06-13 11:18:53 -04:00
Matt Gibson
9ff82ab176
Use the correct policy enum type (#2045)
Explicit conversion from non-generics to generics doesn't seem to work
here, so I moved to using the read methods already on base Policy.
2022-06-09 18:57:56 -05:00
Matt Gibson
ef403b4362
[PS-616] [PS-795] Fix/auto enroll master password reset without user verification (#2038)
* Fix parameter name to match entity

* Deserialize policy data in object

* Add policy with config type to fixtures

* Return policy with deserialized config

* Use CoreHelper serializers

* Add master password reset on accept request

* Simplify policy data parsing

* Linter
2022-06-08 08:44:28 -05:00
Chad Scharf
60a167f2b7
Update swashbuckle for swaggerUI (#2039) 2022-06-07 10:11:18 -04:00
Federico Maccaroni
b070e9a387
[PS-589] Fix emergency contact takeover device verification and endpoints for its settings (#2016)
* Added UnknownDeviceVerificationEnabled on User that is turned off when emergency contact takes over the account. Also added endpoints to get and update 2fa device verification settings. And Updated migrations & tests

* Applied dotnet format

* Fixed method rename call on TwoFactorController

* PS-589 Format fixes

* PS-589 changed UnknownDeviceVerificationEnabled to be non-nullable
2022-06-06 14:52:50 -03:00
Carlos J. Muentes
14302efa2c
CSA-2 - Require user interaction for SSO redirect (#1948)
* CSA-2 - adding validation before redirecting for SSO login

* Updating server to use generated and signed JWT for SSO redirect

* Removing erroneous file

* Removing erroneous file

* Updating for PR feedback, adding domain_hint to Login and fixing invalid domain_hint name reference

* Some code styling changes from PR feedback

* Removing unnecessary JSON serialization

* Couple small changes from PR feedback

* Fixing linting errors

* Update formatting in AccountController.cs

* Remove unused dependency

* Add token lifetime to settings

* Use tokenable directly

* Return defined models

* Revert sso proj file changes

* Check expiration validity when validating org

* Show error message with expired token

* Formatting fixes

* Add SsoTokenLifetime to Sso settings

* Fix build errors

* Fix sql warnings

Co-authored-by: Carlos J. Muentes <cmuentes@bitwarden.com>
Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com>
Co-authored-by: Matt Gibson <mgibson@bitwarden.com>
2022-06-01 12:23:52 -05:00
Justin Baur
719abc7e61
[BEEEP] Integration tests (#1945)
* Add api integration tests

* Add some stuff

* Make program mockable

* Work on IntegrationTests for Identity

* Formatting

* Update packages.lock.json

* Update more packages.lock.json

* Update all packages.lock.json

* Fix InMemory configuration

* Actually fix test configuration

* Fix tests for CI

* Fix event service

* Force EF EventRepository

* Add client_credentials test

* Remove Api.IntegrationTest

* Remove Api Program changes

* Cleanup

* Add more Auth-Email tests

* Run formatting

* Address some PR feedback

* Move integration stuff to it's own common project

* Ran linter

* Add shared project to test solution

* Remove sln changes

* Clean usings

* Add more coverage

* Address PR feedback
2022-05-20 15:24:59 -04:00
Justin Baur
53241f16e0
Add Additional Logging to Self-hosted installs for F4E (#1999)
* Add logging to SH logs

* Fix tests
2022-05-16 09:57:00 -04:00
Federico Maccaroni
2e2d3075d1
EC-198 Added feature flag for 2FA Email for new device login (#1993)
* EC-198 added global setting flag for 2FA email on new device login feature

* EC-198 Removed is development environment check on 2FA email new device login given that we can now rely on the global settings feature flag

* EC-198 Improved IGlobalSettings and UserService code for testing
2022-05-13 10:48:48 -03:00
Matt Gibson
c54c39b28c
Feature/self hosted families for enterprise (#1991)
* Families for enterprise/split up organization sponsorship service (#1829)

* Split OrganizationSponsorshipService into commands

* Use tokenable for token validation

* Use interfaces to set up for DI

* Use commands over services

* Move service tests to command tests

* Value types can't be null

* Run dotnet format

* Update src/Core/OrganizationFeatures/OrganizationSponsorships/FamiliesForEnterprise/CancelSponsorshipCommand.cs

Co-authored-by: Justin Baur <admin@justinbaur.com>

* Fix controller tests

Co-authored-by: Justin Baur <admin@justinbaur.com>

* Families for enterprise/split up organization sponsorship service (#1875)

* Split OrganizationSponsorshipService into commands

* Use tokenable for token validation

* Use interfaces to set up for DI

* Use commands over services

* Move service tests to command tests

* Value types can't be null

* Run dotnet format

* Update src/Core/OrganizationFeatures/OrganizationSponsorships/FamiliesForEnterprise/CancelSponsorshipCommand.cs

Co-authored-by: Justin Baur <admin@justinbaur.com>

* Fix controller tests

* Split create and send sponsorships

* Split up create sponsorship

* Add self hosted commands to dependency injection

* Add field to store cloud billing sync key on self host instances

* Fix typo

* Fix data protector purpose of sponsorship offers

* Split cloud and selfhosted sponsorship offer tokenable

* Generate offer from self hosted with all necessary auth data

* Add Required properties to constructor

* Split up cancel sponsorship command

* Split revoke sponsorship command between cloud and self hosted

* Fix/f4e multiple sponsorships (#1838)

* Use sponosorship from validate to redeem

* Update tests

* Format

* Remove sponsorship service

* Run dotnet format

* Fix self hosted only controller attribute

* Clean up file structure and fixes

* Remove unneeded tokenables

* Remove obsolete commands

* Do not require file/class prefix if unnecessary

* Update Organizaiton sprocs

* Remove unnecessary models

* Fix tests

* Generalize LicenseService path calculation

Use async file read and deserialization

* Use interfaces for testability

* Remove unused usings

* Correct test direction

* Test license reading

* remove unused usings

* Format

Co-authored-by: Justin Baur <admin@justinbaur.com>

* Improve DataProtectorTokenFactory test coverage (#1884)

* Add encstring to server

* Test factory

Co-authored-by: Carlos Muentes <cmuentes@bitwarden.com>

* Format

* Remove SymmetricKeyProtectedString

Not needed

* Set ForcInvalid

Co-authored-by: Carlos Muentes <cmuentes@bitwarden.com>

* Feature/self f4e/api keys (#1896)

* Add in ApiKey

* Work on API Key table

* Work on apikey table

* Fix response model

* Work on information for UI

* Work on last sync date

* Work on sync status

* Work on auth

* Work on tokenable

* Work on merge

* Add custom requirement

* Add policy

* Run formatting

* Work on EF Migrations

* Work on OrganizationConnection

* Work on database

* Work on additional database table

* Run formatting

* Small fixes

* More cleanup

* Cleanup

* Add RevisionDate

* Add GO

* Finish Sql project

* Add newlines

* Fix stored proc file

* Fix sqlproj

* Add newlines

* Fix table

* Add navigation property

* Delete Connections when organization is deleted

* Add connection validation

* Start adding ID column

* Work on ID column

* Work on SQL migration

* Work on migrations

* Run formatting

* Fix test build

* Fix sprocs

* Work on migrations

* Fix Create table

* Fix sproc

* Add prints to migration

* Add default value

* Update EF migrations

* Formatting

* Add to integration tests

* Minor fixes

* Formatting

* Cleanup

* Address PR feedback

* Address more PR feedback

* Fix formatting

* Fix formatting

* Fix

* Address PR feedback

* Remove accidential change

* Fix SQL build

* Run formatting

* Address PR feedback

* Add sync data to OrganizationUserOrgDetails

* Add comments

* Remove OrganizationConnectionService interface

* Remove unused using

* Address PR feedback

* Formatting

* Minor fix

* Feature/self f4e/update db (#1930)

* Fix migration

* Fix TimesRenewed

* Add comments

* Make two properties non-nullable

* Remove need for SponsoredOrg on SH (#1934)

* Remove need for SponsoredOrg on SH

* Add Family prefix

* Add check for enterprise org on BillingSync key (#1936)

* [PS-10] Feature/sponsorships removed at end of term (#1938)

* Rename commands to min unique names

* Inject revoke command based on self hosting

* WIP: Remove/Revoke marks to delete

* Complete WIP

* Improve remove/revoke tests

* PR review

* Fail validation if sponsorship has failed to sync for 6 months

* Feature/do not accept old self host sponsorships (#1939)

* Do not accept >6mo old self-hosted sponsorships

* Give disabled grace period of 3 months

* Fix issues of Sql.proj differing from migration outcome (#1942)

* Fix issues of Sql.proj differing from migration outcome

* Yoink int tests

* Add missing assert helpers

* Feature/org sponsorship sync (#1922)

* Self-hosted side sync first pass

TODO:
* flush out org sponsorship model
* implement cloud side
* process cloud-side response and update self-hosted records

* sync scaffolding second pass

* remove list of Org User ids from sync and begin work on SelfHostedRevokeSponsorship

* allow authenticated http calls from server to return a result

* update models

* add logic for sync and change offer email template

* add billing sync key and hide CreateSponsorship without user

* fix tests

* add job scheduling

* add authorize attributes to endpoints

* separate models into data/model and request/response

* batch sync more, add EnableCloudCommunication for testing

* send emails in bulk

* make userId and sponsorshipType non nullable

* batch more on self hosted side of sync

* remove TODOs and formatting

* changed logic of cloud sync

* let BaseIdentityClientService handle all logging

* call sync from scheduled job on self host

* create bulk db operations for OrganizationSponsorships

* remove SponsoredOrgId from sync, return default from server http call

* validate BillingSyncKey during sync

revert changes to CreateSponsorshipCommand

* revert changes to ICreateSponsorshipCommand

* add some tests

* add DeleteExpiredSponsorshipsJob

* add cloud sync test

* remove extra method

* formatting

* prevent new sponsorships from disabled orgs

* update packages

* - pulled out send sponsorship command dependency from sync on cloud
- don't throw error when sponsorships are empty
- formatting

* formatting models

* more formatting

* remove licensingService dependency from selfhosted sync

* use installation urls and formatting

* create constructor for RequestModel and formatting

* add date parameter to OrganizationSponsorship_DeleteExpired

* add new migration

* formatting

* rename OrganizationCreateSponsorshipRequestModel to OrganizationSponsorshipCreateRequestModel

* prevent whole sync from failing if one sponsorship type is unsupported

* deserialize config and billingsynckey from org connection

* alter log message when sync disabled

* Add grace period to disabled orgs

* return early on self hosted if there are no sponsorships in database

* rename BillingSyncConfig

* send sponsorship offers from controller

* allow config to be a null object

* better exception handling in sync scheduler

* add ef migrations

* formatting

* fix tests

* fix validate test

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>

* Fix OrganizationApiKey issues (#1941)

Co-authored-by: Justin Baur <admin@justinbaur.com>

* Feature/org sponsorship self hosted tests (#1947)

* Self-hosted side sync first pass

TODO:
* flush out org sponsorship model
* implement cloud side
* process cloud-side response and update self-hosted records

* sync scaffolding second pass

* remove list of Org User ids from sync and begin work on SelfHostedRevokeSponsorship

* allow authenticated http calls from server to return a result

* update models

* add logic for sync and change offer email template

* add billing sync key and hide CreateSponsorship without user

* fix tests

* add job scheduling

* add authorize attributes to endpoints

* separate models into data/model and request/response

* batch sync more, add EnableCloudCommunication for testing

* send emails in bulk

* make userId and sponsorshipType non nullable

* batch more on self hosted side of sync

* remove TODOs and formatting

* changed logic of cloud sync

* let BaseIdentityClientService handle all logging

* call sync from scheduled job on self host

* create bulk db operations for OrganizationSponsorships

* remove SponsoredOrgId from sync, return default from server http call

* validate BillingSyncKey during sync

revert changes to CreateSponsorshipCommand

* revert changes to ICreateSponsorshipCommand

* add some tests

* add DeleteExpiredSponsorshipsJob

* add cloud sync test

* remove extra method

* formatting

* prevent new sponsorships from disabled orgs

* update packages

* - pulled out send sponsorship command dependency from sync on cloud
- don't throw error when sponsorships are empty
- formatting

* formatting models

* more formatting

* remove licensingService dependency from selfhosted sync

* use installation urls and formatting

* create constructor for RequestModel and formatting

* add date parameter to OrganizationSponsorship_DeleteExpired

* add new migration

* formatting

* rename OrganizationCreateSponsorshipRequestModel to OrganizationSponsorshipCreateRequestModel

* prevent whole sync from failing if one sponsorship type is unsupported

* deserialize config and billingsynckey from org connection

* add mockHttp nuget package and use httpclientfactory

* fix current tests

* WIP of creating tests

* WIP of new self hosted tests

* WIP self hosted tests

* finish self hosted tests

* formatting

* format of interface

* remove extra config file

* added newlines

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>

* Fix Organization_DeleteById (#1950)

* Fix Organization_Delete

* Fix L

* [PS-4] block enterprise user from sponsoring itself (#1943)

* [PS-248] Feature/add connections enabled endpoint (#1953)

* Move Organization models to sub namespaces

* Add Organization Connection api endpoints

* Get all connections rather than just enabled ones

* Add missing services to DI

* pluralize private api endpoints

* Add type protection to org connection request/response

* Fix route

* Use nullable Id to signify no connection

* Test Get Connections enabled

* Fix data discoverer

* Also drop this sproc for rerunning

* Id is the OUTPUT of create sprocs

* Fix connection config parsing

* Linter fixes

* update sqlproj file name

* Use param xdocs on methods

* Simplify controller path attribute

* Use JsonDocument to avoid escaped json in our response/request strings

* Fix JsonDoc tests

* Linter fixes

* Fix ApiKey Command and add tests (#1949)

* Fix ApiKey command

* Formatting

* Fix test failures introduced in #1943 (#1957)

* Remove "Did you know?" copy from emails. (#1962)

* Remove "Did you know"

* Remove jsonIf helper

* Feature/fix send single sponsorship offer email (#1956)

* Fix sponsorship offer email

* Do not sanitize org name

* PR feedback

* Feature/f4e sync event [PS-75] (#1963)

* Create sponsorship sync event type

* Add InstallationId to Event model

* Add combinatorics-based test case generators

* Log sponsorships sync event on sync

* Linter and test fixes

* Fix failing test

* Migrate sprocs and view

* Remove unused `using`s

* [PS-190] Add manual sync trigger in self hosted (#1955)

* WIP add button to admin project for billing sync

* add connection table to view page

* minor fixes for self hosted side of sync

* fixes number of bugs for cloud side of sync

* deserialize before returning for some reason

* add json attributes to return models

* list of sponsorships parameter is immutable, add secondary list

* change sproc name

* add error handling

* Fix tests

* modify call to connection

* Update src/Admin/Controllers/OrganizationsController.cs

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>

* undo change to sproc name

* simplify logic

* Update src/Core/OrganizationFeatures/OrganizationSponsorships/FamiliesForEnterprise/Cloud/CloudSyncSponsorshipsCommand.cs

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>

* register services despite if self hosted or cloud

* remove json properties

* revert merge conflict

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>

* Update OrganizationSponsorship valid until when updating org expirati… (#1966)

* Update OrganizationSponsorship valid until when updating org expiration date

* Linter fixes

* [PS-7] change revert email copy and add ValidUntil to sponsorship (#1965)

* change revert email copy and add ValidUntil to sponsorship

* add 15 days if no ValidUntil

* Chore/merge/self hosted families for enterprise (#1972)

* Log swallowed HttpRequestExceptions (#1866)

Co-authored-by: Hinton <oscar@oscarhinton.com>

* Allow for utilization of  readonly db connection (#1937)

* Bump the pin of the download-artifacts action to bypass the broken GitHub api (#1952)

* Bumped version to 1.48.0 (#1958)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* [EC-160] Give Provider Users access to all org ciphers and collections (#1959)

* Bumped version to 1.48.1 (#1961)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Avoid sending "user need confirmation" emails when there are no org admins (#1960)

* Remove noncompliant users for new policies (#1951)

* [PS-284] Allow installation clients to not need a user. (#1968)

* Allow installation clients to not need a user.

* Run formatting

Co-authored-by: Andrei <30410186+Manolachi@users.noreply.github.com>
Co-authored-by: Hinton <oscar@oscarhinton.com>
Co-authored-by: sneakernuts <671942+sneakernuts@users.noreply.github.com>
Co-authored-by: Joseph Flinn <58369717+joseph-flinn@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Justin Baur <136baur@gmail.com>

* Fix/license file not found (#1974)

* Handle null license

* Throw hint message if license is not found by the admin project.

* Use CloudOrganizationId from Connection config

* Change test to support change

* Fix test

Co-authored-by: Matt Gibson <mgibson@bitwarden.com>

* Feature/f4e selfhosted rename migration to .sql (#1971)

* rename migration to .sql

* format

* Add unit tests to self host F4E (#1975)

* Work on tests

* Added more tests

* Run linting

* Address PR feedback

* Fix AssertRecent

* Linting

* Fixed empty tests

* Fix/misc self hosted f4e (#1973)

* Allow setting of ApiUri

* Return updates sponsorshipsData objects

* Bind arguments by name

* Greedy load sponsorships to email.

When upsert was called, it creates Ids on _all_ records, which meant
that the lazy-evaluation from this call always returned an empty list.

* add scope for sync command DI in job. simplify error logic

* update the sync job to get CloudOrgId from the BillingSyncKey

Co-authored-by: Jacob Fink <jfink@bitwarden.com>

* Chore/merge/self hosted families for enterprise (#1987)

* Log swallowed HttpRequestExceptions (#1866)

Co-authored-by: Hinton <oscar@oscarhinton.com>

* Allow for utilization of  readonly db connection (#1937)

* Bump the pin of the download-artifacts action to bypass the broken GitHub api (#1952)

* Bumped version to 1.48.0 (#1958)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* [EC-160] Give Provider Users access to all org ciphers and collections (#1959)

* Bumped version to 1.48.1 (#1961)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Avoid sending "user need confirmation" emails when there are no org admins (#1960)

* Remove noncompliant users for new policies (#1951)

* [PS-284] Allow installation clients to not need a user. (#1968)

* Allow installation clients to not need a user.

* Run formatting

* Use accept flow for sponsorship offers (#1964)

* PS-82 check send 2FA email for new devices on TwoFactorController send-email-login (#1977)

* [Bug] Skip WebAuthn 2fa event logs during login flow (#1978)

* [Bug] Supress WebAuthn 2fa event logs during login process

* Formatting

* Simplified method call with new paramter input

* Update RealIps Description (#1980)

Describe the syntax of the real_ips configuration key with an example, to prevent type errors in the `setup` container when parsing `config.yml`

* add proper URI validation to duo host (#1984)

* captcha scores (#1967)

* captcha scores

* some api fixes

* check bot on captcha attribute

* Update src/Core/Services/Implementations/HCaptchaValidationService.cs

Co-authored-by: e271828- <e271828-@users.noreply.github.com>

Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com>
Co-authored-by: e271828- <e271828-@users.noreply.github.com>

* ensure no path specific in duo host (#1985)

Co-authored-by: Andrei <30410186+Manolachi@users.noreply.github.com>
Co-authored-by: Hinton <oscar@oscarhinton.com>
Co-authored-by: sneakernuts <671942+sneakernuts@users.noreply.github.com>
Co-authored-by: Joseph Flinn <58369717+joseph-flinn@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Justin Baur <136baur@gmail.com>
Co-authored-by: Federico Maccaroni <fedemkr@gmail.com>
Co-authored-by: Vincent Salucci <26154748+vincentsalucci@users.noreply.github.com>
Co-authored-by: Jordan Cooks <notnamed@users.noreply.github.com>
Co-authored-by: Kyle Spearrin <kspearrin@users.noreply.github.com>
Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com>
Co-authored-by: e271828- <e271828-@users.noreply.github.com>

* Address feedback (#1990)

Co-authored-by: Justin Baur <admin@justinbaur.com>
Co-authored-by: Carlos Muentes <cmuentes@bitwarden.com>
Co-authored-by: Jake Fink <jfink@bitwarden.com>
Co-authored-by: Justin Baur <136baur@gmail.com>
Co-authored-by: Andrei <30410186+Manolachi@users.noreply.github.com>
Co-authored-by: Hinton <oscar@oscarhinton.com>
Co-authored-by: sneakernuts <671942+sneakernuts@users.noreply.github.com>
Co-authored-by: Joseph Flinn <58369717+joseph-flinn@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
Co-authored-by: Federico Maccaroni <fedemkr@gmail.com>
Co-authored-by: Vincent Salucci <26154748+vincentsalucci@users.noreply.github.com>
Co-authored-by: Jordan Cooks <notnamed@users.noreply.github.com>
Co-authored-by: Kyle Spearrin <kspearrin@users.noreply.github.com>
Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com>
Co-authored-by: e271828- <e271828-@users.noreply.github.com>
2022-05-10 16:12:09 -05:00
Federico Maccaroni
a7a45893a3
PS-82 check send 2FA email for new devices on TwoFactorController send-email-login (#1977) 2022-04-28 13:14:09 -03:00
sneakernuts
0e88720d3a
Logging config changes (#1935)
* Logging config changes

* Regenerated packages.lock.json files

* fixed up more typos and regenerated json
2022-04-05 15:19:16 +00:00
Federico Maccaroni
6f60d24f5a
Email verification for new devices (#1931)
* PS-56 Added Email 2FA on login with new devices that don't have any 2FA enabled

* PS-56 Fixed wrong argument in VerifyTwoFactor call
2022-04-01 17:08:47 -03:00
Justin Baur
dd37745736
Fix OneLogin Import (#1899)
* Add PermissiveStringConverter

* Formatting

* Add value check

* Fix PR feedback

* Run formatter
2022-03-08 13:22:47 -05:00
Matt Gibson
a725802476
Handle null user in captch tokenable (#1897)
* Handle null user in captch tokenable

* Update test/Core.Test/Models/Business/Tokenables/HCaptchaTokenableTests.cs

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
2022-03-08 08:21:54 -06:00
Robyn MacCallum
17b22ca5a9
Add attachments check before moving ciphers to a free org (#1890) 2022-03-02 17:37:36 -05:00
Kyle Spearrin
4cbe05da3c
SendGrid Mail Delivery Provider (#1892)
* add sendgrid mail delivery service

* <

* remove duplicate code

* fix test by using ISendGridClient interface
2022-03-01 19:09:51 -05:00
Justin Baur
6f12a9e621
Additional 2FA tests (#1860)
* Add 2FA tests for organization

* Move user tests to be in same directory

* Fixed some names and namespace qualifications

* Add GetTwoFactorProviders tests

* Add tests to ensure we can read from name as well
2022-02-10 13:48:06 -05:00
Oscar Hinton
8d6c49f656
Add lock files for NuGet (#1855) 2022-02-10 15:40:31 +01:00
Justin Baur
b1cd42e394
Fix json only serializing base properties (#1840)
* Fix json only serializing base properties

* Run formatting

* Switch to returning concrete type

* Update method name
2022-02-07 10:28:11 -05:00
Justin Baur
9e074bca49
Revert TwoFactorProviders to be saved with numerical value (#1828)
* Add enum key resolver

* Change tests to reflect changes
2022-02-02 14:21:11 -05:00
Matt Gibson
8ce4d56a91
Fix/f4e multiple sponsorships (#1838)
* Use sponosorship from validate to redeem

* Update tests

* Format
2022-02-02 12:59:47 -06:00
Justin Baur
b47c30d4f4
Fix organization_license not reading camelCase (#1832)
* Fix organization_license not reading camelCase

* Fix formatting
2022-02-01 12:26:50 -05:00
Oscar Hinton
ac8ca46f0f
Remove the u2f lib (#1820) 2022-01-24 12:14:04 +01:00
Justin Baur
5268f2781e
Start Migration from Newtonsoft.Json to System.Text.Json (#1803)
* Start switch to System.Text.Json

* Work on switching to System.Text.Json

* Main work on STJ refactor

* Fix build errors

* Run formatting

* Delete unused file

* Use legacy for two factor providers

* Run formatter

* Add TokenProviderTests

* Run formatting

* Fix merge issues

* Switch to use JsonSerializer

* Address PR feedback

* Fix formatting

* Ran formatter

* Switch to async

* Ensure Enums are serialized as strings

* Fix formatting

* Enqueue single items as arrays

* Remove CreateAsync method on AzureQueueService
2022-01-21 09:36:25 -05:00
Oscar Hinton
68a8092235
[Emergency Access] Add premium check (#1815) 2022-01-18 16:05:12 +01:00
Oscar Hinton
0def1830af
Move identity endpoints to Identity service (#1807) 2022-01-17 13:21:51 +01:00
Oscar Hinton
e4a10aae27
Split out repositories to Infrastructure.Dapper / EntityFramework (#1759) 2022-01-11 10:40:51 +01:00
Matt Gibson
e2c6fc81f4
Feature/token service (#1785)
* Implement draft token service

* Add tokenizer and factory

* Handle expiring tokens through base class

* Allow direct token validity checks

* Add safe unprotect to tokenizer

* Add interface to tokenizer factory

* Use tokenizer

* Fix rebase

* Handle cleartext prefix in tokenizer base

* Use epoch milliseconds for expiration in tokens

* Use tokenizers

* Test tokens

* Linter fixes

* Add TokenizerFactory to DI services

* Test epoch milliseconds deserialization

* Use separate injectables for each token type

* Fix directory

* Add functional unprotect to token

* Fix namespace and correct object names

* Remove Tokenable interface

* Test remaining Tokens classes

* Dotnet format

* Fix sut provider errors with update

* Remove useless property

Co-authored-by: Hinton <oscar@oscarhinton.com>
2022-01-10 09:58:16 -06:00
Oscar Hinton
9086db3b0d
Fix format of StripePaymentService tests (#1794) 2022-01-03 18:11:11 +01:00
Oscar Hinton
73b3b9b0c9
Add test cases for StripePaymentService (#1615) 2022-01-03 15:44:28 +01:00
Justin Baur
bb34de74cb
Freshsales integration (#1782)
* Add FreshsalesController

* Add better errors

* Fix formatting issues

* Add comments

* Add Billing.Test to solution files

* Fix unit test

* Format code

* Address PR feedback
2021-12-22 13:27:52 -05:00
Oscar Hinton
23b0a1f9df
Run dotnet format (#1764) 2021-12-16 15:35:09 +01:00
Matt Gibson
e999f66a28
Send invites for both all collection and limited collection users (#1765)
* Send invites for both all collection and limited collection users

* Test all access and limited access invites

* Remove comment
2021-12-14 10:29:31 -06:00
Oscar Hinton
63f6dd9a24
Move request/response models (#1754) 2021-12-14 16:05:07 +01:00
Matt Gibson
a70564cea8
Families for enterprise/fix new org sponsorship after deleted sponsored org (#1740)
* Sponsorship exists only if sponsored org is not null

* Replace existing sponsorship if necessary

* Update src/Core/Services/Implementations/OrganizationSponsorshipService.cs

Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com>

* Fix tests

Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com>
2021-12-02 10:27:41 -06:00
Matt Gibson
8dffb27667
Families for enterprise/add sponsorship prevalidate (#1734)
* Add sponsorship prevalidate endpoint

* Test pre validate endpoint

* Fix tests

* Rename variable
2021-11-24 14:18:52 -06:00
Thomas Rittson
29d3e1fd2b
Fix null error when leaving organization (#1730)
* Fix null error when leaving organization

* Update tests
2021-11-22 19:55:25 +10:00
Thomas Rittson
7e3e87ed39
Update error message for leaving org with CME (#1729) 2021-11-22 08:22:28 +10:00
Matt Gibson
33edc8eba0
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 1185bf3ec8.

* 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 17:25:06 -05:00
Thomas Rittson
2dc29e51d1
Fix bug preventing user from leaving org (#1721) 2021-11-18 21:15:22 +10:00
Thomas Rittson
9f96e4ce90
Disable EA Takeover if grantor uses Key Connector (#1718) 2021-11-18 07:47:43 +10:00
Oscar Hinton
f866b25e43
Key Connector feature toggle (#1716) 2021-11-17 11:46:35 +01:00
Thomas Rittson
e3143271d7
[Key Connector] Prevent user from leaving org (#1715)
* Block user from leaving org using Key Connector

* Add tests
2021-11-15 19:46:13 +10:00
Thomas Rittson
c2975b003d
[Key Connector] Fix policy checks and other pre-reqs (#1711)
* Require SSO Policy to enable Key Connector

* Require that SSO is enabled to use Key Connector

* Fix error messages

"Key Connector" instead of "KeyConnector"

* Refactor dependent policy checks to handle expansion

* Block disabling Sso Policy if using Key Connector

* Update tests for policies required by Key Connector

* Fix tests

* Add test for Key Connector to require Sso Policy

* Add test: Sso config must be enabled to use Key Connector
2021-11-15 19:25:10 +10:00
Oscar Hinton
f1c41257b3
Allow disabling key connector if no user is enrolled (#1712) 2021-11-12 14:38:31 +01:00
Oscar Hinton
fd37cb5a12
Add support for Key Connector OTP and account migration (#1663)
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
2021-11-09 16:37:32 +01:00
Oscar Hinton
1aa25f2712
Add checks for vault timeout policy (#1694) 2021-11-08 14:37:40 +01:00
Thomas Rittson
e57bef6af4
Fix policy enforcement against invited users (#1680) 2021-11-03 07:08:13 +10:00
Justin Baur
4c9d9b248c
Fix bug in TaxInfo (#1682)
* Fixed bug in TaxInfo

* Added a few more tests to TaxInfoTests

* Added tests for HasTaxId
2021-11-01 12:13:31 -04:00
SudoEvan
dcc11e3819
Added unit tests for StrictEmailAddressListAttribute in Bit.Core.Utilities (#1652)
* Added unit tests for StrictEmailAddressListAttribute in Bit.Core.Utilities

* Fixed list format; added a null test on StrictEmailAddressListAttribute in Utilities
2021-10-29 12:24:53 -04:00
Justin Baur
114f58aa8e
Fix tests (#1675)
* Fix SendServiceTests that arose from merge

* Fixed SendService tests to be inline with spec

* Reorder usings
2021-10-28 15:47:58 -04:00
Justin Baur
d854332643
Unit Tests for hot spots (#1454)
* Add TaxInfoTests

* Add UserTests

* Add SendServicTests

* Added IconFetchingServicesTests

* Add endline
2021-10-28 14:30:41 -04:00
Matt Gibson
8f0115e62f
Check canScale when scaling for sso (#1661)
* Check canScale when scaling for sso

* PR review

Use AutoAddSeats to add seats in a consistent way.
This requires moving user check out of that method.

* User logic moved out of method
2021-10-25 10:19:37 -05:00
Oscar Hinton
c5d5601464
Add support for crypto agent (#1623) 2021-10-25 15:09:14 +02:00
Oscar Hinton
79447b6671
Remove Business Portal (#1614) 2021-10-06 10:39:13 +02:00
Matt Gibson
bd297fb7a2
SqlServer split manage collection permission (#1594)
* SqlServer split manage collection permission

* Clarify names

* Test claims generation

* Test permission serialization

* Simplify claims building

* Use new collections permissions

* Throw on use of deprecated permissions

* Lower case all claims

* Remove todos

* Clean nonexistent project from test solution

* JsonIgnore for both system and newtonsoft json

* Make migrations more robust to multiple runs

* remove duplicate usings

* Remove obsolete permissions

* Test solutions separately to detect failures

* Handle dos line endings

* Fix collections create/update permissions

* Change restore cipher to edit permissions

* Improve formatting

* Simplify map

* Refactor test
2021-10-05 11:12:05 -05:00
Oscar Hinton
63c8070b01
Add Stripe Adapter and IBraintreeGateway to DI (#1596) 2021-09-27 23:01:13 +02:00
Thomas Rittson
66629b2f1c
Refactor policy checks (#1536)
* Move policy checking logic inside PolicyService

* Refactor to use currentContext.ManagePolicies

* Make orgUser status check more semantic

* Fix single org user checks

* Use CoreHelper implementation to deserialize json

* Refactor policy checks to use db query

* Use new db query for enforcing 2FA Policy

* Add Policy_ReadByTypeApplicableToUser

* Stub out EF implementations

* Refactor: use PolicyRepository only

* Refactor tests

* Copy SQL queries to proj and update sqlproj file

* Refactor importCiphersAsync to use new method

* Add EF implementations and tests

* Refactor SQL to remove unnecessary operations
2021-09-28 06:54:28 +10:00
Matt Gibson
d39f45c81c
Organization autoscaling (#1585)
* Add autoscale fields to Organization

* Add autoscale setting changes

* Autoscale organizations

updates InviteUsersAsync to support all invite sources.

sends an email to org owners when organization autoscaled

* All organizations autoscale

Disabling autoscaling can be done by setting max seats to current seats.

We only warn about autoscaling on the first autoscaling event.

* Fix tests

* Bug fixes

* Simplify subscription update logic

* Void invoices that fail to delete

Stripe no longer allows deletion of draft invoices that were created as part of subscription updates. It's necessary to void out these invoices without sending tem to the client.

* Notify org owners when their subscription runs out of seats

* Use datetime for notifications

Allows for later re-sending email if we want to periodically remind
owners

* Do not update subscription if it already matches new quatity

* Include all migrations

* Remove unnecessary inline styling

* SubscriptionUpdate handles update decisions

* Remove unnecessary html setter

* PR review

* Use minimum access for class methods
2021-09-23 05:36:08 -05:00
Oscar Hinton
c22e48c1b4
Resolve error when deleting an account connected to a provider (#1580) 2021-09-15 20:34:06 +02:00
Thomas Rittson
e1908cd6b5
Add support for international domain names (IDN) in email addresses (#1512)
* Adjust email address checking to handle unicode

* ASCII only in local part
* allow unicode in second-level and top-level domain

* Add PunyEncoding/Decoding methods and tests

* Use PunyEncoding for outbound email recipients

* Use MailKit for punycode, handle edge cases

* Punyencode all email addresses in mailServices

* Remove punyencoding from HandlebarsMailService

* Add to punyencoding tests

* Use more inclusive e-mail error

* Fix comment wording

* Apply StrictEmail checking to emergency access invite

* Remove punyDecode helper
2021-08-31 13:49:11 +10:00
Matt Gibson
1779d33a66
Verify Send file does not exist before saving file (#1515)
* Verify Send file does not exist before saving file

* Fix flaky test
2021-08-17 08:37:00 -05:00