diff --git a/.editorconfig b/.editorconfig index fd68808456..71dd40de98 100644 --- a/.editorconfig +++ b/.editorconfig @@ -71,10 +71,10 @@ dotnet_naming_symbols.any_async_methods.applicable_kinds = method dotnet_naming_symbols.any_async_methods.applicable_accessibilities = * dotnet_naming_symbols.any_async_methods.required_modifiers = async -dotnet_naming_style.end_in_async.required_prefix = +dotnet_naming_style.end_in_async.required_prefix = dotnet_naming_style.end_in_async.required_suffix = Async dotnet_naming_style.end_in_async.capitalization = pascal_case -dotnet_naming_style.end_in_async.word_separator = +dotnet_naming_style.end_in_async.word_separator = # Obsolete warnings, this should be removed or changed to warning once we address some of the obsolete items. dotnet_diagnostic.CS0618.severity = suggestion @@ -85,6 +85,12 @@ dotnet_diagnostic.CS0612.severity = suggestion # Remove unnecessary using directives https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0005 dotnet_diagnostic.IDE0005.severity = warning +# Specify CultureInfo https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1304 +dotnet_diagnostic.CA1304.severity = warning + +# Specify IFormatProvider https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1305 +dotnet_diagnostic.CA1305.severity = warning + # CSharp code style settings: [*.cs] # Prefer "var" everywhere diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 694e9048a7..a7717be4e8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -31,7 +31,7 @@ jobs: persist-credentials: false - name: Set up .NET - uses: actions/setup-dotnet@d4c94342e560b34958eacfc5d055d21461ed1c5d # v5.0.0 + uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 - name: Verify format run: dotnet format --verify-no-changes @@ -39,8 +39,7 @@ jobs: build-artifacts: name: Build Docker images runs-on: ubuntu-22.04 - needs: - - lint + needs: lint outputs: has_secrets: ${{ steps.check-secrets.outputs.has_secrets }} permissions: @@ -120,7 +119,7 @@ jobs: fi - name: Set up .NET - uses: actions/setup-dotnet@d4c94342e560b34958eacfc5d055d21461ed1c5d # v5.0.0 + uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 - name: Set up Node uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0 @@ -271,7 +270,7 @@ jobs: output-format: sarif - name: Upload Grype results to GitHub - uses: github/codeql-action/upload-sarif@e12f0178983d466f2f6028f5cc7a6d786fd97f4b # v4.31.4 + uses: github/codeql-action/upload-sarif@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9 with: sarif_file: ${{ steps.container-scan.outputs.sarif }} sha: ${{ contains(github.event_name, 'pull_request') && github.event.pull_request.head.sha || github.sha }} @@ -295,7 +294,7 @@ jobs: persist-credentials: false - name: Set up .NET - uses: actions/setup-dotnet@d4c94342e560b34958eacfc5d055d21461ed1c5d # v5.0.0 + uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 - name: Log in to Azure uses: bitwarden/gh-actions/azure-login@main @@ -401,8 +400,7 @@ jobs: build-mssqlmigratorutility: name: Build MSSQL migrator utility runs-on: ubuntu-22.04 - needs: - - lint + needs: lint defaults: run: shell: bash @@ -422,7 +420,7 @@ jobs: persist-credentials: false - name: Set up .NET - uses: actions/setup-dotnet@d4c94342e560b34958eacfc5d055d21461ed1c5d # v5.0.0 + uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 - name: Print environment run: | @@ -452,14 +450,13 @@ jobs: path: util/MsSqlMigratorUtility/obj/build-output/publish/MsSqlMigratorUtility if-no-files-found: error - self-host-build: - name: Trigger self-host build + bitwarden-lite-build: + name: Trigger Bitwarden lite build if: | github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/rc' || github.ref == 'refs/heads/hotfix-rc') runs-on: ubuntu-22.04 - needs: - - build-artifacts + needs: build-artifacts permissions: id-token: write steps: @@ -505,11 +502,10 @@ jobs: }); trigger-k8s-deploy: - name: Trigger k8s deploy + name: Trigger K8s deploy if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' runs-on: ubuntu-22.04 - needs: - - build-artifacts + needs: build-artifacts permissions: id-token: write steps: @@ -539,7 +535,7 @@ jobs: owner: ${{ github.repository_owner }} repositories: devops - - name: Trigger k8s deploy + - name: Trigger K8s deploy uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: github-token: ${{ steps.app-token.outputs.token }} @@ -557,8 +553,7 @@ jobs: setup-ephemeral-environment: name: Setup Ephemeral Environment - needs: - - build-artifacts + needs: build-artifacts if: | needs.build-artifacts.outputs.has_secrets == 'true' && github.event_name == 'pull_request' @@ -581,7 +576,7 @@ jobs: - build-artifacts - upload - build-mssqlmigratorutility - - self-host-build + - bitwarden-lite-build - trigger-k8s-deploy permissions: id-token: write diff --git a/.github/workflows/cleanup-after-pr.yml b/.github/workflows/cleanup-after-pr.yml deleted file mode 100644 index 4e59f1fa96..0000000000 --- a/.github/workflows/cleanup-after-pr.yml +++ /dev/null @@ -1,71 +0,0 @@ -name: Container registry cleanup - -on: - pull_request: - types: [closed] - -env: - _AZ_REGISTRY: "bitwardenprod.azurecr.io" - -jobs: - build-docker: - name: Remove branch-specific Docker images - runs-on: ubuntu-22.04 - permissions: - id-token: write - steps: - - name: Log in to Azure - uses: bitwarden/gh-actions/azure-login@main - with: - subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} - tenant_id: ${{ secrets.AZURE_TENANT_ID }} - client_id: ${{ secrets.AZURE_CLIENT_ID }} - - - name: Log in to Azure ACR - run: az acr login -n "$_AZ_REGISTRY" --only-show-errors - - ########## Remove Docker images ########## - - name: Remove the Docker image from ACR - env: - REF: ${{ github.event.pull_request.head.ref }} - SERVICES: | - services: - - Admin - - Api - - Attachments - - Events - - EventsProcessor - - Icons - - Identity - - K8S-Proxy - - MsSql - - Nginx - - Notifications - - Server - - Setup - - Sso - run: | - for SERVICE in $(echo "${SERVICES}" | yq e ".services[]" - ) - do - SERVICE_NAME=$(echo "$SERVICE" | awk '{print tolower($0)}') - IMAGE_TAG=$(echo "${REF}" | sed "s#/#-#g") # slash safe branch name - - echo "[*] Checking if remote exists: $_AZ_REGISTRY/$SERVICE_NAME:$IMAGE_TAG" - TAG_EXISTS=$( - az acr repository show-tags --name "$_AZ_REGISTRY" --repository "$SERVICE_NAME" \ - | jq --arg TAG "$IMAGE_TAG" -e '. | any(. == $TAG)' - ) - - if [[ "$TAG_EXISTS" == "true" ]]; then - echo "[*] Tag exists. Removing tag" - az acr repository delete --name "$_AZ_REGISTRY" --image "$SERVICE_NAME:$IMAGE_TAG" --yes - else - echo "[*] Tag does not exist. No action needed" - fi - done - - - name: Log out of Docker - run: docker logout - - - name: Log out from Azure - uses: bitwarden/gh-actions/azure-logout@main diff --git a/.github/workflows/review-code.yml b/.github/workflows/review-code.yml index 0e0597fccf..000f402096 100644 --- a/.github/workflows/review-code.yml +++ b/.github/workflows/review-code.yml @@ -2,7 +2,7 @@ name: Code Review on: pull_request: - types: [opened, synchronize, reopened, ready_for_review] + types: [opened, synchronize, reopened] permissions: {} diff --git a/.github/workflows/test-database.yml b/.github/workflows/test-database.yml index 0fbdb5d069..4630c18e40 100644 --- a/.github/workflows/test-database.yml +++ b/.github/workflows/test-database.yml @@ -49,7 +49,7 @@ jobs: persist-credentials: false - name: Set up .NET - uses: actions/setup-dotnet@d4c94342e560b34958eacfc5d055d21461ed1c5d # v5.0.0 + uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 - name: Restore tools run: dotnet tool restore @@ -183,7 +183,7 @@ jobs: persist-credentials: false - name: Set up .NET - uses: actions/setup-dotnet@d4c94342e560b34958eacfc5d055d21461ed1c5d # v5.0.0 + uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 - name: Print environment run: | diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 550d943dbc..a6d07bb650 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -32,10 +32,10 @@ jobs: persist-credentials: false - name: Set up .NET - uses: actions/setup-dotnet@d4c94342e560b34958eacfc5d055d21461ed1c5d # v5.0.0 + uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 - name: Install rust - uses: dtolnay/rust-toolchain@b3b07ba8b418998c39fb20f53e8b695cdcc8de1b # stable + uses: dtolnay/rust-toolchain@f7ccc83f9ed1e5b9c81d8a67d7ad1a747e22a561 # stable with: toolchain: stable diff --git a/.vscode/launch.json b/.vscode/launch.json index c407ba5604..74115dcc86 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -69,6 +69,28 @@ "preLaunchTask": "buildFullServer", "stopAll": true }, + { + "name": "Full Server with Seeder API", + "configurations": [ + "run-Admin", + "run-API", + "run-Events", + "run-EventsProcessor", + "run-Identity", + "run-Sso", + "run-Icons", + "run-Billing", + "run-Notifications", + "run-SeederAPI" + ], + "presentation": { + "hidden": false, + "group": "AA_compounds", + "order": 6 + }, + "preLaunchTask": "buildFullServerWithSeederApi", + "stopAll": true + }, { "name": "Self Host: Bit", "configurations": [ @@ -204,6 +226,17 @@ }, "preLaunchTask": "buildSso", }, + { + "name": "Seeder API", + "configurations": [ + "run-SeederAPI" + ], + "presentation": { + "hidden": false, + "group": "cloud", + }, + "preLaunchTask": "buildSeederAPI", + }, { "name": "Admin Self Host", "configurations": [ @@ -270,6 +303,17 @@ }, "preLaunchTask": "buildSso", }, + { + "name": "Seeder API Self Host", + "configurations": [ + "run-SeederAPI-SelfHost" + ], + "presentation": { + "hidden": false, + "group": "self-host", + }, + "preLaunchTask": "buildSeederAPI", + } ], "configurations": [ // Configurations represent run-only scenarios so that they can be used in multiple compounds @@ -311,6 +355,25 @@ "/Views": "${workspaceFolder}/Views" } }, + { + "name": "run-SeederAPI", + "presentation": { + "hidden": true, + }, + "requireExactSource": true, + "type": "coreclr", + "request": "launch", + "program": "${workspaceFolder}/util/SeederApi/bin/Debug/net8.0/SeederApi.dll", + "args": [], + "cwd": "${workspaceFolder}/util/SeederApi", + "stopAtEntry": false, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development", + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, { "name": "run-Billing", "presentation": { @@ -488,6 +551,27 @@ "/Views": "${workspaceFolder}/Views" } }, + { + "name": "run-SeederAPI-SelfHost", + "presentation": { + "hidden": true, + }, + "requireExactSource": true, + "type": "coreclr", + "request": "launch", + "program": "${workspaceFolder}/util/SeederApi/bin/Debug/net8.0/SeederApi.dll", + "args": [], + "cwd": "${workspaceFolder}/util/SeederApi", + "stopAtEntry": false, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development", + "ASPNETCORE_URLS": "http://localhost:5048", + "developSelfHosted": "true", + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, { "name": "run-Admin-SelfHost", "presentation": { diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 567f9b6e58..07a55fdeb3 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -43,6 +43,21 @@ "label": "buildFullServer", "hide": true, "dependsOrder": "sequence", + "dependsOn": [ + "buildAdmin", + "buildAPI", + "buildEventsProcessor", + "buildIdentity", + "buildSso", + "buildIcons", + "buildBilling", + "buildNotifications" + ], + }, + { + "label": "buildFullServerWithSeederApi", + "hide": true, + "dependsOrder": "sequence", "dependsOn": [ "buildAdmin", "buildAPI", @@ -52,6 +67,7 @@ "buildIcons", "buildBilling", "buildNotifications", + "buildSeederAPI" ], }, { @@ -89,6 +105,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile" }, { @@ -102,6 +121,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile" }, { @@ -115,6 +137,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile" }, { @@ -128,6 +153,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile" }, { @@ -141,6 +169,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile" }, { @@ -154,6 +185,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile" }, { @@ -167,6 +201,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile" }, { @@ -180,6 +217,29 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": "$msCompile", + "group": { + "kind": "build", + "isDefault": true + } + }, + { + "label": "buildSeederAPI", + "hide": true, + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/util/SeederApi/SeederApi.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile", "group": { "kind": "build", @@ -197,6 +257,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile", "group": { "kind": "build", @@ -214,6 +277,9 @@ "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary" ], + "options": { + "cwd": "${workspaceFolder}" + }, "problemMatcher": "$msCompile", "group": { "kind": "build", @@ -224,6 +290,9 @@ "label": "test", "type": "shell", "command": "dotnet test", + "options": { + "cwd": "${workspaceFolder}" + }, "group": { "kind": "test", "isDefault": true diff --git a/Directory.Build.props b/Directory.Build.props index db3ccf40f5..e7a8422605 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -3,7 +3,7 @@ net8.0 - 2025.12.2 + 2026.1.0 Bit.$(MSBuildProjectName) enable @@ -13,21 +13,21 @@ true - + - + 18.0.1 - + 2.6.6 - + 2.5.6 - + 6.0.0 - + 5.1.0 - + 4.18.1 - + 4.18.1 \ No newline at end of file diff --git a/bitwarden-server.sln b/bitwarden-server.sln index 6786ad610c..ae9571a4a5 100644 --- a/bitwarden-server.sln +++ b/bitwarden-server.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29102.190 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36705.20 d17.14 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src - AGPL", "src - AGPL", "{DD5BD056-4AAE-43EF-BBD2-0B569B8DA84D}" EndProject @@ -11,19 +11,19 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{DD5BD056-4 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{458155D3-BCBC-481D-B37A-40D2ED10F0A4}" ProjectSection(SolutionItems) = preProject + .dockerignore = .dockerignore + .editorconfig = .editorconfig + .gitignore = .gitignore + CONTRIBUTING.md = CONTRIBUTING.md Directory.Build.props = Directory.Build.props global.json = global.json - .gitignore = .gitignore - README.md = README.md - .editorconfig = .editorconfig - TRADEMARK_GUIDELINES.md = TRADEMARK_GUIDELINES.md - SECURITY.md = SECURITY.md - LICENSE_FAQ.md = LICENSE_FAQ.md - LICENSE_BITWARDEN.txt = LICENSE_BITWARDEN.txt - LICENSE_AGPL.txt = LICENSE_AGPL.txt LICENSE.txt = LICENSE.txt - CONTRIBUTING.md = CONTRIBUTING.md - .dockerignore = .dockerignore + LICENSE_AGPL.txt = LICENSE_AGPL.txt + LICENSE_BITWARDEN.txt = LICENSE_BITWARDEN.txt + LICENSE_FAQ.md = LICENSE_FAQ.md + README.md = README.md + SECURITY.md = SECURITY.md + TRADEMARK_GUIDELINES.md = TRADEMARK_GUIDELINES.md EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core", "src\Core\Core.csproj", "{3973D21B-A692-4B60-9B70-3631C057423A}" @@ -134,10 +134,16 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbSeederUtility", "util\DbSeederUtility\DbSeederUtility.csproj", "{17A89266-260A-4A03-81AE-C0468C6EE06E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RustSdk", "util\RustSdk\RustSdk.csproj", "{D1513D90-E4F5-44A9-9121-5E46E3E4A3F7}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedWeb.Test", "test\SharedWeb.Test\SharedWeb.Test.csproj", "{AD59537D-5259-4B7A-948F-0CF58E80B359}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SeederApi", "util\SeederApi\SeederApi.csproj", "{9F08DFBB-482B-4C9D-A5F4-6BDA6EC2E68F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SeederApi.IntegrationTest", "test\SeederApi.IntegrationTest\SeederApi.IntegrationTest.csproj", "{A2E067EF-609C-4D13-895A-E054C61D48BB}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SSO.Test", "bitwarden_license\test\SSO.Test\SSO.Test.csproj", "{7D98784C-C253-43FB-9873-25B65C6250D6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sso.IntegrationTest", "bitwarden_license\test\Sso.IntegrationTest\Sso.IntegrationTest.csproj", "{FFB09376-595B-6F93-36F0-70CAE90AFECB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -350,10 +356,22 @@ Global {AD59537D-5259-4B7A-948F-0CF58E80B359}.Debug|Any CPU.Build.0 = Debug|Any CPU {AD59537D-5259-4B7A-948F-0CF58E80B359}.Release|Any CPU.ActiveCfg = Release|Any CPU {AD59537D-5259-4B7A-948F-0CF58E80B359}.Release|Any CPU.Build.0 = Release|Any CPU + {9F08DFBB-482B-4C9D-A5F4-6BDA6EC2E68F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9F08DFBB-482B-4C9D-A5F4-6BDA6EC2E68F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9F08DFBB-482B-4C9D-A5F4-6BDA6EC2E68F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9F08DFBB-482B-4C9D-A5F4-6BDA6EC2E68F}.Release|Any CPU.Build.0 = Release|Any CPU + {A2E067EF-609C-4D13-895A-E054C61D48BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A2E067EF-609C-4D13-895A-E054C61D48BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A2E067EF-609C-4D13-895A-E054C61D48BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A2E067EF-609C-4D13-895A-E054C61D48BB}.Release|Any CPU.Build.0 = Release|Any CPU {7D98784C-C253-43FB-9873-25B65C6250D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7D98784C-C253-43FB-9873-25B65C6250D6}.Debug|Any CPU.Build.0 = Debug|Any CPU {7D98784C-C253-43FB-9873-25B65C6250D6}.Release|Any CPU.ActiveCfg = Release|Any CPU {7D98784C-C253-43FB-9873-25B65C6250D6}.Release|Any CPU.Build.0 = Release|Any CPU + {FFB09376-595B-6F93-36F0-70CAE90AFECB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FFB09376-595B-6F93-36F0-70CAE90AFECB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FFB09376-595B-6F93-36F0-70CAE90AFECB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FFB09376-595B-6F93-36F0-70CAE90AFECB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -410,7 +428,10 @@ Global {17A89266-260A-4A03-81AE-C0468C6EE06E} = {DD5BD056-4AAE-43EF-BBD2-0B569B8DA84E} {D1513D90-E4F5-44A9-9121-5E46E3E4A3F7} = {DD5BD056-4AAE-43EF-BBD2-0B569B8DA84E} {AD59537D-5259-4B7A-948F-0CF58E80B359} = {DD5BD056-4AAE-43EF-BBD2-0B569B8DA84F} + {9F08DFBB-482B-4C9D-A5F4-6BDA6EC2E68F} = {DD5BD056-4AAE-43EF-BBD2-0B569B8DA84E} + {A2E067EF-609C-4D13-895A-E054C61D48BB} = {DD5BD056-4AAE-43EF-BBD2-0B569B8DA84F} {7D98784C-C253-43FB-9873-25B65C6250D6} = {287CFF34-BBDB-4BC4-AF88-1E19A5A4679B} + {FFB09376-595B-6F93-36F0-70CAE90AFECB} = {287CFF34-BBDB-4BC4-AF88-1E19A5A4679B} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {E01CBF68-2E20-425F-9EDB-E0A6510CA92F} diff --git a/bitwarden_license/src/Scim/Startup.cs b/bitwarden_license/src/Scim/Startup.cs index 2a84faa8dd..a912562f72 100644 --- a/bitwarden_license/src/Scim/Startup.cs +++ b/bitwarden_license/src/Scim/Startup.cs @@ -44,6 +44,7 @@ public class Startup // Repositories services.AddDatabaseRepositories(globalSettings); + services.AddTestPlayIdTracking(globalSettings); // Context services.AddScoped(); diff --git a/bitwarden_license/src/Sso/Controllers/AccountController.cs b/bitwarden_license/src/Sso/Controllers/AccountController.cs index 7141f8429d..dde2ac7a46 100644 --- a/bitwarden_license/src/Sso/Controllers/AccountController.cs +++ b/bitwarden_license/src/Sso/Controllers/AccountController.cs @@ -462,6 +462,7 @@ public class AccountController : Controller // FIXME: Update this file to be null safe and then delete the line below #nullable disable var provider = result.Properties.Items["scheme"]; + //Todo: Validate provider is a valid GUID with TryParse instead. When this is invalid it throws an exception var orgId = new Guid(provider); var ssoConfig = await _ssoConfigRepository.GetByOrganizationIdAsync(orgId); if (ssoConfig == null || !ssoConfig.Enabled) @@ -615,7 +616,7 @@ public class AccountController : Controller // Since we're in the auto-provisioning logic, this means that the user exists, but they have not // authenticated with the org's SSO provider before now (otherwise we wouldn't be auto-provisioning them). - // We've verified that the user is Accepted or Confnirmed, so we can create an SsoUser link and proceed + // We've verified that the user is Accepted or Confirmed, so we can create an SsoUser link and proceed // with authentication. await CreateSsoUserRecordAsync(providerUserId, guaranteedExistingUser.Id, organization.Id, guaranteedOrgUser); @@ -680,22 +681,10 @@ public class AccountController : Controller ApiKey = CoreHelpers.SecureRandomString(30) }; - /* - The feature flag is checked here so that we can send the new MJML welcome email templates. - The other organization invites flows have an OrganizationUser allowing the RegisterUserCommand the ability - to fetch the Organization. The old method RegisterUser(User) here does not have that context, so we need - to use a new method RegisterSSOAutoProvisionedUserAsync(User, Organization) to send the correct email. - [PM-28057]: Prefer RegisterSSOAutoProvisionedUserAsync for SSO auto-provisioned users. - TODO: Remove Feature flag: PM-28221 - */ - if (_featureService.IsEnabled(FeatureFlagKeys.MjmlWelcomeEmailTemplates)) - { - await _registerUserCommand.RegisterSSOAutoProvisionedUserAsync(newUser, organization); - } - else - { - await _registerUserCommand.RegisterUser(newUser); - } + // Always use RegisterSSOAutoProvisionedUserAsync to ensure organization context is available + // for domain validation (BlockClaimedDomainAccountCreation policy) and welcome emails. + // The feature flag logic for welcome email templates is handled internally by RegisterUserCommand. + await _registerUserCommand.RegisterSSOAutoProvisionedUserAsync(newUser, organization); // If the organization has 2fa policy enabled, make sure to default jit user 2fa to email var twoFactorPolicy = diff --git a/bitwarden_license/src/Sso/IdentityServer/DistributedCachePersistedGrantStore.cs b/bitwarden_license/src/Sso/IdentityServer/DistributedCachePersistedGrantStore.cs new file mode 100644 index 0000000000..ecb2f36cec --- /dev/null +++ b/bitwarden_license/src/Sso/IdentityServer/DistributedCachePersistedGrantStore.cs @@ -0,0 +1,102 @@ +using Bit.Sso.Utilities; +using Duende.IdentityServer.Models; +using Duende.IdentityServer.Stores; +using ZiggyCreatures.Caching.Fusion; + +namespace Bit.Sso.IdentityServer; + +/// +/// Distributed cache-backed persisted grant store for short-lived grants. +/// Uses IFusionCache (which wraps IDistributedCache) for horizontal scaling support, +/// and fall back to in-memory caching if Redis is not configured. +/// Designed for SSO authorization codes which are short-lived (5 minutes) and single-use. +/// +/// +/// This is purposefully a different implementation from how Identity solves Persisted Grants. +/// Because even flavored grant store, e.g., AuthorizationCodeGrantStore, can add intermediary +/// logic to a grant's handling by type, the fact that they all wrap IdentityServer's IPersistedGrantStore +/// leans on IdentityServer's opinion that all grants, regardless of type, go to the same persistence +/// mechanism (cache, database). +/// +/// +public class DistributedCachePersistedGrantStore : IPersistedGrantStore +{ + private readonly IFusionCache _cache; + + public DistributedCachePersistedGrantStore( + [FromKeyedServices(PersistedGrantsDistributedCacheConstants.CacheKey)] IFusionCache cache) + { + _cache = cache; + } + + public async Task GetAsync(string key) + { + var result = await _cache.TryGetAsync(key); + + if (!result.HasValue) + { + return null; + } + + var grant = result.Value; + + // Check if grant has expired - remove expired grants from cache + if (grant.Expiration.HasValue && grant.Expiration.Value < DateTime.UtcNow) + { + await RemoveAsync(key); + return null; + } + + return grant; + } + + public Task> GetAllAsync(PersistedGrantFilter filter) + { + // Cache stores are key-value based and don't support querying by filter criteria. + // This method is typically used for cleanup operations on long-lived grants in databases. + // For SSO's short-lived authorization codes, we rely on TTL expiration instead. + + return Task.FromResult(Enumerable.Empty()); + } + + public Task RemoveAllAsync(PersistedGrantFilter filter) + { + // Revocation Strategy: SSO's logout flow (AccountController.LogoutAsync) only clears local + // authentication cookies and performs federated logout with external IdPs. It does not invoke + // Duende's EndSession or TokenRevocation endpoints. Authorization codes are single-use and expire + // within 5 minutes, making explicit revocation unnecessary for SSO's security model. + // https://docs.duendesoftware.com/identityserver/reference/stores/persisted-grant-store/ + + // Cache stores are key-value based and don't support bulk deletion by filter. + // This method is typically used for cleanup operations on long-lived grants in databases. + // For SSO's short-lived authorization codes, we rely on TTL expiration instead. + + return Task.FromResult(0); + } + + public async Task RemoveAsync(string key) + { + await _cache.RemoveAsync(key); + } + + public async Task StoreAsync(PersistedGrant grant) + { + // Calculate TTL based on grant expiration + var duration = grant.Expiration.HasValue + ? grant.Expiration.Value - DateTime.UtcNow + : TimeSpan.FromMinutes(5); // Default to 5 minutes if no expiration set + + // Ensure positive duration + if (duration <= TimeSpan.Zero) + { + return; + } + + // Cache key "sso-grants:" is configured by service registration. Going through the consumed KeyedService will + // give us a consistent cache key prefix for these grants. + await _cache.SetAsync( + grant.Key, + grant, + new FusionCacheEntryOptions { Duration = duration }); + } +} diff --git a/bitwarden_license/src/Sso/Startup.cs b/bitwarden_license/src/Sso/Startup.cs index 2f83f3dad0..a2f363d533 100644 --- a/bitwarden_license/src/Sso/Startup.cs +++ b/bitwarden_license/src/Sso/Startup.cs @@ -41,6 +41,7 @@ public class Startup // Repositories services.AddDatabaseRepositories(globalSettings); + services.AddTestPlayIdTracking(globalSettings); // Context services.AddScoped(); diff --git a/bitwarden_license/src/Sso/Utilities/PersistedGrantsDistributedCacheConstants.cs b/bitwarden_license/src/Sso/Utilities/PersistedGrantsDistributedCacheConstants.cs new file mode 100644 index 0000000000..3ec45377e3 --- /dev/null +++ b/bitwarden_license/src/Sso/Utilities/PersistedGrantsDistributedCacheConstants.cs @@ -0,0 +1,10 @@ +namespace Bit.Sso.Utilities; + +public static class PersistedGrantsDistributedCacheConstants +{ + /// + /// The SSO Persisted Grant cache key. Identifies the keyed service consumed by the SSO Persisted Grant Store as + /// well as the cache key/namespace for grant storage. + /// + public const string CacheKey = "sso-grants"; +} diff --git a/bitwarden_license/src/Sso/Utilities/ServiceCollectionExtensions.cs b/bitwarden_license/src/Sso/Utilities/ServiceCollectionExtensions.cs index a51a04f5c8..da7a79535e 100644 --- a/bitwarden_license/src/Sso/Utilities/ServiceCollectionExtensions.cs +++ b/bitwarden_license/src/Sso/Utilities/ServiceCollectionExtensions.cs @@ -9,6 +9,7 @@ using Bit.Sso.IdentityServer; using Bit.Sso.Models; using Duende.IdentityServer.Models; using Duende.IdentityServer.ResponseHandling; +using Duende.IdentityServer.Stores; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Sustainsys.Saml2.AspNetCore2; @@ -77,6 +78,17 @@ public static class ServiceCollectionExtensions }) .AddIdentityServerCertificate(env, globalSettings); + // PM-23572 + // Register named FusionCache for SSO authorization code grants. + // Provides separation of concerns and automatic Redis/in-memory negotiation + // .AddInMemoryCaching should still persist above; this handles configuration caching, etc., + // and is separate from this keyed service, which only serves grant negotiation. + services.AddExtendedCache(PersistedGrantsDistributedCacheConstants.CacheKey, globalSettings); + + // Store authorization codes in distributed cache for horizontal scaling + // Uses named FusionCache which gracefully degrades to in-memory when Redis isn't configured + services.AddSingleton(); + return identityServerBuilder; } } diff --git a/bitwarden_license/src/Sso/package-lock.json b/bitwarden_license/src/Sso/package-lock.json index f5e0468f87..efeee7f4ca 100644 --- a/bitwarden_license/src/Sso/package-lock.json +++ b/bitwarden_license/src/Sso/package-lock.json @@ -17,9 +17,9 @@ "css-loader": "7.1.2", "expose-loader": "5.0.1", "mini-css-extract-plugin": "2.9.2", - "sass": "1.93.2", + "sass": "1.97.2", "sass-loader": "16.0.5", - "webpack": "5.102.1", + "webpack": "5.104.1", "webpack-cli": "5.1.4" } }, @@ -749,9 +749,9 @@ } }, "node_modules/baseline-browser-mapping": { - "version": "2.8.18", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.8.18.tgz", - "integrity": "sha512-UYmTpOBwgPScZpS4A+YbapwWuBwasxvO/2IOHArSsAhL/+ZdmATBXTex3t+l2hXwLVYK382ibr/nKoY9GKe86w==", + "version": "2.9.13", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.13.tgz", + "integrity": "sha512-WhtvB2NG2wjr04+h77sg3klAIwrgOqnjS49GGudnUPGFFgg7G17y7Qecqp+2Dr5kUDxNRBca0SK7cG8JwzkWDQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -792,9 +792,9 @@ } }, "node_modules/browserslist": { - "version": "4.26.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.26.3.tgz", - "integrity": "sha512-lAUU+02RFBuCKQPj/P6NgjlbCnLBMp4UtgTx7vNHd3XSIJF87s9a5rA3aH2yw3GS9DqZAUbOtZdCCiZeVRqt0w==", + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", "dev": true, "funding": [ { @@ -813,11 +813,11 @@ "license": "MIT", "peer": true, "dependencies": { - "baseline-browser-mapping": "^2.8.9", - "caniuse-lite": "^1.0.30001746", - "electron-to-chromium": "^1.5.227", - "node-releases": "^2.0.21", - "update-browserslist-db": "^1.1.3" + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" @@ -834,9 +834,9 @@ "license": "MIT" }, "node_modules/caniuse-lite": { - "version": "1.0.30001751", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001751.tgz", - "integrity": "sha512-A0QJhug0Ly64Ii3eIqHu5X51ebln3k4yTUkY1j8drqpWHVreg/VLijN48cZ1bYPiqOQuqpkIKnzr/Ul8V+p6Cw==", + "version": "1.0.30001763", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001763.tgz", + "integrity": "sha512-mh/dGtq56uN98LlNX9qdbKnzINhX0QzhiWBFEkFfsFO4QyCvL8YegrJAazCwXIeqkIob8BlZPGM3xdnY+sgmvQ==", "dev": true, "funding": [ { @@ -988,9 +988,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.237", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.237.tgz", - "integrity": "sha512-icUt1NvfhGLar5lSWH3tHNzablaA5js3HVHacQimfP8ViEBOQv+L7DKEuHdbTZ0SKCO1ogTJTIL1Gwk9S6Qvcg==", + "version": "1.5.267", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", + "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", "dev": true, "license": "ISC" }, @@ -1022,9 +1022,9 @@ } }, "node_modules/es-module-lexer": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", - "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", + "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", "dev": true, "license": "MIT" }, @@ -1418,13 +1418,17 @@ } }, "node_modules/loader-runner": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", - "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.1.tgz", + "integrity": "sha512-IWqP2SCPhyVFTBtRcgMHdzlf9ul25NwaFx4wCEH/KjAXuuHY4yNjvPXsBokp8jCB936PyWRaPKUNh8NvylLp2Q==", "dev": true, "license": "MIT", "engines": { "node": ">=6.11.5" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" } }, "node_modules/locate-path": { @@ -1541,9 +1545,9 @@ "optional": true }, "node_modules/node-releases": { - "version": "2.0.26", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.26.tgz", - "integrity": "sha512-S2M9YimhSjBSvYnlr5/+umAnPHE++ODwt5e2Ij6FoX45HA/s4vHdkDx1eax2pAPeAOqu4s9b7ppahsyEFdVqQA==", + "version": "2.0.27", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", + "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", "dev": true, "license": "MIT" }, @@ -1874,9 +1878,9 @@ "license": "MIT" }, "node_modules/sass": { - "version": "1.93.2", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.93.2.tgz", - "integrity": "sha512-t+YPtOQHpGW1QWsh1CHQ5cPIr9lbbGZLZnbihP/D/qZj/yuV68m8qarcV17nvkOX81BCrvzAlq2klCQFZghyTg==", + "version": "1.97.2", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.97.2.tgz", + "integrity": "sha512-y5LWb0IlbO4e97Zr7c3mlpabcbBtS+ieiZ9iwDooShpFKWXf62zz5pEPdwrLYm+Bxn1fnbwFGzHuCLSA9tBmrw==", "dev": true, "license": "MIT", "peer": true, @@ -2109,9 +2113,9 @@ } }, "node_modules/terser-webpack-plugin": { - "version": "5.3.14", - "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.14.tgz", - "integrity": "sha512-vkZjpUjb6OMS7dhV+tILUW6BhpDR7P2L/aQSAv+Uwk+m8KATX9EccViHTJR2qDtACKPIYndLGCyl3FMo+r2LMw==", + "version": "5.3.16", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.16.tgz", + "integrity": "sha512-h9oBFCWrq78NyWWVcSwZarJkZ01c2AyGrzs1crmHZO3QUg9D61Wu4NPjBy69n7JqylFF5y+CsUZYmYEIZ3mR+Q==", "dev": true, "license": "MIT", "dependencies": { @@ -2165,9 +2169,9 @@ "license": "MIT" }, "node_modules/update-browserslist-db": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz", - "integrity": "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", "dev": true, "funding": [ { @@ -2217,9 +2221,9 @@ } }, "node_modules/webpack": { - "version": "5.102.1", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.102.1.tgz", - "integrity": "sha512-7h/weGm9d/ywQ6qzJ+Xy+r9n/3qgp/thalBbpOi5i223dPXKi04IBtqPN9nTd+jBc7QKfvDbaBnFipYp4sJAUQ==", + "version": "5.104.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.104.1.tgz", + "integrity": "sha512-Qphch25abbMNtekmEGJmeRUhLDbe+QfiWTiqpKYkpCOWY64v9eyl+KRRLmqOFA2AvKPpc9DC6+u2n76tQLBoaA==", "dev": true, "license": "MIT", "peer": true, @@ -2232,21 +2236,21 @@ "@webassemblyjs/wasm-parser": "^1.14.1", "acorn": "^8.15.0", "acorn-import-phases": "^1.0.3", - "browserslist": "^4.26.3", + "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.17.3", - "es-module-lexer": "^1.2.1", + "enhanced-resolve": "^5.17.4", + "es-module-lexer": "^2.0.0", "eslint-scope": "5.1.1", "events": "^3.2.0", "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.2.11", "json-parse-even-better-errors": "^2.3.1", - "loader-runner": "^4.2.0", + "loader-runner": "^4.3.1", "mime-types": "^2.1.27", "neo-async": "^2.6.2", "schema-utils": "^4.3.3", "tapable": "^2.3.0", - "terser-webpack-plugin": "^5.3.11", + "terser-webpack-plugin": "^5.3.16", "watchpack": "^2.4.4", "webpack-sources": "^3.3.3" }, diff --git a/bitwarden_license/src/Sso/package.json b/bitwarden_license/src/Sso/package.json index df46444aca..b0a1849421 100644 --- a/bitwarden_license/src/Sso/package.json +++ b/bitwarden_license/src/Sso/package.json @@ -16,9 +16,9 @@ "css-loader": "7.1.2", "expose-loader": "5.0.1", "mini-css-extract-plugin": "2.9.2", - "sass": "1.93.2", + "sass": "1.97.2", "sass-loader": "16.0.5", - "webpack": "5.102.1", + "webpack": "5.104.1", "webpack-cli": "5.1.4" } } diff --git a/bitwarden_license/test/SSO.Test/Controllers/AccountControllerTest.cs b/bitwarden_license/test/SSO.Test/Controllers/AccountControllerTest.cs index b276174814..66cb018923 100644 --- a/bitwarden_license/test/SSO.Test/Controllers/AccountControllerTest.cs +++ b/bitwarden_license/test/SSO.Test/Controllers/AccountControllerTest.cs @@ -6,7 +6,6 @@ using Bit.Core.Auth.Entities; using Bit.Core.Auth.Models.Business.Tokenables; using Bit.Core.Auth.Models.Data; using Bit.Core.Auth.Repositories; -using Bit.Core.Auth.UserFeatures.Registration; using Bit.Core.Entities; using Bit.Core.Enums; using Bit.Core.Repositories; @@ -21,7 +20,6 @@ using Duende.IdentityServer.Models; using Duende.IdentityServer.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using NSubstitute; @@ -1013,133 +1011,6 @@ public class AccountControllerTest } } - [Theory, BitAutoData] - public async Task AutoProvisionUserAsync_WithFeatureFlagEnabled_CallsRegisterSSOAutoProvisionedUser( - SutProvider sutProvider) - { - // Arrange - var orgId = Guid.NewGuid(); - var providerUserId = "ext-new-user"; - var email = "newuser@example.com"; - var organization = new Organization { Id = orgId, Name = "Test Org", Seats = null }; - - // No existing user (JIT provisioning scenario) - sutProvider.GetDependency().GetByEmailAsync(email).Returns((User?)null); - sutProvider.GetDependency().GetByIdAsync(orgId).Returns(organization); - sutProvider.GetDependency().GetByOrganizationEmailAsync(orgId, email) - .Returns((OrganizationUser?)null); - - // Feature flag enabled - sutProvider.GetDependency() - .IsEnabled(FeatureFlagKeys.MjmlWelcomeEmailTemplates) - .Returns(true); - - // Mock the RegisterSSOAutoProvisionedUserAsync to return success - sutProvider.GetDependency() - .RegisterSSOAutoProvisionedUserAsync(Arg.Any(), Arg.Any()) - .Returns(IdentityResult.Success); - - var claims = new[] - { - new Claim(JwtClaimTypes.Email, email), - new Claim(JwtClaimTypes.Name, "New User") - } as IEnumerable; - var config = new SsoConfigurationData(); - - var method = typeof(AccountController).GetMethod( - "CreateUserAndOrgUserConditionallyAsync", - BindingFlags.Instance | BindingFlags.NonPublic); - Assert.NotNull(method); - - // Act - var task = (Task<(User user, Organization organization, OrganizationUser orgUser)>)method!.Invoke( - sutProvider.Sut, - new object[] - { - orgId.ToString(), - providerUserId, - claims, - null!, - config - })!; - - var result = await task; - - // Assert - await sutProvider.GetDependency().Received(1) - .RegisterSSOAutoProvisionedUserAsync( - Arg.Is(u => u.Email == email && u.Name == "New User"), - Arg.Is(o => o.Id == orgId && o.Name == "Test Org")); - - Assert.NotNull(result.user); - Assert.Equal(email, result.user.Email); - Assert.Equal(organization.Id, result.organization.Id); - } - - [Theory, BitAutoData] - public async Task AutoProvisionUserAsync_WithFeatureFlagDisabled_CallsRegisterUserInstead( - SutProvider sutProvider) - { - // Arrange - var orgId = Guid.NewGuid(); - var providerUserId = "ext-legacy-user"; - var email = "legacyuser@example.com"; - var organization = new Organization { Id = orgId, Name = "Test Org", Seats = null }; - - // No existing user (JIT provisioning scenario) - sutProvider.GetDependency().GetByEmailAsync(email).Returns((User?)null); - sutProvider.GetDependency().GetByIdAsync(orgId).Returns(organization); - sutProvider.GetDependency().GetByOrganizationEmailAsync(orgId, email) - .Returns((OrganizationUser?)null); - - // Feature flag disabled - sutProvider.GetDependency() - .IsEnabled(FeatureFlagKeys.MjmlWelcomeEmailTemplates) - .Returns(false); - - // Mock the RegisterUser to return success - sutProvider.GetDependency() - .RegisterUser(Arg.Any()) - .Returns(IdentityResult.Success); - - var claims = new[] - { - new Claim(JwtClaimTypes.Email, email), - new Claim(JwtClaimTypes.Name, "Legacy User") - } as IEnumerable; - var config = new SsoConfigurationData(); - - var method = typeof(AccountController).GetMethod( - "CreateUserAndOrgUserConditionallyAsync", - BindingFlags.Instance | BindingFlags.NonPublic); - Assert.NotNull(method); - - // Act - var task = (Task<(User user, Organization organization, OrganizationUser orgUser)>)method!.Invoke( - sutProvider.Sut, - new object[] - { - orgId.ToString(), - providerUserId, - claims, - null!, - config - })!; - - var result = await task; - - // Assert - await sutProvider.GetDependency().Received(1) - .RegisterUser(Arg.Is(u => u.Email == email && u.Name == "Legacy User")); - - // Verify the new method was NOT called - await sutProvider.GetDependency().DidNotReceive() - .RegisterSSOAutoProvisionedUserAsync(Arg.Any(), Arg.Any()); - - Assert.NotNull(result.user); - Assert.Equal(email, result.user.Email); - } - [Theory, BitAutoData] public void ExternalChallenge_WithMatchingOrgId_Succeeds( SutProvider sutProvider, diff --git a/bitwarden_license/test/SSO.Test/IdentityServer/DistributedCachePersistedGrantStoreTests.cs b/bitwarden_license/test/SSO.Test/IdentityServer/DistributedCachePersistedGrantStoreTests.cs new file mode 100644 index 0000000000..c0aa93f068 --- /dev/null +++ b/bitwarden_license/test/SSO.Test/IdentityServer/DistributedCachePersistedGrantStoreTests.cs @@ -0,0 +1,257 @@ +using Bit.Sso.IdentityServer; +using Duende.IdentityServer.Models; +using Duende.IdentityServer.Stores; +using NSubstitute; +using ZiggyCreatures.Caching.Fusion; + +namespace Bit.SSO.Test.IdentityServer; + +public class DistributedCachePersistedGrantStoreTests +{ + private readonly IFusionCache _cache; + private readonly DistributedCachePersistedGrantStore _sut; + + public DistributedCachePersistedGrantStoreTests() + { + _cache = Substitute.For(); + _sut = new DistributedCachePersistedGrantStore(_cache); + } + + [Fact] + public async Task StoreAsync_StoresGrantWithCalculatedTTL() + { + // Arrange + var grant = CreateTestGrant("test-key", expiration: DateTime.UtcNow.AddMinutes(5)); + + // Act + await _sut.StoreAsync(grant); + + // Assert + await _cache.Received(1).SetAsync( + "test-key", + grant, + Arg.Is(opts => + opts.Duration >= TimeSpan.FromMinutes(4.9) && + opts.Duration <= TimeSpan.FromMinutes(5))); + } + + [Fact] + public async Task StoreAsync_WithNoExpiration_UsesDefaultFiveMinuteTTL() + { + // Arrange + var grant = CreateTestGrant("no-expiry-key", expiration: null); + + // Act + await _sut.StoreAsync(grant); + + // Assert + await _cache.Received(1).SetAsync( + "no-expiry-key", + grant, + Arg.Is(opts => opts.Duration == TimeSpan.FromMinutes(5))); + } + + [Fact] + public async Task StoreAsync_WithAlreadyExpiredGrant_DoesNotStore() + { + // Arrange + var expiredGrant = CreateTestGrant("expired-key", expiration: DateTime.UtcNow.AddMinutes(-1)); + + // Act + await _sut.StoreAsync(expiredGrant); + + // Assert + await _cache.DidNotReceive().SetAsync( + Arg.Any(), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task StoreAsync_EnablesDistributedCache() + { + // Arrange + var grant = CreateTestGrant("distributed-key", expiration: DateTime.UtcNow.AddMinutes(5)); + + // Act + await _sut.StoreAsync(grant); + + // Assert + await _cache.Received(1).SetAsync( + "distributed-key", + grant, + Arg.Is(opts => + opts.SkipDistributedCache == false && + opts.SkipDistributedCacheReadWhenStale == false)); + } + + [Fact] + public async Task GetAsync_WithValidGrant_ReturnsGrant() + { + // Arrange + var grant = CreateTestGrant("valid-key", expiration: DateTime.UtcNow.AddMinutes(5)); + _cache.TryGetAsync("valid-key") + .Returns(MaybeValue.FromValue(grant)); + + // Act + var result = await _sut.GetAsync("valid-key"); + + // Assert + Assert.NotNull(result); + Assert.Equal("valid-key", result.Key); + Assert.Equal("authorization_code", result.Type); + Assert.Equal("test-subject", result.SubjectId); + await _cache.DidNotReceive().RemoveAsync(Arg.Any()); + } + + [Fact] + public async Task GetAsync_WithNonExistentKey_ReturnsNull() + { + // Arrange + _cache.TryGetAsync("nonexistent-key") + .Returns(MaybeValue.None); + + // Act + var result = await _sut.GetAsync("nonexistent-key"); + + // Assert + Assert.Null(result); + await _cache.DidNotReceive().RemoveAsync(Arg.Any()); + } + + [Fact] + public async Task GetAsync_WithExpiredGrant_RemovesAndReturnsNull() + { + // Arrange + var expiredGrant = CreateTestGrant("expired-key", expiration: DateTime.UtcNow.AddMinutes(-1)); + _cache.TryGetAsync("expired-key") + .Returns(MaybeValue.FromValue(expiredGrant)); + + // Act + var result = await _sut.GetAsync("expired-key"); + + // Assert + Assert.Null(result); + await _cache.Received(1).RemoveAsync("expired-key"); + } + + [Fact] + public async Task GetAsync_WithNoExpiration_ReturnsGrant() + { + // Arrange + var grant = CreateTestGrant("no-expiry-key", expiration: null); + _cache.TryGetAsync("no-expiry-key") + .Returns(MaybeValue.FromValue(grant)); + + // Act + var result = await _sut.GetAsync("no-expiry-key"); + + // Assert + Assert.NotNull(result); + Assert.Equal("no-expiry-key", result.Key); + Assert.Null(result.Expiration); + await _cache.DidNotReceive().RemoveAsync(Arg.Any()); + } + + [Fact] + public async Task RemoveAsync_RemovesGrantFromCache() + { + // Act + await _sut.RemoveAsync("remove-key"); + + // Assert + await _cache.Received(1).RemoveAsync("remove-key"); + } + + [Fact] + public async Task GetAllAsync_ReturnsEmptyCollection() + { + // Arrange + var filter = new PersistedGrantFilter + { + SubjectId = "test-subject", + SessionId = "test-session", + ClientId = "test-client", + Type = "authorization_code" + }; + + // Act + var result = await _sut.GetAllAsync(filter); + + // Assert + Assert.NotNull(result); + Assert.Empty(result); + } + + [Fact] + public async Task RemoveAllAsync_CompletesWithoutError() + { + // Arrange + var filter = new PersistedGrantFilter + { + SubjectId = "test-subject", + ClientId = "test-client" + }; + + // Act & Assert - should not throw + await _sut.RemoveAllAsync(filter); + + // Verify no cache operations were performed + await _cache.DidNotReceive().RemoveAsync(Arg.Any()); + } + + [Fact] + public async Task StoreAsync_PreservesAllGrantProperties() + { + // Arrange + var grant = new PersistedGrant + { + Key = "full-grant-key", + Type = "authorization_code", + SubjectId = "user-123", + SessionId = "session-456", + ClientId = "client-789", + Description = "Test grant", + CreationTime = DateTime.UtcNow.AddMinutes(-1), + Expiration = DateTime.UtcNow.AddMinutes(5), + ConsumedTime = null, + Data = "{\"test\":\"data\"}" + }; + + PersistedGrant? capturedGrant = null; + await _cache.SetAsync( + Arg.Any(), + Arg.Do(g => capturedGrant = g), + Arg.Any()); + + // Act + await _sut.StoreAsync(grant); + + // Assert + Assert.NotNull(capturedGrant); + Assert.Equal(grant.Key, capturedGrant.Key); + Assert.Equal(grant.Type, capturedGrant.Type); + Assert.Equal(grant.SubjectId, capturedGrant.SubjectId); + Assert.Equal(grant.SessionId, capturedGrant.SessionId); + Assert.Equal(grant.ClientId, capturedGrant.ClientId); + Assert.Equal(grant.Description, capturedGrant.Description); + Assert.Equal(grant.CreationTime, capturedGrant.CreationTime); + Assert.Equal(grant.Expiration, capturedGrant.Expiration); + Assert.Equal(grant.ConsumedTime, capturedGrant.ConsumedTime); + Assert.Equal(grant.Data, capturedGrant.Data); + } + + private static PersistedGrant CreateTestGrant(string key, DateTime? expiration) + { + return new PersistedGrant + { + Key = key, + Type = "authorization_code", + SubjectId = "test-subject", + ClientId = "test-client", + CreationTime = DateTime.UtcNow, + Expiration = expiration, + Data = "{\"test\":\"data\"}" + }; + } +} diff --git a/bitwarden_license/test/Scim.IntegrationTest/Scim.IntegrationTest.csproj b/bitwarden_license/test/Scim.IntegrationTest/Scim.IntegrationTest.csproj index 4fc79f2025..d0d329397c 100644 --- a/bitwarden_license/test/Scim.IntegrationTest/Scim.IntegrationTest.csproj +++ b/bitwarden_license/test/Scim.IntegrationTest/Scim.IntegrationTest.csproj @@ -1,35 +1,37 @@ - - - - false - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - - - - - - true - PreserveNewest - Never - - - + + + + false + + $(WarningsNotAsErrors);CA1305 + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + true + PreserveNewest + Never + + + diff --git a/bitwarden_license/test/Sso.IntegrationTest/Controllers/AccountControllerTests.cs b/bitwarden_license/test/Sso.IntegrationTest/Controllers/AccountControllerTests.cs new file mode 100644 index 0000000000..7a1c9f9628 --- /dev/null +++ b/bitwarden_license/test/Sso.IntegrationTest/Controllers/AccountControllerTests.cs @@ -0,0 +1,952 @@ +using System.Net; +using Bit.Core; +using Bit.Core.AdminConsole.Entities; +using Bit.Core.Auth.Entities; +using Bit.Core.Auth.Models.Data; +using Bit.Core.Auth.Repositories; +using Bit.Core.Entities; +using Bit.Core.Enums; +using Bit.Core.Repositories; +using Bit.Core.Services; +using Bit.Sso.IntegrationTest.Utilities; +using Bit.Test.Common.AutoFixture.Attributes; +using Bitwarden.License.Test.Sso.IntegrationTest.Utilities; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc.Testing; +using NSubstitute; +using Xunit; +using AuthenticationSchemes = Bit.Core.AuthenticationSchemes; + +namespace Bit.Sso.IntegrationTest.Controllers; + +public class AccountControllerTests(SsoApplicationFactory factory) : IClassFixture +{ + private readonly SsoApplicationFactory _factory = factory; + + /* + * Test to verify the /Account/ExternalCallback endpoint exists and is reachable. + */ + [Fact] + public async Task ExternalCallback_EndpointExists_ReturnsExpectedStatusCode() + { + // Arrange + var client = _factory.CreateClient(); + + // Act - Verify the endpoint is accessible (even if it fails due to missing auth) + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - The endpoint should exist and return 500 (not 404) due to missing authentication + Assert.NotEqual(HttpStatusCode.NotFound, response.StatusCode); + } + + /* + * Test to verify calling /Account/ExternalCallback without an authentication cookie + * results in an error as expected. + */ + [Fact] + public async Task ExternalCallback_WithNoAuthenticationCookie_ReturnsError() + { + // Arrange + var client = _factory.CreateClient(); + + // Act - Call ExternalCallback without proper authentication setup + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because there's no external authentication cookie + Assert.False(response.IsSuccessStatusCode); + // The endpoint will throw an exception when authentication fails + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify behavior of /Account/ExternalCallback with PM24579 feature flag + */ + [Theory] + [BitAutoData(true)] + [BitAutoData(false)] + public async Task ExternalCallback_WithPM24579FeatureFlag_AndNoAuthCookie_ReturnsError + ( + bool featureFlagEnabled + ) + { + // Arrange + var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + var featureService = Substitute.For(); + featureService.IsEnabled(FeatureFlagKeys.PM24579_PreventSsoOnExistingNonCompliantUsers).Returns(featureFlagEnabled); + services.AddSingleton(featureService); + }); + }).CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert + Assert.False(response.IsSuccessStatusCode); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify behavior of /Account/ExternalCallback simulating failed authentication. + */ + [Fact] + public async Task ExternalCallback_WithMockedAuthenticationService_FailedAuth_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithFailedAuthentication() + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert + Assert.False(response.IsSuccessStatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when SSO config exists but is disabled. + */ + [Fact] + public async Task ExternalCallback_WithDisabledSsoConfig_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig(ssoConfig => ssoConfig!.Enabled = false) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because SSO config is disabled + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Organization not found or SSO configuration not enabled", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + [Fact] + public async Task ExternalCallback_FindUserFromExternalProviderAsync_OrganizationOrSsoConfigNotFound_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because user has invalid status + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Organization not found or SSO configuration not enabled", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when SSO config expects an ACR value + * but the authentication response has a missing or invalid ACR claim. + */ + [Fact] + public async Task ExternalCallback_WithExpectedAcrValue_AndInvalidAcr_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig(ssoConfig => ssoConfig!.SetData( + new SsoConfigurationData + { + ExpectedReturnAcrValue = "urn:expected:acr:value" + })) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because ACR claim is missing or invalid + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Expected authentication context class reference (acr) was not returned with the authentication response or is invalid", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when the authentication response + * does not contain any recognizable user ID claim (sub, NameIdentifier, uid, upn, eppn). + */ + [Fact] + public async Task ExternalCallback_WithNoUserIdClaim_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .OmitProviderUserId() + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); ; + + // Assert - Should fail because no user ID claim was found + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Unknown userid", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when no email claim is found + * and the providerUserId cannot be used as a fallback email (doesn't contain @). + */ + [Fact] + public async Task ExternalCallback_WithNoEmailClaim_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithNullEmail() + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because no email claim was found + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Cannot find email claim", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when an existing user + * uses Key Connector but has no org user record (was removed from organization). + */ + [Fact] + public async Task ExternalCallback_WithExistingKeyConnectorUser_AndNoOrgUser_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser(user => + { + user.UsesKeyConnector = true; + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because user uses Key Connector but has no org user record + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("You were removed from the organization managing single sign-on for your account", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when an existing user + * uses Key Connector and has an org user record in the invited status. + */ + [Fact] + public async Task ExternalCallback_WithExistingKeyConnectorUser_AndInvitedOrgUser_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig(ssoConfig => { }) + .WithUser(user => + { + user.UsesKeyConnector = true; + }) + .WithOrganizationUser(orgUser => + { + orgUser.Status = OrganizationUserStatusType.Invited; + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because user uses Key Connector but the Org user is in the invited status + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("You were removed from the organization managing single sign-on for your account", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when an existing user + * (not using Key Connector) has no org user record - they were removed from the organization. + */ + [Fact] + public async Task ExternalCallback_WithExistingUser_AndNoOrgUser_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because user exists but has no org user record + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("You were removed from the organization managing single sign-on for your account. Contact the organization administrator", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when an existing user + * has an org user record with Invited status - they must accept the invite first. + */ + [Fact] + public async Task ExternalCallback_WithExistingUser_AndInvitedOrgUserStatus_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser(orgUser => + { + orgUser.Status = OrganizationUserStatusType.Invited; + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because user must accept invite before using SSO + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("you must first log in using your master password", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when organization has no available seats + * and cannot auto-scale because it's a self-hosted instance. + */ + [Fact] + public async Task ExternalCallback_WithNoAvailableSeats_OnSelfHosted_ReturnsError() + { + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithOrganization(org => + { + org.Seats = 5; // Organization has seat limit + }) + .AsSelfHosted() + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because no seats available and cannot auto-scale on self-hosted + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("No seats available for organization", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when organization has no available seats + * and auto-scaling fails (e.g., billing issue, max seats reached). + */ + [Fact] + public async Task ExternalCallback_WithNoAvailableSeats_AndAutoAddSeatsFails_ReturnsError() + { + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithOrganization(org => + { + org.Seats = 5; + org.MaxAutoscaleSeats = 5; + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because auto-adding seats failed + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("No seats available for organization", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when email cannot be found + * during new user provisioning (Scenario 2) after bypassing the first email check + * via manual linking path (userIdentifier is set). + */ + [Fact] + public async Task ExternalCallback_WithUserIdentifier_AndNoEmail_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUserIdentifier("") + .WithNullEmail() + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because email cannot be found during new user provisioning + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Cannot find email claim", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when org user has an unknown/invalid status. + * This tests defensive code that handles future enum values or data corruption scenarios. + * We simulate this by casting an invalid integer to OrganizationUserStatusType. + */ + [Fact] + public async Task ExternalCallback_WithUnknownOrgUserStatus_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser(orgUser => + { + orgUser.Status = (OrganizationUserStatusType)99; // Invalid enum value - simulates future status or data corruption + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because org user status is unknown/invalid + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("is in an unknown state", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + // Note: "User should be found ln 304" appears to be unreachable defensive code. + // CreateUserAndOrgUserConditionallyAsync always returns a non-null user or throws an exception, + // so possibleSsoLinkedUser cannot be null when the feature flag check executes. + + /* + * Test to verify /Account/ExternalCallback returns error when userIdentifier + * is malformed (doesn't contain comma separator for userId,token format). + * There is only a single test case here but in the future we may need to expand the + * tests to cover other invalid formats. + */ + [Theory] + [BitAutoData("No-Comas-Identifier")] + public async Task ExternalCallback_WithInvalidUserIdentifierFormat_ReturnsError( + string UserIdentifier + ) + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUserIdentifier(UserIdentifier) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because userIdentifier format is invalid + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Invalid user identifier", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when userIdentifier + * contains valid userId but invalid/mismatched token. + * + * NOTE: This test uses the substitute pattern instead of SsoTestDataBuilder because: + * - The userIdentifier in the auth result must contain a userId that matches a user in the system + * - User.SetNewId() always overwrites the Id (unlike Organization.SetNewId() which has a guard) + * - This means we cannot pre-set a User.Id before database insertion + * - The auth mock must be configured BEFORE accessing factory.Services (required by SubstituteService) + * - Therefore, we cannot coordinate the userId between the auth mock and the seeded user + * - Using substitutes allows us to control the exact userId and mock UserManager.VerifyUserTokenAsync + */ + [Fact] + public async Task ExternalCallback_WithUserIdentifier_AndInvalidToken_ReturnsError() + { + // Arrange + var organizationId = Guid.NewGuid(); + var providerUserId = Guid.NewGuid().ToString(); + var userId = Guid.NewGuid(); + var testEmail = "test_user@integration.test"; + var testName = "Test User"; + // Valid format but token won't verify + var userIdentifier = $"{userId},invalid-token"; + + var claimedUser = new User + { + Id = userId, + Email = testEmail, + Name = testName + }; + + var organization = new Organization + { + Id = organizationId, + Name = "Test Organization", + Enabled = true, + UseSso = true + }; + + var ssoConfig = new SsoConfig + { + OrganizationId = organizationId, + Enabled = true + }; + ssoConfig.SetData(new SsoConfigurationData()); + + var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + var featureService = Substitute.For(); + featureService.IsEnabled(FeatureFlagKeys.PM24579_PreventSsoOnExistingNonCompliantUsers).Returns(true); + services.AddSingleton(featureService); + + // Mock organization repository + var orgRepo = Substitute.For(); + orgRepo.GetByIdAsync(organizationId).Returns(organization); + orgRepo.GetByIdentifierAsync(organizationId.ToString()).Returns(organization); + services.AddSingleton(orgRepo); + + // Mock SSO config repository + var ssoConfigRepo = Substitute.For(); + ssoConfigRepo.GetByOrganizationIdAsync(organizationId).Returns(ssoConfig); + services.AddSingleton(ssoConfigRepo); + + // Mock user repository - no existing user via SSO + var userRepo = Substitute.For(); + userRepo.GetBySsoUserAsync(providerUserId, organizationId).Returns((User?)null); + services.AddSingleton(userRepo); + + // Mock user service - returns user for manual linking lookup + var userService = Substitute.For(); + userService.GetUserByIdAsync(userId.ToString()).Returns(claimedUser); + services.AddSingleton(userService); + + // Mock UserManager to return false for token verification + var userManager = Substitute.For>( + Substitute.For>(), null, null, null, null, null, null, null, null); + userManager.VerifyUserTokenAsync( + claimedUser, + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(false); + services.AddSingleton(userManager); + + // Mock authentication service with userIdentifier that has valid format but invalid token + var authService = Substitute.For(); + authService.AuthenticateAsync( + Arg.Any(), + AuthenticationSchemes.BitwardenExternalCookieAuthenticationScheme) + .Returns(MockSuccessfulAuthResult.Build(organizationId, providerUserId, testEmail, testName, null, userIdentifier)); + services.AddSingleton(authService); + }); + }).CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because token verification failed + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Supplied userId and token did not match", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error for revoked org user when PM24579 feature flag is enabled. + */ + [Fact] + public async Task ExternalCallback_WithRevokedOrgUser_WithPM24579FeatureFlagEnabled_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser(orgUser => + { + orgUser.Status = OrganizationUserStatusType.Revoked; + }) + .WithFeatureFlags(factoryService => + { + factoryService.SubstituteService(srv => + { + srv.IsEnabled(FeatureFlagKeys.PM24579_PreventSsoOnExistingNonCompliantUsers).Returns(true); + }); + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because user state is invalid + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains( + $"Your access to organization {testData.Organization?.DisplayName()} has been revoked. Please contact your administrator for assistance.", + stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error for revoked org user when PM24579 feature flag is disabled. + */ + [Fact] + public async Task ExternalCallback_WithRevokedOrgUserStatus_WithPM24579FeatureFlagDisabled_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser(orgUser => + { + orgUser.Status = OrganizationUserStatusType.Revoked; + }) + .WithFeatureFlags(factoryService => + { + factoryService.SubstituteService(srv => + { + srv.IsEnabled(FeatureFlagKeys.PM24579_PreventSsoOnExistingNonCompliantUsers).Returns(false); + }); + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because user has invalid status + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains( + $"Your access to organization {testData.Organization?.DisplayName()} has been revoked. Please contact your administrator for assistance.", + stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error for invited org user when PM24579 feature flag is disabled. + */ + [Fact] + public async Task ExternalCallback_WithInvitedOrgUserStatus_WithPM24579FeatureFlagDisabled_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser(orgUser => + { + orgUser.Status = OrganizationUserStatusType.Invited; + }) + .WithFeatureFlags(factoryService => + { + factoryService.SubstituteService(srv => + { + srv.IsEnabled(FeatureFlagKeys.PM24579_PreventSsoOnExistingNonCompliantUsers).Returns(false); + }); + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because user has invalid status + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains( + $"To accept your invite to {testData.Organization?.DisplayName()}, you must first log in using your master password. Once your invite has been accepted, you will be able to log in using SSO.", + stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + + /* + * Test to verify /Account/ExternalCallback returns error when user is found via SSO + * but has no organization user record (with feature flag enabled). + */ + [Fact] + public async Task ExternalCallback_WithSsoUser_AndNoOrgUser_WithFeatureFlagEnabled_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithSsoUser() + .WithFeatureFlags(factoryService => + { + factoryService.SubstituteService(srv => + { + srv.IsEnabled(FeatureFlagKeys.PM24579_PreventSsoOnExistingNonCompliantUsers).Returns(true); + }); + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because org user cannot be found + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Could not find organization user", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when the provider scheme + * is not a valid GUID (SSOProviderIsNotAnOrgId). + * + * NOTE: This test uses the substitute pattern instead of SsoTestDataBuilder because: + * - Organization.Id is of type Guid and cannot be set to a non-GUID value + * - The auth mock scheme must be a non-GUID string to trigger this error path + * - This cannot be tested since ln 438 in AccountController.FindUserFromExternalProviderAsync throws a different exception + * before reaching the organization lookup exception. + */ + [Fact(Skip = "This test cannot be executed because the organization ID must be a GUID. See note in test summary.")] + public async Task ExternalCallback_WithInvalidProviderGuid_ReturnsError() + { + // Arrange + var invalidScheme = "not-a-valid-guid"; + var providerUserId = Guid.NewGuid().ToString(); + var testEmail = "test@example.com"; + var testName = "Test User"; + + var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + // Mock authentication service with invalid (non-GUID) scheme + var authService = Substitute.For(); + authService.AuthenticateAsync( + Arg.Any(), + AuthenticationSchemes.BitwardenExternalCookieAuthenticationScheme) + .Returns(MockSuccessfulAuthResult.Build(invalidScheme, providerUserId, testEmail, testName)); + services.AddSingleton(authService); + }); + }).CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because provider is not a valid organization GUID + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Organization not found from identifier.", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * Test to verify /Account/ExternalCallback returns error when the organization ID + * in the auth result does not match any organization in the database. + * NOTE: This code path is unreachable because the SsoConfig must exist to proceed, but there is a circular dependency: + * - SsoConfig cannot exist without a valid Organization but the test is testing that an Organization cannot be found. + */ + [Fact(Skip = "This code path is unreachable because the SsoConfig must exist to proceed. But the SsoConfig cannot exist without a valid Organization.")] + public async Task ExternalCallback_WithNonExistentOrganization_ReturnsError() + { + // Arrange + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithNonExistentOrganizationInAuth() + .BuildAsync(); + + var client = testData.Factory.CreateClient(); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should fail because organization cannot be found by the ID in auth result + var stringResponse = await response.Content.ReadAsStringAsync(); + Assert.Contains("Could not find organization", stringResponse); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + /* + * SUCCESS PATH: Test to verify /Account/ExternalCallback succeeds when an existing + * SSO-linked user logs in (user exists in SsoUser table). + */ + [Fact] + public async Task ExternalCallback_WithExistingSsoUser_ReturnsSuccess() + { + // Arrange - User with SSO link already exists + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser() + .WithSsoUser() + .BuildAsync(); + + var client = testData.Factory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false // Prevent auto-redirects to capture initial response + }); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should succeed and redirect + Assert.True( + response.StatusCode == HttpStatusCode.Redirect, + $"Expected success/redirect but got {response.StatusCode}"); + + Assert.NotNull(response.Headers.Location); + } + + /* + * SUCCESS PATH: Test to verify /Account/ExternalCallback succeeds when JIT provisioning + * a new user (user doesn't exist, gets created automatically). + */ + [Fact] + public async Task ExternalCallback_WithJitProvisioning_ReturnsSuccess() + { + // Arrange - No user, no org user - JIT provisioning will create both + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .BuildAsync(); + + var client = testData.Factory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false // Prevent auto-redirects to capture initial response + }); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should succeed and redirect + Assert.True( + response.StatusCode == HttpStatusCode.Redirect, + $"Expected success/redirect but got {response.StatusCode}"); + + Assert.NotNull(response.Headers.Location); + } + + /* + * SUCCESS PATH: Test to verify /Account/ExternalCallback succeeds when an existing user + * with a valid (Confirmed) organization user status logs in via SSO for the first time. + */ + [Fact] + public async Task ExternalCallback_WithExistingUserAndConfirmedOrgUser_ReturnsSuccess() + { + // Arrange - Existing user with confirmed org user status, no SSO link yet + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser(orgUser => + { + orgUser.Status = OrganizationUserStatusType.Confirmed; + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false // Prevent auto-redirects to capture initial response + }); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should succeed and redirect + Assert.True( + response.StatusCode == HttpStatusCode.Redirect, + $"Expected success/redirect but got {response.StatusCode}"); + + Assert.NotNull(response.Headers.Location); + } + + /* + * SUCCESS PATH: Test to verify /Account/ExternalCallback succeeds when an existing user + * with Accepted organization user status logs in via SSO. + */ + [Fact] + public async Task ExternalCallback_WithExistingUserAndAcceptedOrgUser_ReturnsSuccess() + { + // Arrange - Existing user with accepted org user status + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser(orgUser => + { + orgUser.Status = OrganizationUserStatusType.Accepted; + }) + .BuildAsync(); + + var client = testData.Factory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false // Prevent auto-redirects to capture initial response + }); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Should succeed and redirect + Assert.True( + response.StatusCode == HttpStatusCode.Redirect, + $"Expected success/redirect but got {response.StatusCode}"); + + Assert.NotNull(response.Headers.Location); + } + + /* + * SUCCESS PATH: Test to verify /Account/ExternalCallback returns a View with 200 status + * when the client is a native application (uses custom URI scheme like "bitwarden://callback"). + * Native clients get a different response for better UX - a 200 with redirect view instead of 302. + * See AccountController lines 371-378. + */ + [Fact] + public async Task ExternalCallback_WithNativeClient_ReturnsViewWith200Status() + { + // Arrange - Existing SSO user with native client context + var testData = await new SsoTestDataBuilder() + .WithSsoConfig() + .WithUser() + .WithOrganizationUser() + .WithSsoUser() + .AsNativeClient() + .BuildAsync(); + + var client = testData.Factory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false + }); + + // Act + var response = await client.GetAsync("/Account/ExternalCallback"); + + // Assert - Native clients get 200 status with a redirect view instead of 302 + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + // The Location header should be empty for native clients (set in controller) + // and the response should contain the redirect view + var content = await response.Content.ReadAsStringAsync(); + Assert.NotEmpty(content); // View content should be present + } +} diff --git a/bitwarden_license/test/Sso.IntegrationTest/Properties/launchSettings.json b/bitwarden_license/test/Sso.IntegrationTest/Properties/launchSettings.json new file mode 100644 index 0000000000..63637a5304 --- /dev/null +++ b/bitwarden_license/test/Sso.IntegrationTest/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "Sso.IntegrationTest": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:59973;http://localhost:59974" + } + } +} \ No newline at end of file diff --git a/bitwarden_license/test/Sso.IntegrationTest/Sso.IntegrationTest.csproj b/bitwarden_license/test/Sso.IntegrationTest/Sso.IntegrationTest.csproj new file mode 100644 index 0000000000..42d0743d51 --- /dev/null +++ b/bitwarden_license/test/Sso.IntegrationTest/Sso.IntegrationTest.csproj @@ -0,0 +1,41 @@ + + + + net8.0 + enable + enable + + false + true + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + true + PreserveNewest + Never + + + + \ No newline at end of file diff --git a/bitwarden_license/test/Sso.IntegrationTest/Utilities/SsoApplicationFactory.cs b/bitwarden_license/test/Sso.IntegrationTest/Utilities/SsoApplicationFactory.cs new file mode 100644 index 0000000000..656c045284 --- /dev/null +++ b/bitwarden_license/test/Sso.IntegrationTest/Utilities/SsoApplicationFactory.cs @@ -0,0 +1,11 @@ +using Bit.IntegrationTestCommon.Factories; + +namespace Bit.Sso.IntegrationTest.Utilities; + +public class SsoApplicationFactory : WebApplicationFactoryBase +{ + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + } +} diff --git a/bitwarden_license/test/Sso.IntegrationTest/Utilities/SsoTestDataBuilder.cs b/bitwarden_license/test/Sso.IntegrationTest/Utilities/SsoTestDataBuilder.cs new file mode 100644 index 0000000000..95f2387af2 --- /dev/null +++ b/bitwarden_license/test/Sso.IntegrationTest/Utilities/SsoTestDataBuilder.cs @@ -0,0 +1,327 @@ +using Bit.Core.AdminConsole.Entities; +using Bit.Core.Auth.Entities; +using Bit.Core.Auth.Models.Data; +using Bit.Core.Auth.Repositories; +using Bit.Core.Entities; +using Bit.Core.Enums; +using Bit.Core.Repositories; +using Bit.Core.Settings; +using Bitwarden.License.Test.Sso.IntegrationTest.Utilities; +using Duende.IdentityServer.Models; +using Duende.IdentityServer.Services; +using Microsoft.AspNetCore.Authentication; +using NSubstitute; +using AuthenticationSchemes = Bit.Core.AuthenticationSchemes; + +namespace Bit.Sso.IntegrationTest.Utilities; + +/// +/// Contains the factory and all entities created by for use in integration tests. +/// +public record SsoTestData( + SsoApplicationFactory Factory, + Organization? Organization, + User? User, + OrganizationUser? OrganizationUser, + SsoConfig? SsoConfig, + SsoUser? SsoUser); + +/// +/// Builder for creating SSO test data with seeded database entities. +/// +public class SsoTestDataBuilder +{ + /// + /// This UserIdentifier is a mock for the UserIdentifier we get from the External Identity Provider. + /// + private string? _userIdentifier; + private Action? _organizationConfig; + private Action? _userConfig; + private Action? _orgUserConfig; + private Action? _ssoConfigConfig; + private Action? _ssoUserConfig; + private Action? _featureFlagConfig; + + private bool _includeUser = false; + private bool _includeSsoUser = false; + private bool _includeOrganizationUser = false; + private bool _includeSsoConfig = false; + private bool _successfulAuth = true; + private bool _withNullEmail = false; + private bool _isSelfHosted = false; + private bool _includeProviderUserId = true; + private bool _useNonExistentOrgInAuth = false; + private bool _isNativeClient = false; + + public SsoTestDataBuilder WithOrganization(Action configure) + { + _organizationConfig = configure; + return this; + } + + public SsoTestDataBuilder WithUser(Action? configure = null) + { + _includeUser = true; + _userConfig = configure; + return this; + } + + public SsoTestDataBuilder WithOrganizationUser(Action? configure = null) + { + _includeOrganizationUser = true; + _orgUserConfig = configure; + return this; + } + + public SsoTestDataBuilder WithSsoConfig(Action? configure = null) + { + _includeSsoConfig = true; + _ssoConfigConfig = configure; + return this; + } + + public SsoTestDataBuilder WithSsoUser(Action? configure = null) + { + _includeSsoUser = true; + _ssoUserConfig = configure; + return this; + } + + public SsoTestDataBuilder WithFeatureFlags(Action configure) + { + _featureFlagConfig = configure; + return this; + } + + public SsoTestDataBuilder WithFailedAuthentication() + { + _successfulAuth = false; + return this; + } + + public SsoTestDataBuilder WithNullEmail() + { + _withNullEmail = true; + return this; + } + + public SsoTestDataBuilder WithUserIdentifier(string userIdentifier) + { + _userIdentifier = userIdentifier; + return this; + } + + public SsoTestDataBuilder OmitProviderUserId() + { + _includeProviderUserId = false; + return this; + } + + public SsoTestDataBuilder AsSelfHosted() + { + _isSelfHosted = true; + return this; + } + + /// + /// Causes the auth result to use a different (non-existent) organization ID than what is seeded + /// in the database. This simulates the "organization not found" scenario. + /// + public SsoTestDataBuilder WithNonExistentOrganizationInAuth() + { + _useNonExistentOrgInAuth = true; + return this; + } + + /// + /// Configures the test to simulate a native client (non-browser) OIDC flow. + /// Native clients use custom URI schemes (e.g., "bitwarden://callback") instead of http/https. + /// This causes ExternalCallback to return a View with 200 status instead of a redirect. + /// + public SsoTestDataBuilder AsNativeClient() + { + _isNativeClient = true; + return this; + } + + public async Task BuildAsync() + { + // Create factory + var factory = new SsoApplicationFactory(); + + // Pre-generate IDs and values needed for auth mock (before accessing Services) + var organizationId = Guid.NewGuid(); + // Use a different org ID in auth if testing "organization not found" scenario + var authOrganizationId = _useNonExistentOrgInAuth ? Guid.NewGuid() : organizationId; + var providerUserId = _includeProviderUserId ? Guid.NewGuid().ToString() : ""; + var userEmail = _withNullEmail ? null : $"user_{Guid.NewGuid()}@test.com"; + var userName = "TestUser"; + + // 1. Configure mocked authentication service BEFORE accessing Services + factory.SubstituteService(authService => + { + if (_successfulAuth) + { + authService.AuthenticateAsync( + Arg.Any(), + AuthenticationSchemes.BitwardenExternalCookieAuthenticationScheme) + .Returns(MockSuccessfulAuthResult.Build( + authOrganizationId, + providerUserId, + userEmail, + userName, + acrValue: null, + _userIdentifier)); + } + else + { + authService.AuthenticateAsync( + Arg.Any(), + AuthenticationSchemes.BitwardenExternalCookieAuthenticationScheme) + .Returns(AuthenticateResult.Fail("External authentication error")); + } + }); + + // 1.a Configure GlobalSettings for Self-Hosted and seat limit + factory.SubstituteService(globalSettings => + { + globalSettings.SelfHosted.Returns(_isSelfHosted); + }); + + // 1.b configure setting feature flags + _featureFlagConfig?.Invoke(factory); + + // 1.c Configure IIdentityServerInteractionService for native client flow + if (_isNativeClient) + { + factory.SubstituteService(interaction => + { + // Native clients have redirect URIs that don't start with http/https + // e.g., "bitwarden://callback" or "com.bitwarden.app://callback" + var authorizationRequest = new AuthorizationRequest + { + RedirectUri = "bitwarden://sso-callback" + }; + interaction.GetAuthorizationContextAsync(Arg.Any()) + .Returns(authorizationRequest); + }); + } + + if (!_successfulAuth) + { + return new SsoTestData(factory, null!, null!, null!, null!, null!); + } + + // 2. Create Organization with defaults (using pre-generated ID) + var organization = new Organization + { + Id = organizationId, + Name = "Test Organization", + BillingEmail = "billing@test.com", + Plan = "Enterprise", + Enabled = true, + UseSso = true + }; + _organizationConfig?.Invoke(organization); + + var orgRepo = factory.Services.GetRequiredService(); + organization = await orgRepo.CreateAsync(organization); + + // 3. Create User with defaults (using pre-generated values) + User? user = null; + if (_includeUser) + { + user = new User + { + Email = userEmail ?? $"email_{Guid.NewGuid()}@test.dev", + Name = userName, + ApiKey = Guid.NewGuid().ToString(), + SecurityStamp = Guid.NewGuid().ToString() + }; + _userConfig?.Invoke(user); + + var userRepo = factory.Services.GetRequiredService(); + user = await userRepo.CreateAsync(user); + } + + // 4. Create OrganizationUser linking them + OrganizationUser? orgUser = null; + if (_includeOrganizationUser) + { + orgUser = new OrganizationUser + { + OrganizationId = organization.Id, + UserId = user!.Id, + Status = OrganizationUserStatusType.Confirmed, + Type = OrganizationUserType.User + }; + _orgUserConfig?.Invoke(orgUser); + + var orgUserRepo = factory.Services.GetRequiredService(); + orgUser = await orgUserRepo.CreateAsync(orgUser); + } + + // 4.a Create many OrganizationUser to test seat count logic + if (organization.Seats > 1) + { + var orgUserRepo = factory.Services.GetRequiredService(); + var userRepo = factory.Services.GetRequiredService(); + var additionalOrgUsers = new List(); + for (var i = 1; i <= organization.Seats; i++) + { + var additionalUser = new User + { + Email = $"additional_user_{i}_{Guid.NewGuid()}@test.dev", + Name = $"AdditionalUser{i}", + ApiKey = Guid.NewGuid().ToString(), + SecurityStamp = Guid.NewGuid().ToString() + }; + var createdAdditionalUser = await userRepo.CreateAsync(additionalUser); + + var additionalOrgUser = new OrganizationUser + { + OrganizationId = organization.Id, + UserId = createdAdditionalUser.Id, + Status = OrganizationUserStatusType.Confirmed, + Type = OrganizationUserType.User + }; + additionalOrgUsers.Add(additionalOrgUser); + } + await orgUserRepo.CreateManyAsync(additionalOrgUsers); + } + + // 5. Create SsoConfig, if ssoConfigConfig is not null + SsoConfig? ssoConfig = null; + if (_includeSsoConfig) + { + ssoConfig = new SsoConfig + { + OrganizationId = authOrganizationId, + Enabled = true + }; + ssoConfig.SetData(new SsoConfigurationData()); + _ssoConfigConfig?.Invoke(ssoConfig); + + var ssoConfigRepo = factory.Services.GetRequiredService(); + ssoConfig = await ssoConfigRepo.CreateAsync(ssoConfig); + } + + // 6. Optionally create SsoUser (using pre-generated providerUserId as ExternalId) + SsoUser? ssoUser = null; + if (_includeSsoUser) + { + ssoUser = new SsoUser + { + OrganizationId = organization.Id, + UserId = user!.Id, + ExternalId = providerUserId + }; + _ssoUserConfig?.Invoke(ssoUser); + + var ssoUserRepo = factory.Services.GetRequiredService(); + ssoUser = await ssoUserRepo.CreateAsync(ssoUser); + } + + return new SsoTestData(factory, organization, user, orgUser, ssoConfig, ssoUser); + } +} diff --git a/bitwarden_license/test/Sso.IntegrationTest/Utilities/SuccessfulAuthResult.cs b/bitwarden_license/test/Sso.IntegrationTest/Utilities/SuccessfulAuthResult.cs new file mode 100644 index 0000000000..72f5738ad9 --- /dev/null +++ b/bitwarden_license/test/Sso.IntegrationTest/Utilities/SuccessfulAuthResult.cs @@ -0,0 +1,88 @@ +using System.Security.Claims; +using Bit.Core; +using Duende.IdentityModel; +using Microsoft.AspNetCore.Authentication; + +namespace Bitwarden.License.Test.Sso.IntegrationTest.Utilities; + +/// +/// Creates a mock for use in tests requiring a valid external authentication result. +/// +internal static class MockSuccessfulAuthResult +{ + /// + /// Since this tests the external Authentication flow, only the OrganizationId is strictly required. + /// However, some tests may require additional claims to be present, so they can be optionally added. + /// + /// + /// + /// + /// + /// + /// + /// + public static AuthenticateResult Build( + Guid organizationId, + string? providerUserId, + string? email, + string? name = null, + string? acrValue = null, + string? userIdentifier = null) + { + return Build(organizationId.ToString(), providerUserId, email, name, acrValue, userIdentifier); + } + + /// + /// Overload that accepts a custom scheme string. Useful for testing invalid provider scenarios + /// where the scheme is not a valid GUID. + /// + public static AuthenticateResult Build( + string scheme, + string? providerUserId, + string? email, + string? name = null, + string? acrValue = null, + string? userIdentifier = null) + { + var claims = new List(); + + if (!string.IsNullOrEmpty(email)) + { + claims.Add(new Claim(JwtClaimTypes.Email, email)); + } + + if (!string.IsNullOrEmpty(providerUserId)) + { + claims.Add(new Claim(JwtClaimTypes.Subject, providerUserId)); + } + + if (!string.IsNullOrEmpty(name)) + { + claims.Add(new Claim(JwtClaimTypes.Name, name)); + } + + if (!string.IsNullOrEmpty(acrValue)) + { + claims.Add(new Claim(JwtClaimTypes.AuthenticationContextClassReference, acrValue)); + } + + var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "External")); + var properties = new AuthenticationProperties + { + Items = + { + ["scheme"] = scheme, + ["return_url"] = "~/", + ["state"] = "test-state", + ["user_identifier"] = userIdentifier ?? string.Empty + } + }; + + var ticket = new AuthenticationTicket( + principal, + properties, + AuthenticationSchemes.BitwardenExternalCookieAuthenticationScheme); + + return AuthenticateResult.Success(ticket); + } +} diff --git a/dev/setup_secrets.ps1 b/dev/setup_secrets.ps1 old mode 100644 new mode 100755 index 96dff04632..5013ca8bac --- a/dev/setup_secrets.ps1 +++ b/dev/setup_secrets.ps1 @@ -2,7 +2,7 @@ # Helper script for applying the same user secrets to each project param ( [switch]$clear, - [Parameter(ValueFromRemainingArguments = $true, Position=1)] + [Parameter(ValueFromRemainingArguments = $true, Position = 1)] $cmdArgs ) @@ -16,17 +16,18 @@ if ($clear -eq $true) { } $projects = @{ - Admin = "../src/Admin" - Api = "../src/Api" - Billing = "../src/Billing" - Events = "../src/Events" - EventsProcessor = "../src/EventsProcessor" - Icons = "../src/Icons" - Identity = "../src/Identity" - Notifications = "../src/Notifications" - Sso = "../bitwarden_license/src/Sso" - Scim = "../bitwarden_license/src/Scim" + Admin = "../src/Admin" + Api = "../src/Api" + Billing = "../src/Billing" + Events = "../src/Events" + EventsProcessor = "../src/EventsProcessor" + Icons = "../src/Icons" + Identity = "../src/Identity" + Notifications = "../src/Notifications" + Sso = "../bitwarden_license/src/Sso" + Scim = "../bitwarden_license/src/Scim" IntegrationTests = "../test/Infrastructure.IntegrationTest" + SeederApi = "../util/SeederApi" } foreach ($key in $projects.keys) { diff --git a/dev/verify_migrations.ps1 b/dev/verify_migrations.ps1 index d63c34f2bd..ad0d34cef1 100644 --- a/dev/verify_migrations.ps1 +++ b/dev/verify_migrations.ps1 @@ -41,7 +41,7 @@ $migrationPath = "util/Migrator/DbScripts" # Get list of migrations from base reference try { - $baseMigrations = git ls-tree -r --name-only $BaseRef -- "$migrationPath/*.sql" 2>$null | Sort-Object + $baseMigrations = git ls-tree -r --name-only $BaseRef -- "$migrationPath/" 2>$null | Where-Object { $_ -like "*.sql" } | Sort-Object if ($LASTEXITCODE -ne 0) { Write-Host "Warning: Could not retrieve migrations from base reference '$BaseRef'" $baseMigrations = @() @@ -53,7 +53,7 @@ catch { } # Get list of migrations from current reference -$currentMigrations = git ls-tree -r --name-only $CurrentRef -- "$migrationPath/*.sql" | Sort-Object +$currentMigrations = git ls-tree -r --name-only $CurrentRef -- "$migrationPath/" | Where-Object { $_ -like "*.sql" } | Sort-Object # Find added migrations $addedMigrations = $currentMigrations | Where-Object { $_ -notin $baseMigrations } diff --git a/src/Admin/Admin.csproj b/src/Admin/Admin.csproj index cd30e841b4..b815ddea82 100644 --- a/src/Admin/Admin.csproj +++ b/src/Admin/Admin.csproj @@ -2,6 +2,8 @@ bitwarden-Admin + + $(WarningsNotAsErrors);CA1304;CA1305 diff --git a/src/Admin/AdminConsole/Controllers/OrganizationsController.cs b/src/Admin/AdminConsole/Controllers/OrganizationsController.cs index cd370e3898..1dbab08ca6 100644 --- a/src/Admin/AdminConsole/Controllers/OrganizationsController.cs +++ b/src/Admin/AdminConsole/Controllers/OrganizationsController.cs @@ -496,6 +496,7 @@ public class OrganizationsController : Controller organization.UseOrganizationDomains = model.UseOrganizationDomains; organization.UseAdminSponsoredFamilies = model.UseAdminSponsoredFamilies; organization.UseAutomaticUserConfirmation = model.UseAutomaticUserConfirmation; + organization.UseDisableSmAdsForUsers = model.UseDisableSmAdsForUsers; organization.UsePhishingBlocker = model.UsePhishingBlocker; //secrets diff --git a/src/Admin/AdminConsole/Models/OrganizationEditModel.cs b/src/Admin/AdminConsole/Models/OrganizationEditModel.cs index 4fff85e1e8..77a8496e5b 100644 --- a/src/Admin/AdminConsole/Models/OrganizationEditModel.cs +++ b/src/Admin/AdminConsole/Models/OrganizationEditModel.cs @@ -107,6 +107,7 @@ public class OrganizationEditModel : OrganizationViewModel MaxAutoscaleSmServiceAccounts = org.MaxAutoscaleSmServiceAccounts; UseOrganizationDomains = org.UseOrganizationDomains; UseAutomaticUserConfirmation = org.UseAutomaticUserConfirmation; + UseDisableSmAdsForUsers = org.UseDisableSmAdsForUsers; UsePhishingBlocker = org.UsePhishingBlocker; _plans = plans; @@ -196,6 +197,8 @@ public class OrganizationEditModel : OrganizationViewModel public int? MaxAutoscaleSmServiceAccounts { get; set; } [Display(Name = "Use Organization Domains")] public bool UseOrganizationDomains { get; set; } + [Display(Name = "Disable SM Ads For Users")] + public new bool UseDisableSmAdsForUsers { get; set; } [Display(Name = "Automatic User Confirmation")] public bool UseAutomaticUserConfirmation { get; set; } @@ -330,6 +333,7 @@ public class OrganizationEditModel : OrganizationViewModel existingOrganization.SmServiceAccounts = SmServiceAccounts; existingOrganization.MaxAutoscaleSmServiceAccounts = MaxAutoscaleSmServiceAccounts; existingOrganization.UseOrganizationDomains = UseOrganizationDomains; + existingOrganization.UseDisableSmAdsForUsers = UseDisableSmAdsForUsers; existingOrganization.UsePhishingBlocker = UsePhishingBlocker; return existingOrganization; } diff --git a/src/Admin/AdminConsole/Models/OrganizationViewModel.cs b/src/Admin/AdminConsole/Models/OrganizationViewModel.cs index 457686be53..652535b592 100644 --- a/src/Admin/AdminConsole/Models/OrganizationViewModel.cs +++ b/src/Admin/AdminConsole/Models/OrganizationViewModel.cs @@ -76,6 +76,7 @@ public class OrganizationViewModel public bool UseSecretsManager => Organization.UseSecretsManager; public bool UseRiskInsights => Organization.UseRiskInsights; public bool UsePhishingBlocker => Organization.UsePhishingBlocker; + public bool UseDisableSmAdsForUsers => Organization.UseDisableSmAdsForUsers; public IEnumerable OwnersDetails { get; set; } public IEnumerable AdminsDetails { get; set; } } diff --git a/src/Admin/AdminConsole/Views/Shared/_OrganizationForm.cshtml b/src/Admin/AdminConsole/Views/Shared/_OrganizationForm.cshtml index b22859ed60..0b60d99e3c 100644 --- a/src/Admin/AdminConsole/Views/Shared/_OrganizationForm.cshtml +++ b/src/Admin/AdminConsole/Views/Shared/_OrganizationForm.cshtml @@ -185,6 +185,13 @@ + @if (FeatureService.IsEnabled(FeatureFlagKeys.SM1719_RemoveSecretsManagerAds)) + { +
+ + +
+ }

Access Intelligence

diff --git a/src/Admin/HostedServices/DatabaseMigrationHostedService.cs b/src/Admin/HostedServices/DatabaseMigrationHostedService.cs index 219e6846bd..51739ce655 100644 --- a/src/Admin/HostedServices/DatabaseMigrationHostedService.cs +++ b/src/Admin/HostedServices/DatabaseMigrationHostedService.cs @@ -1,5 +1,5 @@ -using Bit.Core.Utilities; -using Microsoft.Data.SqlClient; +using System.Data.Common; +using Bit.Core.Utilities; namespace Bit.Admin.HostedServices; @@ -30,7 +30,7 @@ public class DatabaseMigrationHostedService : IHostedService, IDisposable // TODO: Maybe flip a flag somewhere to indicate migration is complete?? break; } - catch (SqlException e) + catch (DbException e) { if (i >= maxMigrationAttempts) { @@ -40,7 +40,7 @@ public class DatabaseMigrationHostedService : IHostedService, IDisposable else { _logger.LogError(e, - "Database unavailable for migration. Trying again (attempt #{0})...", i + 1); + "Database unavailable for migration. Trying again (attempt #{AttemptNumber})...", i + 1); await Task.Delay(20000, cancellationToken); } } diff --git a/src/Admin/Startup.cs b/src/Admin/Startup.cs index 87d68a7ac6..6c0a644ee6 100644 --- a/src/Admin/Startup.cs +++ b/src/Admin/Startup.cs @@ -65,6 +65,7 @@ public class Startup default: break; } + services.AddTestPlayIdTracking(globalSettings); // Context services.AddScoped(); diff --git a/src/Admin/package-lock.json b/src/Admin/package-lock.json index 6e0f78e1e6..e851daac36 100644 --- a/src/Admin/package-lock.json +++ b/src/Admin/package-lock.json @@ -18,9 +18,9 @@ "css-loader": "7.1.2", "expose-loader": "5.0.1", "mini-css-extract-plugin": "2.9.2", - "sass": "1.93.2", + "sass": "1.97.2", "sass-loader": "16.0.5", - "webpack": "5.102.1", + "webpack": "5.104.1", "webpack-cli": "5.1.4" } }, @@ -750,9 +750,9 @@ } }, "node_modules/baseline-browser-mapping": { - "version": "2.8.18", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.8.18.tgz", - "integrity": "sha512-UYmTpOBwgPScZpS4A+YbapwWuBwasxvO/2IOHArSsAhL/+ZdmATBXTex3t+l2hXwLVYK382ibr/nKoY9GKe86w==", + "version": "2.9.13", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.13.tgz", + "integrity": "sha512-WhtvB2NG2wjr04+h77sg3klAIwrgOqnjS49GGudnUPGFFgg7G17y7Qecqp+2Dr5kUDxNRBca0SK7cG8JwzkWDQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -793,9 +793,9 @@ } }, "node_modules/browserslist": { - "version": "4.26.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.26.3.tgz", - "integrity": "sha512-lAUU+02RFBuCKQPj/P6NgjlbCnLBMp4UtgTx7vNHd3XSIJF87s9a5rA3aH2yw3GS9DqZAUbOtZdCCiZeVRqt0w==", + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", "dev": true, "funding": [ { @@ -814,11 +814,11 @@ "license": "MIT", "peer": true, "dependencies": { - "baseline-browser-mapping": "^2.8.9", - "caniuse-lite": "^1.0.30001746", - "electron-to-chromium": "^1.5.227", - "node-releases": "^2.0.21", - "update-browserslist-db": "^1.1.3" + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" @@ -835,9 +835,9 @@ "license": "MIT" }, "node_modules/caniuse-lite": { - "version": "1.0.30001751", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001751.tgz", - "integrity": "sha512-A0QJhug0Ly64Ii3eIqHu5X51ebln3k4yTUkY1j8drqpWHVreg/VLijN48cZ1bYPiqOQuqpkIKnzr/Ul8V+p6Cw==", + "version": "1.0.30001763", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001763.tgz", + "integrity": "sha512-mh/dGtq56uN98LlNX9qdbKnzINhX0QzhiWBFEkFfsFO4QyCvL8YegrJAazCwXIeqkIob8BlZPGM3xdnY+sgmvQ==", "dev": true, "funding": [ { @@ -989,9 +989,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.237", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.237.tgz", - "integrity": "sha512-icUt1NvfhGLar5lSWH3tHNzablaA5js3HVHacQimfP8ViEBOQv+L7DKEuHdbTZ0SKCO1ogTJTIL1Gwk9S6Qvcg==", + "version": "1.5.267", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", + "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", "dev": true, "license": "ISC" }, @@ -1023,9 +1023,9 @@ } }, "node_modules/es-module-lexer": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", - "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", + "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", "dev": true, "license": "MIT" }, @@ -1419,13 +1419,17 @@ } }, "node_modules/loader-runner": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", - "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.1.tgz", + "integrity": "sha512-IWqP2SCPhyVFTBtRcgMHdzlf9ul25NwaFx4wCEH/KjAXuuHY4yNjvPXsBokp8jCB936PyWRaPKUNh8NvylLp2Q==", "dev": true, "license": "MIT", "engines": { "node": ">=6.11.5" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" } }, "node_modules/locate-path": { @@ -1542,9 +1546,9 @@ "optional": true }, "node_modules/node-releases": { - "version": "2.0.26", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.26.tgz", - "integrity": "sha512-S2M9YimhSjBSvYnlr5/+umAnPHE++ODwt5e2Ij6FoX45HA/s4vHdkDx1eax2pAPeAOqu4s9b7ppahsyEFdVqQA==", + "version": "2.0.27", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", + "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", "dev": true, "license": "MIT" }, @@ -1875,9 +1879,9 @@ "license": "MIT" }, "node_modules/sass": { - "version": "1.93.2", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.93.2.tgz", - "integrity": "sha512-t+YPtOQHpGW1QWsh1CHQ5cPIr9lbbGZLZnbihP/D/qZj/yuV68m8qarcV17nvkOX81BCrvzAlq2klCQFZghyTg==", + "version": "1.97.2", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.97.2.tgz", + "integrity": "sha512-y5LWb0IlbO4e97Zr7c3mlpabcbBtS+ieiZ9iwDooShpFKWXf62zz5pEPdwrLYm+Bxn1fnbwFGzHuCLSA9tBmrw==", "dev": true, "license": "MIT", "peer": true, @@ -2110,9 +2114,9 @@ } }, "node_modules/terser-webpack-plugin": { - "version": "5.3.14", - "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.14.tgz", - "integrity": "sha512-vkZjpUjb6OMS7dhV+tILUW6BhpDR7P2L/aQSAv+Uwk+m8KATX9EccViHTJR2qDtACKPIYndLGCyl3FMo+r2LMw==", + "version": "5.3.16", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.16.tgz", + "integrity": "sha512-h9oBFCWrq78NyWWVcSwZarJkZ01c2AyGrzs1crmHZO3QUg9D61Wu4NPjBy69n7JqylFF5y+CsUZYmYEIZ3mR+Q==", "dev": true, "license": "MIT", "dependencies": { @@ -2174,9 +2178,9 @@ "license": "MIT" }, "node_modules/update-browserslist-db": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz", - "integrity": "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", "dev": true, "funding": [ { @@ -2226,9 +2230,9 @@ } }, "node_modules/webpack": { - "version": "5.102.1", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.102.1.tgz", - "integrity": "sha512-7h/weGm9d/ywQ6qzJ+Xy+r9n/3qgp/thalBbpOi5i223dPXKi04IBtqPN9nTd+jBc7QKfvDbaBnFipYp4sJAUQ==", + "version": "5.104.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.104.1.tgz", + "integrity": "sha512-Qphch25abbMNtekmEGJmeRUhLDbe+QfiWTiqpKYkpCOWY64v9eyl+KRRLmqOFA2AvKPpc9DC6+u2n76tQLBoaA==", "dev": true, "license": "MIT", "peer": true, @@ -2241,21 +2245,21 @@ "@webassemblyjs/wasm-parser": "^1.14.1", "acorn": "^8.15.0", "acorn-import-phases": "^1.0.3", - "browserslist": "^4.26.3", + "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.17.3", - "es-module-lexer": "^1.2.1", + "enhanced-resolve": "^5.17.4", + "es-module-lexer": "^2.0.0", "eslint-scope": "5.1.1", "events": "^3.2.0", "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.2.11", "json-parse-even-better-errors": "^2.3.1", - "loader-runner": "^4.2.0", + "loader-runner": "^4.3.1", "mime-types": "^2.1.27", "neo-async": "^2.6.2", "schema-utils": "^4.3.3", "tapable": "^2.3.0", - "terser-webpack-plugin": "^5.3.11", + "terser-webpack-plugin": "^5.3.16", "watchpack": "^2.4.4", "webpack-sources": "^3.3.3" }, diff --git a/src/Admin/package.json b/src/Admin/package.json index f6f21e2cf9..3a3926d6ee 100644 --- a/src/Admin/package.json +++ b/src/Admin/package.json @@ -17,9 +17,9 @@ "css-loader": "7.1.2", "expose-loader": "5.0.1", "mini-css-extract-plugin": "2.9.2", - "sass": "1.93.2", + "sass": "1.97.2", "sass-loader": "16.0.5", - "webpack": "5.102.1", + "webpack": "5.104.1", "webpack-cli": "5.1.4" } } diff --git a/src/Api/AdminConsole/Authorization/Requirements/MemberRequirement.cs b/src/Api/AdminConsole/Authorization/Requirements/MemberRequirement.cs new file mode 100644 index 0000000000..ed205524d1 --- /dev/null +++ b/src/Api/AdminConsole/Authorization/Requirements/MemberRequirement.cs @@ -0,0 +1,14 @@ +using Bit.Core.Context; + +namespace Bit.Api.AdminConsole.Authorization.Requirements; + +/// +/// Requires that the user is a member of the organization. +/// +public class MemberRequirement : IOrganizationRequirement +{ + public Task AuthorizeAsync( + CurrentContextOrganization? organizationClaims, + Func> isProviderUserForOrg) + => Task.FromResult(organizationClaims is not null); +} diff --git a/src/Api/AdminConsole/Controllers/OrganizationUsersController.cs b/src/Api/AdminConsole/Controllers/OrganizationUsersController.cs index a380d2f0d9..90d02a46a1 100644 --- a/src/Api/AdminConsole/Controllers/OrganizationUsersController.cs +++ b/src/Api/AdminConsole/Controllers/OrganizationUsersController.cs @@ -19,6 +19,7 @@ using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.DeleteClaimed using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.Interfaces; using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.InviteUsers; using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.RestoreUser.v1; +using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.SelfRevokeUser; using Bit.Core.AdminConsole.OrganizationFeatures.Policies; using Bit.Core.AdminConsole.OrganizationFeatures.Policies.PolicyRequirements; using Bit.Core.AdminConsole.Repositories; @@ -81,6 +82,7 @@ public class OrganizationUsersController : BaseAdminConsoleController private readonly IInitPendingOrganizationCommand _initPendingOrganizationCommand; private readonly V1_RevokeOrganizationUserCommand _revokeOrganizationUserCommand; private readonly IAdminRecoverAccountCommand _adminRecoverAccountCommand; + private readonly ISelfRevokeOrganizationUserCommand _selfRevokeOrganizationUserCommand; public OrganizationUsersController(IOrganizationRepository organizationRepository, IOrganizationUserRepository organizationUserRepository, @@ -112,7 +114,8 @@ public class OrganizationUsersController : BaseAdminConsoleController IBulkResendOrganizationInvitesCommand bulkResendOrganizationInvitesCommand, IAdminRecoverAccountCommand adminRecoverAccountCommand, IAutomaticallyConfirmOrganizationUserCommand automaticallyConfirmOrganizationUserCommand, - V2_RevokeOrganizationUserCommand.IRevokeOrganizationUserCommand revokeOrganizationUserCommandVNext) + V2_RevokeOrganizationUserCommand.IRevokeOrganizationUserCommand revokeOrganizationUserCommandVNext, + ISelfRevokeOrganizationUserCommand selfRevokeOrganizationUserCommand) { _organizationRepository = organizationRepository; _organizationUserRepository = organizationUserRepository; @@ -145,6 +148,7 @@ public class OrganizationUsersController : BaseAdminConsoleController _initPendingOrganizationCommand = initPendingOrganizationCommand; _revokeOrganizationUserCommand = revokeOrganizationUserCommand; _adminRecoverAccountCommand = adminRecoverAccountCommand; + _selfRevokeOrganizationUserCommand = selfRevokeOrganizationUserCommand; } [HttpGet("{id}")] @@ -635,6 +639,20 @@ public class OrganizationUsersController : BaseAdminConsoleController await RestoreOrRevokeUserAsync(orgId, id, _revokeOrganizationUserCommand.RevokeUserAsync); } + [HttpPut("revoke-self")] + [Authorize] + public async Task RevokeSelfAsync(Guid orgId) + { + var userId = _userService.GetProperUserId(User); + if (!userId.HasValue) + { + throw new UnauthorizedAccessException(); + } + + var result = await _selfRevokeOrganizationUserCommand.SelfRevokeUserAsync(orgId, userId.Value); + return Handle(result); + } + [HttpPatch("{id}/revoke")] [Obsolete("This endpoint is deprecated. Use PUT method instead")] [Authorize] @@ -647,11 +665,6 @@ public class OrganizationUsersController : BaseAdminConsoleController [Authorize] public async Task> BulkRevokeAsync(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model) { - if (!_featureService.IsEnabled(FeatureFlagKeys.BulkRevokeUsersV2)) - { - return await RestoreOrRevokeUsersAsync(orgId, model, _revokeOrganizationUserCommand.RevokeUsersAsync); - } - var currentUserId = _userService.GetProperUserId(User); if (currentUserId == null) { diff --git a/src/Api/AdminConsole/Controllers/PoliciesController.cs b/src/Api/AdminConsole/Controllers/PoliciesController.cs index ae1d12e887..bce0332d67 100644 --- a/src/Api/AdminConsole/Controllers/PoliciesController.cs +++ b/src/Api/AdminConsole/Controllers/PoliciesController.cs @@ -7,7 +7,6 @@ using Bit.Api.AdminConsole.Models.Request; using Bit.Api.AdminConsole.Models.Response.Helpers; using Bit.Api.AdminConsole.Models.Response.Organizations; using Bit.Api.Models.Response; -using Bit.Core; using Bit.Core.AdminConsole.Entities; using Bit.Core.AdminConsole.Enums; using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationDomains.Interfaces; @@ -212,7 +211,6 @@ public class PoliciesController : Controller } [HttpPut("{type}/vnext")] - [RequireFeatureAttribute(FeatureFlagKeys.CreateDefaultLocation)] [Authorize] public async Task PutVNext(Guid orgId, PolicyType type, [FromBody] SavePolicyRequest model) { diff --git a/src/Api/AdminConsole/Models/Response/BaseProfileOrganizationResponseModel.cs b/src/Api/AdminConsole/Models/Response/BaseProfileOrganizationResponseModel.cs index f5ef468b4e..c3378cd11d 100644 --- a/src/Api/AdminConsole/Models/Response/BaseProfileOrganizationResponseModel.cs +++ b/src/Api/AdminConsole/Models/Response/BaseProfileOrganizationResponseModel.cs @@ -48,6 +48,7 @@ public abstract class BaseProfileOrganizationResponseModel : ResponseModel UseAutomaticUserConfirmation = organizationDetails.UseAutomaticUserConfirmation; UseSecretsManager = organizationDetails.UseSecretsManager; UsePhishingBlocker = organizationDetails.UsePhishingBlocker; + UseDisableSMAdsForUsers = organizationDetails.UseDisableSMAdsForUsers; UsePasswordManager = organizationDetails.UsePasswordManager; SelfHost = organizationDetails.SelfHost; Seats = organizationDetails.Seats; @@ -100,6 +101,7 @@ public abstract class BaseProfileOrganizationResponseModel : ResponseModel public bool UseOrganizationDomains { get; set; } public bool UseAdminSponsoredFamilies { get; set; } public bool UseAutomaticUserConfirmation { get; set; } + public bool UseDisableSMAdsForUsers { get; set; } public bool UsePhishingBlocker { get; set; } public bool SelfHost { get; set; } public int? Seats { get; set; } diff --git a/src/Api/AdminConsole/Models/Response/Organizations/OrganizationResponseModel.cs b/src/Api/AdminConsole/Models/Response/Organizations/OrganizationResponseModel.cs index 9a3543f4bb..46c5a50b6c 100644 --- a/src/Api/AdminConsole/Models/Response/Organizations/OrganizationResponseModel.cs +++ b/src/Api/AdminConsole/Models/Response/Organizations/OrganizationResponseModel.cs @@ -74,6 +74,7 @@ public class OrganizationResponseModel : ResponseModel UseOrganizationDomains = organization.UseOrganizationDomains; UseAdminSponsoredFamilies = organization.UseAdminSponsoredFamilies; UseAutomaticUserConfirmation = organization.UseAutomaticUserConfirmation; + UseDisableSmAdsForUsers = organization.UseDisableSmAdsForUsers; UsePhishingBlocker = organization.UsePhishingBlocker; } @@ -124,6 +125,7 @@ public class OrganizationResponseModel : ResponseModel public bool UseOrganizationDomains { get; set; } public bool UseAdminSponsoredFamilies { get; set; } public bool UseAutomaticUserConfirmation { get; set; } + public bool UseDisableSmAdsForUsers { get; set; } public bool UsePhishingBlocker { get; set; } } diff --git a/src/Api/Api.csproj b/src/Api/Api.csproj index dd27de2e63..d25b989d11 100644 --- a/src/Api/Api.csproj +++ b/src/Api/Api.csproj @@ -4,6 +4,8 @@ false bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml true + + $(WarningsNotAsErrors);CA1304;CA1305 diff --git a/src/Api/Auth/Controllers/AccountsController.cs b/src/Api/Auth/Controllers/AccountsController.cs index 839d00f7a1..1223e2f05f 100644 --- a/src/Api/Auth/Controllers/AccountsController.cs +++ b/src/Api/Auth/Controllers/AccountsController.cs @@ -38,7 +38,9 @@ public class AccountsController : Controller private readonly IProviderUserRepository _providerUserRepository; private readonly IUserService _userService; private readonly IPolicyService _policyService; + private readonly ISetInitialMasterPasswordCommandV1 _setInitialMasterPasswordCommandV1; private readonly ISetInitialMasterPasswordCommand _setInitialMasterPasswordCommand; + private readonly ITdeSetPasswordCommand _tdeSetPasswordCommand; private readonly ITdeOffboardingPasswordCommand _tdeOffboardingPasswordCommand; private readonly ITwoFactorIsEnabledQuery _twoFactorIsEnabledQuery; private readonly IFeatureService _featureService; @@ -54,6 +56,8 @@ public class AccountsController : Controller IUserService userService, IPolicyService policyService, ISetInitialMasterPasswordCommand setInitialMasterPasswordCommand, + ISetInitialMasterPasswordCommandV1 setInitialMasterPasswordCommandV1, + ITdeSetPasswordCommand tdeSetPasswordCommand, ITdeOffboardingPasswordCommand tdeOffboardingPasswordCommand, ITwoFactorIsEnabledQuery twoFactorIsEnabledQuery, IFeatureService featureService, @@ -69,6 +73,8 @@ public class AccountsController : Controller _userService = userService; _policyService = policyService; _setInitialMasterPasswordCommand = setInitialMasterPasswordCommand; + _setInitialMasterPasswordCommandV1 = setInitialMasterPasswordCommandV1; + _tdeSetPasswordCommand = tdeSetPasswordCommand; _tdeOffboardingPasswordCommand = tdeOffboardingPasswordCommand; _twoFactorIsEnabledQuery = twoFactorIsEnabledQuery; _featureService = featureService; @@ -208,7 +214,7 @@ public class AccountsController : Controller } [HttpPost("set-password")] - public async Task PostSetPasswordAsync([FromBody] SetPasswordRequestModel model) + public async Task PostSetPasswordAsync([FromBody] SetInitialPasswordRequestModel model) { var user = await _userService.GetUserByPrincipalAsync(User); if (user == null) @@ -216,33 +222,48 @@ public class AccountsController : Controller throw new UnauthorizedAccessException(); } - try + if (model.IsV2Request()) { - user = model.ToUser(user); + if (model.IsTdeSetPasswordRequest()) + { + await _tdeSetPasswordCommand.SetMasterPasswordAsync(user, model.ToData()); + } + else + { + await _setInitialMasterPasswordCommand.SetInitialMasterPasswordAsync(user, model.ToData()); + } } - catch (Exception e) + else { - ModelState.AddModelError(string.Empty, e.Message); + // TODO removed with https://bitwarden.atlassian.net/browse/PM-27327 + try + { + user = model.ToUser(user); + } + catch (Exception e) + { + ModelState.AddModelError(string.Empty, e.Message); + throw new BadRequestException(ModelState); + } + + var result = await _setInitialMasterPasswordCommandV1.SetInitialMasterPasswordAsync( + user, + model.MasterPasswordHash, + model.Key, + model.OrgIdentifier); + + if (result.Succeeded) + { + return; + } + + foreach (var error in result.Errors) + { + ModelState.AddModelError(string.Empty, error.Description); + } + throw new BadRequestException(ModelState); } - - var result = await _setInitialMasterPasswordCommand.SetInitialMasterPasswordAsync( - user, - model.MasterPasswordHash, - model.Key, - model.OrgIdentifier); - - if (result.Succeeded) - { - return; - } - - foreach (var error in result.Errors) - { - ModelState.AddModelError(string.Empty, error.Description); - } - - throw new BadRequestException(ModelState); } [HttpPost("verify-password")] diff --git a/src/Api/Auth/Controllers/WebAuthnController.cs b/src/Api/Auth/Controllers/WebAuthnController.cs index 60b8621c5e..833087e99c 100644 --- a/src/Api/Auth/Controllers/WebAuthnController.cs +++ b/src/Api/Auth/Controllers/WebAuthnController.cs @@ -21,7 +21,6 @@ using Microsoft.AspNetCore.Mvc; namespace Bit.Api.Auth.Controllers; [Route("webauthn")] -[Authorize(Policies.Web)] public class WebAuthnController : Controller { private readonly IUserService _userService; @@ -62,6 +61,7 @@ public class WebAuthnController : Controller _featureService = featureService; } + [Authorize(Policies.Web)] [HttpGet("")] public async Task> Get() { @@ -71,6 +71,7 @@ public class WebAuthnController : Controller return new ListResponseModel(credentials.Select(c => new WebAuthnCredentialResponseModel(c))); } + [Authorize(Policies.Application)] [HttpPost("attestation-options")] public async Task AttestationOptions([FromBody] SecretVerificationRequestModel model) { @@ -88,6 +89,7 @@ public class WebAuthnController : Controller }; } + [Authorize(Policies.Web)] [HttpPost("assertion-options")] public async Task AssertionOptions([FromBody] SecretVerificationRequestModel model) { @@ -104,6 +106,7 @@ public class WebAuthnController : Controller }; } + [Authorize(Policies.Application)] [HttpPost("")] public async Task Post([FromBody] WebAuthnLoginCredentialCreateRequestModel model) { @@ -149,6 +152,7 @@ public class WebAuthnController : Controller } } + [Authorize(Policies.Application)] [HttpPut()] public async Task UpdateCredential([FromBody] WebAuthnLoginCredentialUpdateRequestModel model) { @@ -172,6 +176,7 @@ public class WebAuthnController : Controller await _credentialRepository.UpdateAsync(credential); } + [Authorize(Policies.Web)] [HttpPost("{id}/delete")] public async Task Delete(Guid id, [FromBody] SecretVerificationRequestModel model) { diff --git a/src/Api/Auth/Models/Request/Accounts/SetInitialPasswordRequestModel.cs b/src/Api/Auth/Models/Request/Accounts/SetInitialPasswordRequestModel.cs new file mode 100644 index 0000000000..55ffdca94b --- /dev/null +++ b/src/Api/Auth/Models/Request/Accounts/SetInitialPasswordRequestModel.cs @@ -0,0 +1,160 @@ +using System.ComponentModel.DataAnnotations; +using Bit.Api.KeyManagement.Models.Requests; +using Bit.Core.Auth.Models.Api.Request.Accounts; +using Bit.Core.Auth.Models.Data; +using Bit.Core.Entities; +using Bit.Core.Enums; +using Bit.Core.KeyManagement.Models.Api.Request; +using Bit.Core.Utilities; + +namespace Bit.Api.Auth.Models.Request.Accounts; + +public class SetInitialPasswordRequestModel : IValidatableObject +{ + // TODO will be removed with https://bitwarden.atlassian.net/browse/PM-27327 + [Obsolete("Use MasterPasswordAuthentication instead")] + [StringLength(300)] + public string? MasterPasswordHash { get; set; } + + [Obsolete("Use MasterPasswordUnlock instead")] + public string? Key { get; set; } + + [Obsolete("Use AccountKeys instead")] + public KeysRequestModel? Keys { get; set; } + + [Obsolete("Use MasterPasswordAuthentication instead")] + public KdfType? Kdf { get; set; } + + [Obsolete("Use MasterPasswordAuthentication instead")] + public int? KdfIterations { get; set; } + + [Obsolete("Use MasterPasswordAuthentication instead")] + public int? KdfMemory { get; set; } + + [Obsolete("Use MasterPasswordAuthentication instead")] + public int? KdfParallelism { get; set; } + + public MasterPasswordAuthenticationDataRequestModel? MasterPasswordAuthentication { get; set; } + public MasterPasswordUnlockDataRequestModel? MasterPasswordUnlock { get; set; } + public AccountKeysRequestModel? AccountKeys { get; set; } + + [StringLength(50)] + public string? MasterPasswordHint { get; set; } + + [Required] + public required string OrgIdentifier { get; set; } + + // TODO removed with https://bitwarden.atlassian.net/browse/PM-27327 + public User ToUser(User existingUser) + { + existingUser.MasterPasswordHint = MasterPasswordHint; + existingUser.Kdf = Kdf!.Value; + existingUser.KdfIterations = KdfIterations!.Value; + existingUser.KdfMemory = KdfMemory; + existingUser.KdfParallelism = KdfParallelism; + existingUser.Key = Key; + Keys?.ToUser(existingUser); + return existingUser; + } + + public IEnumerable Validate(ValidationContext validationContext) + { + if (IsV2Request()) + { + // V2 registration + + // Validate Kdf + var authenticationKdf = MasterPasswordAuthentication!.Kdf.ToData(); + var unlockKdf = MasterPasswordUnlock!.Kdf.ToData(); + + // Currently, KDF settings are not saved separately for authentication and unlock and must therefore be equal + if (!authenticationKdf.Equals(unlockKdf)) + { + yield return new ValidationResult("KDF settings must be equal for authentication and unlock.", + [$"{nameof(MasterPasswordAuthentication)}.{nameof(MasterPasswordAuthenticationDataRequestModel.Kdf)}", + $"{nameof(MasterPasswordUnlock)}.{nameof(MasterPasswordUnlockDataRequestModel.Kdf)}"]); + } + + var authenticationValidationErrors = KdfSettingsValidator.Validate(authenticationKdf).ToList(); + if (authenticationValidationErrors.Count != 0) + { + yield return authenticationValidationErrors.First(); + } + + var unlockValidationErrors = KdfSettingsValidator.Validate(unlockKdf).ToList(); + if (unlockValidationErrors.Count != 0) + { + yield return unlockValidationErrors.First(); + } + + yield break; + } + + // V1 registration + // TODO removed with https://bitwarden.atlassian.net/browse/PM-27327 + if (string.IsNullOrEmpty(MasterPasswordHash)) + { + yield return new ValidationResult("MasterPasswordHash must be supplied."); + } + + if (string.IsNullOrEmpty(Key)) + { + yield return new ValidationResult("Key must be supplied."); + } + + if (Kdf == null) + { + yield return new ValidationResult("Kdf must be supplied."); + yield break; + } + + if (KdfIterations == null) + { + yield return new ValidationResult("KdfIterations must be supplied."); + yield break; + } + + if (Kdf == KdfType.Argon2id) + { + if (KdfMemory == null) + { + yield return new ValidationResult("KdfMemory must be supplied when Kdf is Argon2id."); + } + + if (KdfParallelism == null) + { + yield return new ValidationResult("KdfParallelism must be supplied when Kdf is Argon2id."); + } + } + + var validationErrors = KdfSettingsValidator + .Validate(Kdf!.Value, KdfIterations!.Value, KdfMemory, KdfParallelism).ToList(); + if (validationErrors.Count != 0) + { + yield return validationErrors.First(); + } + } + + public bool IsV2Request() + { + // AccountKeys can be null for TDE users, so we don't check that here + return MasterPasswordAuthentication != null && MasterPasswordUnlock != null; + } + + public bool IsTdeSetPasswordRequest() + { + return AccountKeys == null; + } + + public SetInitialMasterPasswordDataModel ToData() + { + return new SetInitialMasterPasswordDataModel + { + MasterPasswordAuthentication = MasterPasswordAuthentication!.ToData(), + MasterPasswordUnlock = MasterPasswordUnlock!.ToData(), + OrgSsoIdentifier = OrgIdentifier, + AccountKeys = AccountKeys?.ToAccountKeysData(), + MasterPasswordHint = MasterPasswordHint + }; + } +} diff --git a/src/Api/Auth/Models/Request/Accounts/SetPasswordRequestModel.cs b/src/Api/Auth/Models/Request/Accounts/SetPasswordRequestModel.cs deleted file mode 100644 index 0d809c6c11..0000000000 --- a/src/Api/Auth/Models/Request/Accounts/SetPasswordRequestModel.cs +++ /dev/null @@ -1,40 +0,0 @@ -// FIXME: Update this file to be null safe and then delete the line below -#nullable disable - -using System.ComponentModel.DataAnnotations; -using Bit.Core.Auth.Models.Api.Request.Accounts; -using Bit.Core.Entities; -using Bit.Core.Enums; - -namespace Bit.Api.Auth.Models.Request.Accounts; - -public class SetPasswordRequestModel -{ - [Required] - [StringLength(300)] - public string MasterPasswordHash { get; set; } - [Required] - public string Key { get; set; } - [StringLength(50)] - public string MasterPasswordHint { get; set; } - public KeysRequestModel Keys { get; set; } - [Required] - public KdfType Kdf { get; set; } - [Required] - public int KdfIterations { get; set; } - public int? KdfMemory { get; set; } - public int? KdfParallelism { get; set; } - public string OrgIdentifier { get; set; } - - public User ToUser(User existingUser) - { - existingUser.MasterPasswordHint = MasterPasswordHint; - existingUser.Kdf = Kdf; - existingUser.KdfIterations = KdfIterations; - existingUser.KdfMemory = KdfMemory; - existingUser.KdfParallelism = KdfParallelism; - existingUser.Key = Key; - Keys?.ToUser(existingUser); - return existingUser; - } -} diff --git a/src/Api/Auth/Models/Request/EmergencyAccessRequestModels.cs b/src/Api/Auth/Models/Request/EmergencyAccessRequestModels.cs index 33a7e52791..75e96ebc66 100644 --- a/src/Api/Auth/Models/Request/EmergencyAccessRequestModels.cs +++ b/src/Api/Auth/Models/Request/EmergencyAccessRequestModels.cs @@ -36,7 +36,7 @@ public class EmergencyAccessUpdateRequestModel existingEmergencyAccess.KeyEncrypted = KeyEncrypted; } existingEmergencyAccess.Type = Type; - existingEmergencyAccess.WaitTimeDays = WaitTimeDays; + existingEmergencyAccess.WaitTimeDays = (short)WaitTimeDays; return existingEmergencyAccess; } } diff --git a/src/Api/Billing/Controllers/AccountsController.cs b/src/Api/Billing/Controllers/AccountsController.cs index 5d3e095fdd..c90b927bee 100644 --- a/src/Api/Billing/Controllers/AccountsController.cs +++ b/src/Api/Billing/Controllers/AccountsController.cs @@ -3,13 +3,10 @@ using Bit.Api.Models.Request.Accounts; using Bit.Api.Models.Response; using Bit.Api.Utilities; using Bit.Core; -using Bit.Core.Auth.UserFeatures.TwoFactorAuth.Interfaces; using Bit.Core.Billing.Models; using Bit.Core.Billing.Models.Business; using Bit.Core.Billing.Services; using Bit.Core.Exceptions; -using Bit.Core.KeyManagement.Queries.Interfaces; -using Bit.Core.Models.Business; using Bit.Core.Services; using Bit.Core.Settings; using Bit.Core.Utilities; @@ -22,60 +19,10 @@ namespace Bit.Api.Billing.Controllers; [Authorize("Application")] public class AccountsController( IUserService userService, - ITwoFactorIsEnabledQuery twoFactorIsEnabledQuery, - IUserAccountKeysQuery userAccountKeysQuery, IFeatureService featureService, ILicensingService licensingService) : Controller { - // TODO: Remove when pm-24996-implement-upgrade-from-free-dialog is removed - [HttpPost("premium")] - public async Task PostPremiumAsync( - PremiumRequestModel model, - [FromServices] GlobalSettings globalSettings) - { - var user = await userService.GetUserByPrincipalAsync(User); - if (user == null) - { - throw new UnauthorizedAccessException(); - } - - var valid = model.Validate(globalSettings); - UserLicense? license = null; - if (valid && globalSettings.SelfHosted) - { - license = await ApiHelpers.ReadJsonFileFromBody(HttpContext, model.License); - } - - if (!valid && !globalSettings.SelfHosted && string.IsNullOrWhiteSpace(model.Country)) - { - throw new BadRequestException("Country is required."); - } - - if (!valid || (globalSettings.SelfHosted && license == null)) - { - throw new BadRequestException("Invalid license."); - } - - var result = await userService.SignUpPremiumAsync(user, model.PaymentToken, - model.PaymentMethodType!.Value, model.AdditionalStorageGb.GetValueOrDefault(0), license, - new TaxInfo { BillingAddressCountry = model.Country, BillingAddressPostalCode = model.PostalCode }); - - var userTwoFactorEnabled = await twoFactorIsEnabledQuery.TwoFactorIsEnabledAsync(user); - var userHasPremiumFromOrganization = await userService.HasPremiumFromOrganization(user); - var organizationIdsClaimingActiveUser = await GetOrganizationIdsClaimingUserAsync(user.Id); - var accountKeys = await userAccountKeysQuery.Run(user); - - var profile = new ProfileResponseModel(user, accountKeys, null, null, null, userTwoFactorEnabled, - userHasPremiumFromOrganization, organizationIdsClaimingActiveUser); - return new PaymentResponseModel - { - UserProfile = profile, - PaymentIntentClientSecret = result.Item2, - Success = result.Item1 - }; - } - - // TODO: Migrate to Query / AccountBillingVNextController as part of Premium -> Organization upgrade work. + // TODO: Remove with deletion of pm-29594-update-individual-subscription-page [HttpGet("subscription")] public async Task GetSubscriptionAsync( [FromServices] GlobalSettings globalSettings, @@ -114,7 +61,7 @@ public class AccountsController( } } - // TODO: Migrate to Command / AccountBillingVNextController as PUT /account/billing/vnext/subscription + // TODO: Remove with deletion of pm-29594-update-individual-subscription-page [HttpPost("storage")] [SelfHosted(NotSelfHostedOnly = true)] public async Task PostStorageAsync([FromBody] StorageRequestModel model) @@ -171,7 +118,7 @@ public class AccountsController( user.IsExpired()); } - // TODO: Migrate to Command / AccountBillingVNextController as POST /account/billing/vnext/subscription/reinstate + // TODO: Remove with deletion of pm-29594-update-individual-subscription-page [HttpPost("reinstate-premium")] [SelfHosted(NotSelfHostedOnly = true)] public async Task PostReinstateAsync() @@ -184,10 +131,4 @@ public class AccountsController( await userService.ReinstatePremiumAsync(user); } - - private async Task> GetOrganizationIdsClaimingUserAsync(Guid userId) - { - var organizationsClaimingUser = await userService.GetOrganizationsClaimingUserAsync(userId); - return organizationsClaimingUser.Select(o => o.Id); - } } diff --git a/src/Api/Billing/Controllers/VNext/AccountBillingVNextController.cs b/src/Api/Billing/Controllers/VNext/AccountBillingVNextController.cs index b01b629e4f..6c56d6db3a 100644 --- a/src/Api/Billing/Controllers/VNext/AccountBillingVNextController.cs +++ b/src/Api/Billing/Controllers/VNext/AccountBillingVNextController.cs @@ -1,10 +1,14 @@ using Bit.Api.Billing.Attributes; using Bit.Api.Billing.Models.Requests.Payment; using Bit.Api.Billing.Models.Requests.Premium; +using Bit.Api.Billing.Models.Requests.Storage; using Bit.Core; +using Bit.Core.Billing.Licenses.Queries; using Bit.Core.Billing.Payment.Commands; using Bit.Core.Billing.Payment.Queries; using Bit.Core.Billing.Premium.Commands; +using Bit.Core.Billing.Subscriptions.Commands; +using Bit.Core.Billing.Subscriptions.Queries; using Bit.Core.Entities; using Bit.Core.Utilities; using Microsoft.AspNetCore.Authorization; @@ -19,9 +23,14 @@ namespace Bit.Api.Billing.Controllers.VNext; public class AccountBillingVNextController( ICreateBitPayInvoiceForCreditCommand createBitPayInvoiceForCreditCommand, ICreatePremiumCloudHostedSubscriptionCommand createPremiumCloudHostedSubscriptionCommand, + IGetBitwardenSubscriptionQuery getBitwardenSubscriptionQuery, IGetCreditQuery getCreditQuery, IGetPaymentMethodQuery getPaymentMethodQuery, - IUpdatePaymentMethodCommand updatePaymentMethodCommand) : BaseBillingController + IGetUserLicenseQuery getUserLicenseQuery, + IReinstateSubscriptionCommand reinstateSubscriptionCommand, + IUpdatePaymentMethodCommand updatePaymentMethodCommand, + IUpdatePremiumStorageCommand updatePremiumStorageCommand, + IUpgradePremiumToOrganizationCommand upgradePremiumToOrganizationCommand) : BaseBillingController { [HttpGet("credit")] [InjectUser] @@ -66,7 +75,6 @@ public class AccountBillingVNextController( } [HttpPost("subscription")] - [RequireFeature(FeatureFlagKeys.PM24996ImplementUpgradeFromFreeDialog)] [InjectUser] public async Task CreateSubscriptionAsync( [BindNever] User user, @@ -77,4 +85,55 @@ public class AccountBillingVNextController( user, paymentMethod, billingAddress, additionalStorageGb); return Handle(result); } + + [HttpGet("license")] + [InjectUser] + public async Task GetLicenseAsync( + [BindNever] User user) + { + var response = await getUserLicenseQuery.Run(user); + return TypedResults.Ok(response); + } + + [HttpGet("subscription")] + [RequireFeature(FeatureFlagKeys.PM29594_UpdateIndividualSubscriptionPage)] + [InjectUser] + public async Task GetSubscriptionAsync( + [BindNever] User user) + { + var subscription = await getBitwardenSubscriptionQuery.Run(user); + return TypedResults.Ok(subscription); + } + + [HttpPost("subscription/reinstate")] + [RequireFeature(FeatureFlagKeys.PM29594_UpdateIndividualSubscriptionPage)] + [InjectUser] + public async Task ReinstateSubscriptionAsync( + [BindNever] User user) + { + var result = await reinstateSubscriptionCommand.Run(user); + return Handle(result); + } + + [HttpPut("subscription/storage")] + [RequireFeature(FeatureFlagKeys.PM29594_UpdateIndividualSubscriptionPage)] + [InjectUser] + public async Task UpdateSubscriptionStorageAsync( + [BindNever] User user, + [FromBody] StorageUpdateRequest request) + { + var result = await updatePremiumStorageCommand.Run(user, request.AdditionalStorageGb); + return Handle(result); + } + + [HttpPost("upgrade")] + [InjectUser] + public async Task UpgradePremiumToOrganizationAsync( + [BindNever] User user, + [FromBody] UpgradePremiumToOrganizationRequest request) + { + var (organizationName, key, planType) = request.ToDomain(); + var result = await upgradePremiumToOrganizationCommand.Run(user, organizationName, key, planType); + return Handle(result); + } } diff --git a/src/Api/Billing/Controllers/VNext/SelfHostedAccountBillingVNextController.cs b/src/Api/Billing/Controllers/VNext/SelfHostedAccountBillingVNextController.cs index b86f29bdbc..ccc1dd9734 100644 --- a/src/Api/Billing/Controllers/VNext/SelfHostedAccountBillingVNextController.cs +++ b/src/Api/Billing/Controllers/VNext/SelfHostedAccountBillingVNextController.cs @@ -1,7 +1,6 @@ using Bit.Api.Billing.Attributes; using Bit.Api.Billing.Models.Requests.Premium; using Bit.Api.Utilities; -using Bit.Core; using Bit.Core.Billing.Models.Business; using Bit.Core.Billing.Premium.Commands; using Bit.Core.Entities; @@ -20,7 +19,6 @@ public class SelfHostedAccountBillingVNextController( ICreatePremiumSelfHostedSubscriptionCommand createPremiumSelfHostedSubscriptionCommand) : BaseBillingController { [HttpPost("license")] - [RequireFeature(FeatureFlagKeys.PM24996ImplementUpgradeFromFreeDialog)] [InjectUser] public async Task UploadLicenseAsync( [BindNever] User user, diff --git a/src/Api/Billing/Models/Requests/Premium/UpgradePremiumToOrganizationRequest.cs b/src/Api/Billing/Models/Requests/Premium/UpgradePremiumToOrganizationRequest.cs new file mode 100644 index 0000000000..14375efc78 --- /dev/null +++ b/src/Api/Billing/Models/Requests/Premium/UpgradePremiumToOrganizationRequest.cs @@ -0,0 +1,37 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; +using Bit.Core.Billing.Enums; + +namespace Bit.Api.Billing.Models.Requests.Premium; + +public class UpgradePremiumToOrganizationRequest +{ + [Required] + public string OrganizationName { get; set; } = null!; + + [Required] + public string Key { get; set; } = null!; + + [Required] + [JsonConverter(typeof(JsonStringEnumConverter))] + public ProductTierType Tier { get; set; } + + [Required] + [JsonConverter(typeof(JsonStringEnumConverter))] + public PlanCadenceType Cadence { get; set; } + + private PlanType PlanType => + Tier switch + { + ProductTierType.Families => PlanType.FamiliesAnnually, + ProductTierType.Teams => Cadence == PlanCadenceType.Monthly + ? PlanType.TeamsMonthly + : PlanType.TeamsAnnually, + ProductTierType.Enterprise => Cadence == PlanCadenceType.Monthly + ? PlanType.EnterpriseMonthly + : PlanType.EnterpriseAnnually, + _ => throw new InvalidOperationException("Cannot upgrade to an Organization subscription that isn't Families, Teams or Enterprise.") + }; + + public (string OrganizationName, string Key, PlanType PlanType) ToDomain() => (OrganizationName, Key, PlanType); +} diff --git a/src/Api/Billing/Models/Requests/Storage/StorageUpdateRequest.cs b/src/Api/Billing/Models/Requests/Storage/StorageUpdateRequest.cs new file mode 100644 index 0000000000..fe0c8e9e17 --- /dev/null +++ b/src/Api/Billing/Models/Requests/Storage/StorageUpdateRequest.cs @@ -0,0 +1,34 @@ +using System.ComponentModel.DataAnnotations; + +namespace Bit.Api.Billing.Models.Requests.Storage; + +/// +/// Request model for updating storage allocation on a user's premium subscription. +/// Allows for both increasing and decreasing storage in an idempotent manner. +/// +public class StorageUpdateRequest : IValidatableObject +{ + /// + /// The additional storage in GB beyond the base storage. + /// Must be between 0 and the maximum allowed (minus base storage). + /// + [Required] + public short AdditionalStorageGb { get; set; } + + public IEnumerable Validate(ValidationContext validationContext) + { + if (AdditionalStorageGb < 0) + { + yield return new ValidationResult( + "Additional storage cannot be negative.", + [nameof(AdditionalStorageGb)]); + } + + if (AdditionalStorageGb > 99) + { + yield return new ValidationResult( + "Maximum additional storage is 99 GB.", + [nameof(AdditionalStorageGb)]); + } + } +} diff --git a/src/Api/AdminConsole/Controllers/OrganizationIntegrationConfigurationController.cs b/src/Api/Dirt/Controllers/OrganizationIntegrationConfigurationController.cs similarity index 92% rename from src/Api/AdminConsole/Controllers/OrganizationIntegrationConfigurationController.cs rename to src/Api/Dirt/Controllers/OrganizationIntegrationConfigurationController.cs index f172a23529..4296aa3edd 100644 --- a/src/Api/AdminConsole/Controllers/OrganizationIntegrationConfigurationController.cs +++ b/src/Api/Dirt/Controllers/OrganizationIntegrationConfigurationController.cs @@ -1,12 +1,12 @@ -using Bit.Api.AdminConsole.Models.Request.Organizations; -using Bit.Api.AdminConsole.Models.Response.Organizations; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +using Bit.Api.Dirt.Models.Request; +using Bit.Api.Dirt.Models.Response; using Bit.Core.Context; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; using Bit.Core.Exceptions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace Bit.Api.AdminConsole.Controllers; +namespace Bit.Api.Dirt.Controllers; [Route("organizations/{organizationId:guid}/integrations/{integrationId:guid}/configurations")] [Authorize("Application")] diff --git a/src/Api/AdminConsole/Controllers/OrganizationIntegrationController.cs b/src/Api/Dirt/Controllers/OrganizationIntegrationController.cs similarity index 91% rename from src/Api/AdminConsole/Controllers/OrganizationIntegrationController.cs rename to src/Api/Dirt/Controllers/OrganizationIntegrationController.cs index b82fe3dfa8..960db648c2 100644 --- a/src/Api/AdminConsole/Controllers/OrganizationIntegrationController.cs +++ b/src/Api/Dirt/Controllers/OrganizationIntegrationController.cs @@ -1,12 +1,12 @@ -using Bit.Api.AdminConsole.Models.Request.Organizations; -using Bit.Api.AdminConsole.Models.Response.Organizations; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Api.Dirt.Models.Request; +using Bit.Api.Dirt.Models.Response; using Bit.Core.Context; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; using Bit.Core.Exceptions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace Bit.Api.AdminConsole.Controllers; +namespace Bit.Api.Dirt.Controllers; [Route("organizations/{organizationId:guid}/integrations")] [Authorize("Application")] diff --git a/src/Api/AdminConsole/Controllers/SlackIntegrationController.cs b/src/Api/Dirt/Controllers/SlackIntegrationController.cs similarity index 94% rename from src/Api/AdminConsole/Controllers/SlackIntegrationController.cs rename to src/Api/Dirt/Controllers/SlackIntegrationController.cs index 7b53f73f81..e98ed0d3fa 100644 --- a/src/Api/AdminConsole/Controllers/SlackIntegrationController.cs +++ b/src/Api/Dirt/Controllers/SlackIntegrationController.cs @@ -1,16 +1,16 @@ using System.Text.Json; -using Bit.Api.AdminConsole.Models.Response.Organizations; -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Api.Dirt.Models.Response; using Bit.Core.Context; -using Bit.Core.Enums; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Repositories; +using Bit.Core.Dirt.Services; using Bit.Core.Exceptions; -using Bit.Core.Repositories; -using Bit.Core.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace Bit.Api.AdminConsole.Controllers; +namespace Bit.Api.Dirt.Controllers; [Route("organizations")] [Authorize("Application")] diff --git a/src/Api/AdminConsole/Controllers/TeamsIntegrationController.cs b/src/Api/Dirt/Controllers/TeamsIntegrationController.cs similarity index 94% rename from src/Api/AdminConsole/Controllers/TeamsIntegrationController.cs rename to src/Api/Dirt/Controllers/TeamsIntegrationController.cs index 36d107bbcc..b2bd55017c 100644 --- a/src/Api/AdminConsole/Controllers/TeamsIntegrationController.cs +++ b/src/Api/Dirt/Controllers/TeamsIntegrationController.cs @@ -1,18 +1,18 @@ using System.Text.Json; -using Bit.Api.AdminConsole.Models.Response.Organizations; -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Api.Dirt.Models.Response; using Bit.Core.Context; -using Bit.Core.Enums; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Repositories; +using Bit.Core.Dirt.Services; using Bit.Core.Exceptions; -using Bit.Core.Repositories; -using Bit.Core.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; -namespace Bit.Api.AdminConsole.Controllers; +namespace Bit.Api.Dirt.Controllers; [Route("organizations")] [Authorize("Application")] diff --git a/src/Api/AdminConsole/Models/Request/Organizations/OrganizationIntegrationConfigurationRequestModel.cs b/src/Api/Dirt/Models/Request/OrganizationIntegrationConfigurationRequestModel.cs similarity index 86% rename from src/Api/AdminConsole/Models/Request/Organizations/OrganizationIntegrationConfigurationRequestModel.cs rename to src/Api/Dirt/Models/Request/OrganizationIntegrationConfigurationRequestModel.cs index 9341392d68..e918bea2d6 100644 --- a/src/Api/AdminConsole/Models/Request/Organizations/OrganizationIntegrationConfigurationRequestModel.cs +++ b/src/Api/Dirt/Models/Request/OrganizationIntegrationConfigurationRequestModel.cs @@ -1,8 +1,7 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; using Bit.Core.Enums; - -namespace Bit.Api.AdminConsole.Models.Request.Organizations; +namespace Bit.Api.Dirt.Models.Request; public class OrganizationIntegrationConfigurationRequestModel { diff --git a/src/Api/AdminConsole/Models/Request/Organizations/OrgnizationIntegrationRequestModel.cs b/src/Api/Dirt/Models/Request/OrganizationIntegrationRequestModel.cs similarity index 94% rename from src/Api/AdminConsole/Models/Request/Organizations/OrgnizationIntegrationRequestModel.cs rename to src/Api/Dirt/Models/Request/OrganizationIntegrationRequestModel.cs index 668afe70bf..259671bd66 100644 --- a/src/Api/AdminConsole/Models/Request/Organizations/OrgnizationIntegrationRequestModel.cs +++ b/src/Api/Dirt/Models/Request/OrganizationIntegrationRequestModel.cs @@ -1,10 +1,10 @@ using System.ComponentModel.DataAnnotations; using System.Text.Json; -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; -using Bit.Core.Enums; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; -namespace Bit.Api.AdminConsole.Models.Request.Organizations; +namespace Bit.Api.Dirt.Models.Request; public class OrganizationIntegrationRequestModel : IValidatableObject { diff --git a/src/Api/AdminConsole/Models/Response/Organizations/OrganizationIntegrationConfigurationResponseModel.cs b/src/Api/Dirt/Models/Response/OrganizationIntegrationConfigurationResponseModel.cs similarity index 90% rename from src/Api/AdminConsole/Models/Response/Organizations/OrganizationIntegrationConfigurationResponseModel.cs rename to src/Api/Dirt/Models/Response/OrganizationIntegrationConfigurationResponseModel.cs index d070375d88..62a3aea405 100644 --- a/src/Api/AdminConsole/Models/Response/Organizations/OrganizationIntegrationConfigurationResponseModel.cs +++ b/src/Api/Dirt/Models/Response/OrganizationIntegrationConfigurationResponseModel.cs @@ -1,8 +1,8 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; using Bit.Core.Enums; using Bit.Core.Models.Api; -namespace Bit.Api.AdminConsole.Models.Response.Organizations; +namespace Bit.Api.Dirt.Models.Response; public class OrganizationIntegrationConfigurationResponseModel : ResponseModel { diff --git a/src/Api/AdminConsole/Models/Response/Organizations/OrganizationIntegrationResponseModel.cs b/src/Api/Dirt/Models/Response/OrganizationIntegrationResponseModel.cs similarity index 93% rename from src/Api/AdminConsole/Models/Response/Organizations/OrganizationIntegrationResponseModel.cs rename to src/Api/Dirt/Models/Response/OrganizationIntegrationResponseModel.cs index 0c31e07bef..60e885fe82 100644 --- a/src/Api/AdminConsole/Models/Response/Organizations/OrganizationIntegrationResponseModel.cs +++ b/src/Api/Dirt/Models/Response/OrganizationIntegrationResponseModel.cs @@ -1,10 +1,10 @@ using System.Text.Json; -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; -using Bit.Core.Enums; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Bit.Core.Models.Api; -namespace Bit.Api.AdminConsole.Models.Response.Organizations; +namespace Bit.Api.Dirt.Models.Response; public class OrganizationIntegrationResponseModel : ResponseModel { diff --git a/src/Api/KeyManagement/Models/Requests/MasterPasswordAuthenticationDataRequestModel.cs b/src/Api/KeyManagement/Models/Requests/MasterPasswordAuthenticationDataRequestModel.cs index d65dc8fcb7..4f70a1135f 100644 --- a/src/Api/KeyManagement/Models/Requests/MasterPasswordAuthenticationDataRequestModel.cs +++ b/src/Api/KeyManagement/Models/Requests/MasterPasswordAuthenticationDataRequestModel.cs @@ -6,8 +6,11 @@ namespace Bit.Api.KeyManagement.Models.Requests; public class MasterPasswordAuthenticationDataRequestModel { public required KdfRequestModel Kdf { get; init; } + [Required] public required string MasterPasswordAuthenticationHash { get; init; } - [StringLength(256)] public required string Salt { get; init; } + [Required] + [StringLength(256)] + public required string Salt { get; init; } public MasterPasswordAuthenticationData ToData() { diff --git a/src/Api/KeyManagement/Models/Requests/MasterPasswordUnlockDataRequestModel.cs b/src/Api/KeyManagement/Models/Requests/MasterPasswordUnlockDataRequestModel.cs index ce7a2b343f..e1d7863cae 100644 --- a/src/Api/KeyManagement/Models/Requests/MasterPasswordUnlockDataRequestModel.cs +++ b/src/Api/KeyManagement/Models/Requests/MasterPasswordUnlockDataRequestModel.cs @@ -7,8 +7,12 @@ namespace Bit.Api.KeyManagement.Models.Requests; public class MasterPasswordUnlockDataRequestModel { public required KdfRequestModel Kdf { get; init; } - [EncryptedString] public required string MasterKeyWrappedUserKey { get; init; } - [StringLength(256)] public required string Salt { get; init; } + [Required] + [EncryptedString] + public required string MasterKeyWrappedUserKey { get; init; } + [Required] + [StringLength(256)] + public required string Salt { get; init; } public MasterPasswordUnlockData ToData() { diff --git a/src/Api/KeyManagement/Validators/SendRotationValidator.cs b/src/Api/KeyManagement/Validators/SendRotationValidator.cs index 10a5d996b7..a781ab99ee 100644 --- a/src/Api/KeyManagement/Validators/SendRotationValidator.cs +++ b/src/Api/KeyManagement/Validators/SendRotationValidator.cs @@ -44,7 +44,7 @@ public class SendRotationValidator : IRotationValidator(); diff --git a/src/Api/Tools/Controllers/OrganizationExportController.cs b/src/Api/Tools/Controllers/OrganizationExportController.cs index dd039bc4a5..578220075a 100644 --- a/src/Api/Tools/Controllers/OrganizationExportController.cs +++ b/src/Api/Tools/Controllers/OrganizationExportController.cs @@ -1,6 +1,5 @@ using Bit.Api.Tools.Authorization; using Bit.Api.Tools.Models.Response; -using Bit.Core; using Bit.Core.AdminConsole.OrganizationFeatures.Shared.Authorization; using Bit.Core.Exceptions; using Bit.Core.Repositories; @@ -21,7 +20,6 @@ public class OrganizationExportController : Controller private readonly IAuthorizationService _authorizationService; private readonly IOrganizationCiphersQuery _organizationCiphersQuery; private readonly ICollectionRepository _collectionRepository; - private readonly IFeatureService _featureService; public OrganizationExportController( IUserService userService, @@ -36,7 +34,6 @@ public class OrganizationExportController : Controller _authorizationService = authorizationService; _organizationCiphersQuery = organizationCiphersQuery; _collectionRepository = collectionRepository; - _featureService = featureService; } [HttpGet("export")] @@ -46,33 +43,20 @@ public class OrganizationExportController : Controller VaultExportOperations.ExportWholeVault); var canExportManaged = await _authorizationService.AuthorizeAsync(User, new OrganizationScope(organizationId), VaultExportOperations.ExportManagedCollections); - var createDefaultLocationEnabled = _featureService.IsEnabled(FeatureFlagKeys.CreateDefaultLocation); if (canExportAll.Succeeded) { - if (createDefaultLocationEnabled) - { - var allOrganizationCiphers = - await _organizationCiphersQuery.GetAllOrganizationCiphersExcludingDefaultUserCollections( - organizationId); + var allOrganizationCiphers = + await _organizationCiphersQuery.GetAllOrganizationCiphersExcludingDefaultUserCollections( + organizationId); - var allCollections = await _collectionRepository - .GetManySharedCollectionsByOrganizationIdAsync( - organizationId); + var allCollections = await _collectionRepository + .GetManySharedCollectionsByOrganizationIdAsync( + organizationId); - return Ok(new OrganizationExportResponseModel(allOrganizationCiphers, allCollections, - _globalSettings)); - } - else - { - var allOrganizationCiphers = await _organizationCiphersQuery.GetAllOrganizationCiphers(organizationId); - - var allCollections = await _collectionRepository.GetManyByOrganizationIdAsync(organizationId); - - return Ok(new OrganizationExportResponseModel(allOrganizationCiphers, allCollections, - _globalSettings)); - } + return Ok(new OrganizationExportResponseModel(allOrganizationCiphers, allCollections, + _globalSettings)); } if (canExportManaged.Succeeded) diff --git a/src/Api/Tools/Controllers/SendsController.cs b/src/Api/Tools/Controllers/SendsController.cs index c54a9b90c9..f9f71d076d 100644 --- a/src/Api/Tools/Controllers/SendsController.cs +++ b/src/Api/Tools/Controllers/SendsController.cs @@ -1,21 +1,21 @@ -// FIXME: Update this file to be null safe and then delete the line below -#nullable disable - -using System.Text.Json; +using System.Text.Json; using Azure.Messaging.EventGrid; using Bit.Api.Models.Response; using Bit.Api.Tools.Models.Request; using Bit.Api.Tools.Models.Response; using Bit.Api.Utilities; using Bit.Core; +using Bit.Core.Auth.Identity; +using Bit.Core.Auth.UserFeatures.SendAccess; using Bit.Core.Exceptions; +using Bit.Core.Platform.Push; using Bit.Core.Services; -using Bit.Core.Settings; using Bit.Core.Tools.Enums; using Bit.Core.Tools.Models.Data; using Bit.Core.Tools.Repositories; using Bit.Core.Tools.SendFeatures; using Bit.Core.Tools.SendFeatures.Commands.Interfaces; +using Bit.Core.Tools.SendFeatures.Queries.Interfaces; using Bit.Core.Tools.Services; using Bit.Core.Utilities; using Microsoft.AspNetCore.Authorization; @@ -24,7 +24,6 @@ using Microsoft.AspNetCore.Mvc; namespace Bit.Api.Tools.Controllers; [Route("sends")] -[Authorize("Application")] public class SendsController : Controller { private readonly ISendRepository _sendRepository; @@ -33,8 +32,10 @@ public class SendsController : Controller private readonly ISendFileStorageService _sendFileStorageService; private readonly IAnonymousSendCommand _anonymousSendCommand; private readonly INonAnonymousSendCommand _nonAnonymousSendCommand; + private readonly ISendOwnerQuery _sendOwnerQuery; private readonly ILogger _logger; - private readonly GlobalSettings _globalSettings; + private readonly IFeatureService _featureService; + private readonly IPushNotificationService _pushNotificationService; public SendsController( ISendRepository sendRepository, @@ -42,21 +43,26 @@ public class SendsController : Controller ISendAuthorizationService sendAuthorizationService, IAnonymousSendCommand anonymousSendCommand, INonAnonymousSendCommand nonAnonymousSendCommand, + ISendOwnerQuery sendOwnerQuery, ISendFileStorageService sendFileStorageService, ILogger logger, - GlobalSettings globalSettings) + IFeatureService featureService, + IPushNotificationService pushNotificationService) { _sendRepository = sendRepository; _userService = userService; _sendAuthorizationService = sendAuthorizationService; _anonymousSendCommand = anonymousSendCommand; _nonAnonymousSendCommand = nonAnonymousSendCommand; + _sendOwnerQuery = sendOwnerQuery; _sendFileStorageService = sendFileStorageService; _logger = logger; - _globalSettings = globalSettings; + _featureService = featureService; + _pushNotificationService = pushNotificationService; } #region Anonymous endpoints + [AllowAnonymous] [HttpPost("access/{id}")] public async Task Access(string id, [FromBody] SendAccessRequestModel model) @@ -70,28 +76,44 @@ public class SendsController : Controller var guid = new Guid(CoreHelpers.Base64UrlDecode(id)); var send = await _sendRepository.GetByIdAsync(guid); - SendAccessResult sendAuthResult = + + if (send == null) + { + throw new BadRequestException("Could not locate send"); + } + + /* This guard can be removed once feature flag is retired*/ + var sendEmailOtpEnabled = _featureService.IsEnabled(FeatureFlagKeys.SendEmailOTP); + if (sendEmailOtpEnabled && send.AuthType == AuthType.Email && send.Emails is not null) + { + return new UnauthorizedResult(); + } + + var sendAuthResult = await _sendAuthorizationService.AccessAsync(send, model.Password); if (sendAuthResult.Equals(SendAccessResult.PasswordRequired)) { return new UnauthorizedResult(); } + if (sendAuthResult.Equals(SendAccessResult.PasswordInvalid)) { await Task.Delay(2000); throw new BadRequestException("Invalid password."); } + if (sendAuthResult.Equals(SendAccessResult.Denied)) { throw new NotFoundException(); } - var sendResponse = new SendAccessResponseModel(send, _globalSettings); + var sendResponse = new SendAccessResponseModel(send); if (send.UserId.HasValue && !send.HideEmail.GetValueOrDefault()) { var creator = await _userService.GetUserByIdAsync(send.UserId.Value); sendResponse.CreatorIdentifier = creator.Email; } + return new ObjectResult(sendResponse); } @@ -115,6 +137,13 @@ public class SendsController : Controller throw new BadRequestException("Could not locate send"); } + /* This guard can be removed once feature flag is retired*/ + var sendEmailOtpEnabled = _featureService.IsEnabled(FeatureFlagKeys.SendEmailOTP); + if (sendEmailOtpEnabled && send.AuthType == AuthType.Email && send.Emails is not null) + { + return new UnauthorizedResult(); + } + var (url, result) = await _anonymousSendCommand.GetSendFileDownloadUrlAsync(send, fileId, model.Password); @@ -122,21 +151,19 @@ public class SendsController : Controller { return new UnauthorizedResult(); } + if (result.Equals(SendAccessResult.PasswordInvalid)) { await Task.Delay(2000); throw new BadRequestException("Invalid password."); } + if (result.Equals(SendAccessResult.Denied)) { throw new NotFoundException(); } - return new ObjectResult(new SendFileDownloadDataResponseModel() - { - Id = fileId, - Url = url, - }); + return new ObjectResult(new SendFileDownloadDataResponseModel() { Id = fileId, Url = url, }); } [AllowAnonymous] @@ -150,7 +177,8 @@ public class SendsController : Controller { try { - var blobName = eventGridEvent.Subject.Split($"{AzureSendFileStorageService.FilesContainerName}/blobs/")[1]; + var blobName = + eventGridEvent.Subject.Split($"{AzureSendFileStorageService.FilesContainerName}/blobs/")[1]; var sendId = AzureSendFileStorageService.SendIdFromBlobName(blobName); var send = await _sendRepository.GetByIdAsync(new Guid(sendId)); if (send == null) @@ -159,6 +187,7 @@ public class SendsController : Controller { await azureSendFileStorageService.DeleteBlobAsync(blobName); } + return; } @@ -166,7 +195,8 @@ public class SendsController : Controller } catch (Exception e) { - _logger.LogError(e, "Uncaught exception occurred while handling event grid event: {Event}", JsonSerializer.Serialize(eventGridEvent)); + _logger.LogError(e, "Uncaught exception occurred while handling event grid event: {Event}", + JsonSerializer.Serialize(eventGridEvent)); return; } } @@ -178,38 +208,98 @@ public class SendsController : Controller #region Non-anonymous endpoints + [Authorize(Policies.Application)] [HttpGet("{id}")] public async Task Get(string id) { - var userId = _userService.GetProperUserId(User).Value; - var send = await _sendRepository.GetByIdAsync(new Guid(id)); - if (send == null || send.UserId != userId) + var sendId = new Guid(id); + var send = await _sendOwnerQuery.Get(sendId, User); + return new SendResponseModel(send); + } + + [Authorize(Policies.Application)] + [HttpGet("")] + public async Task> GetAll() + { + var sends = await _sendOwnerQuery.GetOwned(User); + var responses = sends.Select(s => new SendResponseModel(s)); + var result = new ListResponseModel(responses); + + return result; + } + + [Authorize(Policy = Policies.Send)] + // [RequireFeature(FeatureFlagKeys.SendEmailOTP)] /* Uncomment once client fallback re-try logic is added */ + [HttpPost("access/")] + public async Task AccessUsingAuth() + { + var guid = User.GetSendId(); + var send = await _sendRepository.GetByIdAsync(guid); + if (send == null) + { + throw new BadRequestException("Could not locate send"); + } + if (send.MaxAccessCount.GetValueOrDefault(int.MaxValue) <= send.AccessCount || + send.ExpirationDate.GetValueOrDefault(DateTime.MaxValue) < DateTime.UtcNow || send.Disabled || + send.DeletionDate < DateTime.UtcNow) { throw new NotFoundException(); } - return new SendResponseModel(send, _globalSettings); + var sendResponse = new SendAccessResponseModel(send); + if (send.UserId.HasValue && !send.HideEmail.GetValueOrDefault()) + { + var creator = await _userService.GetUserByIdAsync(send.UserId.Value); + sendResponse.CreatorIdentifier = creator.Email; + } + + send.AccessCount++; + await _sendRepository.ReplaceAsync(send); + await _pushNotificationService.PushSyncSendUpdateAsync(send); + + return new ObjectResult(sendResponse); } - [HttpGet("")] - public async Task> GetAll() + [Authorize(Policy = Policies.Send)] + // [RequireFeature(FeatureFlagKeys.SendEmailOTP)] /* Uncomment once client fallback re-try logic is added */ + [HttpPost("access/file/{fileId}")] + public async Task GetSendFileDownloadDataUsingAuth(string fileId) { - var userId = _userService.GetProperUserId(User).Value; - var sends = await _sendRepository.GetManyByUserIdAsync(userId); - var responses = sends.Select(s => new SendResponseModel(s, _globalSettings)); - return new ListResponseModel(responses); + var sendId = User.GetSendId(); + var send = await _sendRepository.GetByIdAsync(sendId); + + if (send == null) + { + throw new BadRequestException("Could not locate send"); + } + if (send.MaxAccessCount.GetValueOrDefault(int.MaxValue) <= send.AccessCount || + send.ExpirationDate.GetValueOrDefault(DateTime.MaxValue) < DateTime.UtcNow || send.Disabled || + send.DeletionDate < DateTime.UtcNow) + { + throw new NotFoundException(); + } + + var url = await _sendFileStorageService.GetSendFileDownloadUrlAsync(send, fileId); + + send.AccessCount++; + await _sendRepository.ReplaceAsync(send); + await _pushNotificationService.PushSyncSendUpdateAsync(send); + + return new ObjectResult(new SendFileDownloadDataResponseModel() { Id = fileId, Url = url }); } + [Authorize(Policies.Application)] [HttpPost("")] public async Task Post([FromBody] SendRequestModel model) { model.ValidateCreation(); - var userId = _userService.GetProperUserId(User).Value; + var userId = _userService.GetProperUserId(User) ?? throw new InvalidOperationException("User ID not found"); var send = model.ToSend(userId, _sendAuthorizationService); await _nonAnonymousSendCommand.SaveSendAsync(send); - return new SendResponseModel(send, _globalSettings); + return new SendResponseModel(send); } + [Authorize(Policies.Application)] [HttpPost("file/v2")] public async Task PostFile([FromBody] SendRequestModel model) { @@ -229,27 +319,28 @@ public class SendsController : Controller } model.ValidateCreation(); - var userId = _userService.GetProperUserId(User).Value; + var userId = _userService.GetProperUserId(User) ?? throw new InvalidOperationException("User ID not found"); var (send, data) = model.ToSend(userId, model.File.FileName, _sendAuthorizationService); var uploadUrl = await _nonAnonymousSendCommand.SaveFileSendAsync(send, data, model.FileLength.Value); return new SendFileUploadDataResponseModel { Url = uploadUrl, FileUploadType = _sendFileStorageService.FileUploadType, - SendResponse = new SendResponseModel(send, _globalSettings) + SendResponse = new SendResponseModel(send) }; } + [Authorize(Policies.Application)] [HttpGet("{id}/file/{fileId}")] public async Task RenewFileUpload(string id, string fileId) { - var userId = _userService.GetProperUserId(User).Value; + var userId = _userService.GetProperUserId(User) ?? throw new InvalidOperationException("User ID not found"); var sendId = new Guid(id); var send = await _sendRepository.GetByIdAsync(sendId); - var fileData = JsonSerializer.Deserialize(send?.Data); + var fileData = JsonSerializer.Deserialize(send?.Data ?? string.Empty); if (send == null || send.Type != SendType.File || (send.UserId.HasValue && send.UserId.Value != userId) || - !send.UserId.HasValue || fileData.Id != fileId || fileData.Validated) + !send.UserId.HasValue || fileData?.Id != fileId || fileData.Validated) { // Not found if Send isn't found, user doesn't have access, request is faulty, // or we've already validated the file. This last is to emulate create-only blob permissions for Azure @@ -260,62 +351,95 @@ public class SendsController : Controller { Url = await _sendFileStorageService.GetSendFileUploadUrlAsync(send, fileId), FileUploadType = _sendFileStorageService.FileUploadType, - SendResponse = new SendResponseModel(send, _globalSettings), + SendResponse = new SendResponseModel(send), }; } + [Authorize(Policies.Application)] [HttpPost("{id}/file/{fileId}")] [SelfHosted(SelfHostedOnly = true)] [RequestSizeLimit(Constants.FileSize501mb)] [DisableFormValueModelBinding] public async Task PostFileForExistingSend(string id, string fileId) { - if (!Request?.ContentType.Contains("multipart/") ?? true) + if (!Request?.ContentType?.Contains("multipart/") ?? true) { throw new BadRequestException("Invalid content."); } var send = await _sendRepository.GetByIdAsync(new Guid(id)); + if (send == null) + { + throw new BadRequestException("Could not locate send"); + } + await Request.GetFileAsync(async (stream) => { await _nonAnonymousSendCommand.UploadFileToExistingSendAsync(stream, send); }); } + [Authorize(Policies.Application)] [HttpPut("{id}")] public async Task Put(string id, [FromBody] SendRequestModel model) { model.ValidateEdit(); - var userId = _userService.GetProperUserId(User).Value; + var userId = _userService.GetProperUserId(User) ?? throw new InvalidOperationException("User ID not found"); var send = await _sendRepository.GetByIdAsync(new Guid(id)); if (send == null || send.UserId != userId) { throw new NotFoundException(); } - await _nonAnonymousSendCommand.SaveSendAsync(model.ToSend(send, _sendAuthorizationService)); - return new SendResponseModel(send, _globalSettings); + await _nonAnonymousSendCommand.SaveSendAsync(model.UpdateSend(send, _sendAuthorizationService)); + return new SendResponseModel(send); } + [Authorize(Policies.Application)] [HttpPut("{id}/remove-password")] public async Task PutRemovePassword(string id) { - var userId = _userService.GetProperUserId(User).Value; + var userId = _userService.GetProperUserId(User) ?? throw new InvalidOperationException("User ID not found"); var send = await _sendRepository.GetByIdAsync(new Guid(id)); if (send == null || send.UserId != userId) { throw new NotFoundException(); } + // This endpoint exists because PUT preserves existing Password/Emails when not provided. + // This allows clients to update other fields without re-submitting sensitive auth data. send.Password = null; + send.AuthType = AuthType.None; await _nonAnonymousSendCommand.SaveSendAsync(send); - return new SendResponseModel(send, _globalSettings); + return new SendResponseModel(send); } + // Removes ALL authentication (email or password) if any is present + [Authorize(Policies.Application)] + [HttpPut("{id}/remove-auth")] + public async Task PutRemoveAuth(string id) + { + var userId = _userService.GetProperUserId(User) ?? throw new InvalidOperationException("User ID not found"); + var send = await _sendRepository.GetByIdAsync(new Guid(id)); + if (send == null || send.UserId != userId) + { + throw new NotFoundException(); + } + + // This endpoint exists because PUT preserves existing Password/Emails when not provided. + // This allows clients to update other fields without re-submitting sensitive auth data. + send.Password = null; + send.Emails = null; + send.AuthType = AuthType.None; + await _nonAnonymousSendCommand.SaveSendAsync(send); + return new SendResponseModel(send); + } + + [Authorize(Policies.Application)] [HttpDelete("{id}")] public async Task Delete(string id) { - var userId = _userService.GetProperUserId(User).Value; + var userId = _userService.GetProperUserId(User) ?? throw new InvalidOperationException("User ID not found"); var send = await _sendRepository.GetByIdAsync(new Guid(id)); if (send == null || send.UserId != userId) { diff --git a/src/Api/Tools/Models/Request/SendRequestModel.cs b/src/Api/Tools/Models/Request/SendRequestModel.cs index a38257db60..f3308dbd5a 100644 --- a/src/Api/Tools/Models/Request/SendRequestModel.cs +++ b/src/Api/Tools/Models/Request/SendRequestModel.cs @@ -3,6 +3,7 @@ using System.ComponentModel.DataAnnotations; using System.Text.Json; +using Bit.Api.Tools.Utilities; using Bit.Core.Exceptions; using Bit.Core.Tools.Entities; using Bit.Core.Tools.Enums; @@ -10,35 +11,119 @@ using Bit.Core.Tools.Models.Data; using Bit.Core.Tools.Services; using Bit.Core.Utilities; +using static System.StringSplitOptions; + namespace Bit.Api.Tools.Models.Request; +/// +/// A send request issued by a Bitwarden client +/// public class SendRequestModel { + /// + /// Indicates whether the send contains text or file data. + /// public SendType Type { get; set; } + + /// + /// Specifies the authentication method required to access this Send. + /// + public AuthType? AuthType { get; set; } + + /// + /// Estimated length of the file accompanying the send. when + /// is . + /// public long? FileLength { get; set; } = null; + + /// + /// Label for the send. + /// [EncryptedString] [EncryptedStringLength(1000)] public string Name { get; set; } + + /// + /// Notes for the send. This is only visible to the owner of the send. + /// [EncryptedString] [EncryptedStringLength(1000)] public string Notes { get; set; } + + /// + /// A base64-encoded byte array containing the Send's encryption key. This key is + /// also provided to send recipients in the Send's URL. + /// [Required] [EncryptedString] [EncryptedStringLength(1000)] public string Key { get; set; } + + /// + /// The maximum number of times a send can be accessed before it expires. + /// When this value is , there is no limit. + /// [Range(1, int.MaxValue)] public int? MaxAccessCount { get; set; } + + /// + /// The date after which a send cannot be accessed. When this value is + /// , there is no expiration date. + /// public DateTime? ExpirationDate { get; set; } + + /// + /// The date after which a send may be automatically deleted from the server. + /// When this is , the send may be deleted after it has + /// exceeded the global send timeout limit. + /// [Required] public DateTime? DeletionDate { get; set; } + + /// + /// Contains file metadata uploaded with the send. + /// The file content is uploaded separately. + /// public SendFileModel File { get; set; } + + /// + /// Contains text data uploaded with the send. + /// public SendTextModel Text { get; set; } + + /// + /// Base64-encoded byte array of a password hash that grants access to the send. + /// Mutually exclusive with . + /// [StringLength(1000)] public string Password { get; set; } + + /// + /// Comma-separated list of emails that may access the send using OTP + /// authentication. Mutually exclusive with . + /// + [StringLength(4000)] + public string Emails { get; set; } + + /// + /// When , send access is disabled. + /// Defaults to . + /// [Required] public bool? Disabled { get; set; } + + /// + /// When send access hides the user's email address + /// and displays a confirmation message instead. Defaults to . + /// public bool? HideEmail { get; set; } + /// + /// Transforms the request into a send object. + /// + /// The user that owns the send. + /// Hashes the send password. + /// The send object public Send ToSend(Guid userId, ISendAuthorizationService sendAuthorizationService) { var send = new Send @@ -46,12 +131,21 @@ public class SendRequestModel Type = Type, UserId = (Guid?)userId }; - ToSend(send, sendAuthorizationService); + send = UpdateSend(send, sendAuthorizationService); return send; } + /// + /// Transforms the request into a send object and file data. + /// + /// The user that owns the send. + /// Name of the file uploaded with the send. + /// Hashes the send password. + /// The send object and file data. public (Send, SendFileData) ToSend(Guid userId, string fileName, ISendAuthorizationService sendAuthorizationService) { + // FIXME: This method does two things: creates a send and a send file data. + // It should only do one thing. var send = ToSendBase(new Send { Type = Type, @@ -61,7 +155,13 @@ public class SendRequestModel return (send, data); } - public Send ToSend(Send existingSend, ISendAuthorizationService sendAuthorizationService) + /// + /// Update a send object with request content + /// + /// The send to update + /// Hashes the send password. + /// The send object + public Send UpdateSend(Send existingSend, ISendAuthorizationService sendAuthorizationService) { existingSend = ToSendBase(existingSend, sendAuthorizationService); switch (existingSend.Type) @@ -81,6 +181,12 @@ public class SendRequestModel return existingSend; } + /// + /// Validates that the request is internally consistent for send creation. + /// + /// + /// Thrown when the send's expiration date has already expired. + /// public void ValidateCreation() { var now = DateTime.UtcNow; @@ -94,6 +200,13 @@ public class SendRequestModel ValidateEdit(); } + /// + /// Validates that the request is internally consistent for send administration. + /// + /// + /// Thrown when the send's deletion date has already expired or when its + /// expiration occurs after its deletion. + /// public void ValidateEdit() { var now = DateTime.UtcNow; @@ -134,12 +247,30 @@ public class SendRequestModel existingSend.ExpirationDate = ExpirationDate; existingSend.DeletionDate = DeletionDate.Value; existingSend.MaxAccessCount = MaxAccessCount; - if (!string.IsNullOrWhiteSpace(Password)) + + if (!string.IsNullOrWhiteSpace(Emails)) + { + // normalize encoding + var emails = Emails.Split(',', RemoveEmptyEntries | TrimEntries); + existingSend.Emails = string.Join(",", emails); + existingSend.Password = null; + existingSend.AuthType = Core.Tools.Enums.AuthType.Email; + } + else if (!string.IsNullOrWhiteSpace(Password)) { existingSend.Password = authorizationService.HashPassword(Password); + existingSend.Emails = null; + existingSend.AuthType = Core.Tools.Enums.AuthType.Password; } + else + { + // Neither Password nor Emails provided - preserve existing values and infer AuthType + existingSend.AuthType = SendUtilities.InferAuthType(existingSend); + } + existingSend.Disabled = Disabled.GetValueOrDefault(); existingSend.HideEmail = HideEmail.GetValueOrDefault(); + return existingSend; } @@ -149,8 +280,15 @@ public class SendRequestModel } } +/// +/// A send request issued by a Bitwarden client +/// public class SendWithIdRequestModel : SendRequestModel { + /// + /// Identifies the send. When this is , the client is requesting + /// a new send. + /// [Required] public Guid? Id { get; set; } } diff --git a/src/Api/Tools/Models/Response/SendAccessResponseModel.cs b/src/Api/Tools/Models/Response/SendAccessResponseModel.cs index b544862fcd..b722dd5fff 100644 --- a/src/Api/Tools/Models/Response/SendAccessResponseModel.cs +++ b/src/Api/Tools/Models/Response/SendAccessResponseModel.cs @@ -3,7 +3,6 @@ using System.Text.Json; using Bit.Core.Models.Api; -using Bit.Core.Settings; using Bit.Core.Tools.Entities; using Bit.Core.Tools.Enums; using Bit.Core.Tools.Models.Data; @@ -11,9 +10,22 @@ using Bit.Core.Utilities; namespace Bit.Api.Tools.Models.Response; +/// +/// A response issued to a Bitwarden client in response to access operations. +/// public class SendAccessResponseModel : ResponseModel { - public SendAccessResponseModel(Send send, GlobalSettings globalSettings) + /// + /// Instantiates a send access response model + /// + /// Content to transmit to the client. + /// + /// Thrown when is + /// + /// + /// Thrown when has an invalid . + /// + public SendAccessResponseModel(Send send) : base("send-access") { if (send == null) @@ -23,6 +35,7 @@ public class SendAccessResponseModel : ResponseModel Id = CoreHelpers.Base64UrlEncode(send.Id.ToByteArray()); Type = send.Type; + AuthType = send.AuthType; SendData sendData; switch (send.Type) @@ -45,11 +58,52 @@ public class SendAccessResponseModel : ResponseModel ExpirationDate = send.ExpirationDate; } + /// + /// Identifies the send in a send URL + /// public string Id { get; set; } + + /// + /// Indicates whether the send contains text or file data. + /// public SendType Type { get; set; } + + /// + /// Specifies the authentication method required to access this Send. + /// + public AuthType? AuthType { get; set; } + + /// + /// Label for the send. This is only visible to the owner of the send. + /// + /// + /// This field contains a base64-encoded byte array. The array contains + /// the E2E-encrypted encrypted content. + /// public string Name { get; set; } + + /// + /// Describes the file attached to the send. + /// + /// + /// File content is downloaded separately using + /// + /// public SendFileModel File { get; set; } + + /// + /// Contains text data uploaded with the send. + /// public SendTextModel Text { get; set; } + + /// + /// The date after which a send cannot be accessed. When this value is + /// , there is no expiration date. + /// public DateTime? ExpirationDate { get; set; } + + /// + /// Indicates the person that created the send to the accessor. + /// public string CreatorIdentifier { get; set; } } diff --git a/src/Api/Tools/Models/Response/SendResponseModel.cs b/src/Api/Tools/Models/Response/SendResponseModel.cs index 17a70cd2db..f7f6b683d6 100644 --- a/src/Api/Tools/Models/Response/SendResponseModel.cs +++ b/src/Api/Tools/Models/Response/SendResponseModel.cs @@ -2,8 +2,8 @@ #nullable disable using System.Text.Json; +using Bit.Api.Tools.Utilities; using Bit.Core.Models.Api; -using Bit.Core.Settings; using Bit.Core.Tools.Entities; using Bit.Core.Tools.Enums; using Bit.Core.Tools.Models.Data; @@ -11,9 +11,23 @@ using Bit.Core.Utilities; namespace Bit.Api.Tools.Models.Response; +/// +/// A response issued to a Bitwarden client in response to ownership operations. +/// +/// public class SendResponseModel : ResponseModel { - public SendResponseModel(Send send, GlobalSettings globalSettings) + /// + /// Instantiates a send response model + /// + /// Content to transmit to the client. + /// + /// Thrown when is + /// + /// + /// Thrown when has an invalid . + /// + public SendResponseModel(Send send) : base("send") { if (send == null) @@ -24,6 +38,7 @@ public class SendResponseModel : ResponseModel Id = send.Id; AccessId = CoreHelpers.Base64UrlEncode(send.Id.ToByteArray()); Type = send.Type; + AuthType = send.AuthType ?? SendUtilities.InferAuthType(send); Key = send.Key; MaxAccessCount = send.MaxAccessCount; AccessCount = send.AccessCount; @@ -31,6 +46,7 @@ public class SendResponseModel : ResponseModel ExpirationDate = send.ExpirationDate; DeletionDate = send.DeletionDate; Password = send.Password; + Emails = send.Emails; Disabled = send.Disabled; HideEmail = send.HideEmail.GetValueOrDefault(); @@ -55,20 +71,113 @@ public class SendResponseModel : ResponseModel Notes = sendData.Notes; } + /// + /// Identifies the send to its owner + /// public Guid Id { get; set; } + + /// + /// Identifies the send in a send URL + /// public string AccessId { get; set; } + + /// + /// Indicates whether the send contains text or file data. + /// public SendType Type { get; set; } + + /// + /// Specifies the authentication method required to access this Send. + /// + public AuthType? AuthType { get; set; } + + /// + /// Label for the send. + /// + /// + /// This field contains a base64-encoded byte array. The array contains + /// the E2E-encrypted encrypted content. + /// public string Name { get; set; } + + /// + /// Notes for the send. This is only visible to the owner of the send. + /// This field is encrypted. + /// + /// + /// This field contains a base64-encoded byte array. The array contains + /// the E2E-encrypted encrypted content. + /// public string Notes { get; set; } + + /// + /// Contains file metadata uploaded with the send. + /// The file content is uploaded separately. + /// public SendFileModel File { get; set; } + + /// + /// Contains text data uploaded with the send. + /// public SendTextModel Text { get; set; } + + /// + /// A base64-encoded byte array containing the Send's encryption key. + /// It's also provided to send recipients in the Send's URL. + /// + /// + /// This field contains a base64-encoded byte array. The array contains + /// the E2E-encrypted content. + /// public string Key { get; set; } + + /// + /// The maximum number of times a send can be accessed before it expires. + /// When this value is , there is no limit. + /// public int? MaxAccessCount { get; set; } + + /// + /// The number of times a send has been accessed since it was created. + /// public int AccessCount { get; set; } + + /// + /// Base64-encoded byte array of a password hash that grants access to the send. + /// Mutually exclusive with . + /// public string Password { get; set; } + + /// + /// Comma-separated list of emails that may access the send using OTP + /// authentication. Mutually exclusive with . + /// + public string Emails { get; set; } + + /// + /// When , send access is disabled. + /// public bool Disabled { get; set; } + + /// + /// The last time this send's data changed. + /// public DateTime RevisionDate { get; set; } + + /// + /// The date after which a send cannot be accessed. When this value is + /// , there is no expiration date. + /// public DateTime? ExpirationDate { get; set; } + + /// + /// The date after which a send may be automatically deleted from the server. + /// public DateTime DeletionDate { get; set; } + + /// + /// When send access hides the user's email address + /// and displays a confirmation message instead. + /// public bool HideEmail { get; set; } } diff --git a/src/Api/Tools/Utilities/InferAuthType.cs b/src/Api/Tools/Utilities/InferAuthType.cs new file mode 100644 index 0000000000..785fde1ec9 --- /dev/null +++ b/src/Api/Tools/Utilities/InferAuthType.cs @@ -0,0 +1,23 @@ +namespace Bit.Api.Tools.Utilities; + +using Bit.Core.Tools.Entities; +using Bit.Core.Tools.Enums; + +public class SendUtilities +{ + public static AuthType InferAuthType(Send send) + { + if (!string.IsNullOrWhiteSpace(send.Password)) + { + return AuthType.Password; + } + + if (!string.IsNullOrWhiteSpace(send.Emails)) + { + return AuthType.Email; + } + + return AuthType.None; + } +} + diff --git a/src/Api/Vault/Controllers/CiphersController.cs b/src/Api/Vault/Controllers/CiphersController.cs index 6a506cc01f..9e107b491d 100644 --- a/src/Api/Vault/Controllers/CiphersController.cs +++ b/src/Api/Vault/Controllers/CiphersController.cs @@ -10,7 +10,6 @@ using Bit.Api.Utilities; using Bit.Api.Vault.Models.Request; using Bit.Api.Vault.Models.Response; using Bit.Core; -using Bit.Core.AdminConsole.Services; using Bit.Core.Context; using Bit.Core.Entities; using Bit.Core.Enums; @@ -43,7 +42,6 @@ public class CiphersController : Controller private readonly ICipherService _cipherService; private readonly IUserService _userService; private readonly IAttachmentStorageService _attachmentStorageService; - private readonly IProviderService _providerService; private readonly ICurrentContext _currentContext; private readonly ILogger _logger; private readonly GlobalSettings _globalSettings; @@ -52,7 +50,6 @@ public class CiphersController : Controller private readonly ICollectionRepository _collectionRepository; private readonly IArchiveCiphersCommand _archiveCiphersCommand; private readonly IUnarchiveCiphersCommand _unarchiveCiphersCommand; - private readonly IFeatureService _featureService; public CiphersController( ICipherRepository cipherRepository, @@ -60,7 +57,6 @@ public class CiphersController : Controller ICipherService cipherService, IUserService userService, IAttachmentStorageService attachmentStorageService, - IProviderService providerService, ICurrentContext currentContext, ILogger logger, GlobalSettings globalSettings, @@ -68,15 +64,13 @@ public class CiphersController : Controller IApplicationCacheService applicationCacheService, ICollectionRepository collectionRepository, IArchiveCiphersCommand archiveCiphersCommand, - IUnarchiveCiphersCommand unarchiveCiphersCommand, - IFeatureService featureService) + IUnarchiveCiphersCommand unarchiveCiphersCommand) { _cipherRepository = cipherRepository; _collectionCipherRepository = collectionCipherRepository; _cipherService = cipherService; _userService = userService; _attachmentStorageService = attachmentStorageService; - _providerService = providerService; _currentContext = currentContext; _logger = logger; _globalSettings = globalSettings; @@ -85,7 +79,6 @@ public class CiphersController : Controller _collectionRepository = collectionRepository; _archiveCiphersCommand = archiveCiphersCommand; _unarchiveCiphersCommand = unarchiveCiphersCommand; - _featureService = featureService; } [HttpGet("{id}")] @@ -344,8 +337,7 @@ public class CiphersController : Controller throw new NotFoundException(); } - bool excludeDefaultUserCollections = _featureService.IsEnabled(FeatureFlagKeys.CreateDefaultLocation) && !includeMemberItems; - var allOrganizationCiphers = excludeDefaultUserCollections + var allOrganizationCiphers = !includeMemberItems ? await _organizationCiphersQuery.GetAllOrganizationCiphersExcludingDefaultUserCollections(organizationId) : @@ -911,7 +903,7 @@ public class CiphersController : Controller [HttpPut("{id}/archive")] [RequireFeature(FeatureFlagKeys.ArchiveVaultItems)] - public async Task PutArchive(Guid id) + public async Task PutArchive(Guid id) { var userId = _userService.GetProperUserId(User).Value; @@ -922,12 +914,16 @@ public class CiphersController : Controller throw new BadRequestException("Cipher was not archived. Ensure the provided ID is correct and you have permission to archive it."); } - return new CipherMiniResponseModel(archivedCipherOrganizationDetails.First(), _globalSettings, archivedCipherOrganizationDetails.First().OrganizationUseTotp); + return new CipherResponseModel(archivedCipherOrganizationDetails.First(), + await _userService.GetUserByPrincipalAsync(User), + await _applicationCacheService.GetOrganizationAbilitiesAsync(), + _globalSettings + ); } [HttpPut("archive")] [RequireFeature(FeatureFlagKeys.ArchiveVaultItems)] - public async Task> PutArchiveMany([FromBody] CipherBulkArchiveRequestModel model) + public async Task> PutArchiveMany([FromBody] CipherBulkArchiveRequestModel model) { if (!_globalSettings.SelfHosted && model.Ids.Count() > 500) { @@ -935,6 +931,7 @@ public class CiphersController : Controller } var userId = _userService.GetProperUserId(User).Value; + var user = await _userService.GetUserByPrincipalAsync(User); var cipherIdsToArchive = new HashSet(model.Ids); @@ -945,9 +942,14 @@ public class CiphersController : Controller throw new BadRequestException("No ciphers were archived. Ensure the provided IDs are correct and you have permission to archive them."); } - var responses = archivedCiphers.Select(c => new CipherMiniResponseModel(c, _globalSettings, c.OrganizationUseTotp)); + var organizationAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); + var responses = archivedCiphers.Select(c => new CipherResponseModel(c, + user, + organizationAbilities, + _globalSettings + )); - return new ListResponseModel(responses); + return new ListResponseModel(responses); } [HttpDelete("{id}")] @@ -1109,7 +1111,7 @@ public class CiphersController : Controller [HttpPut("{id}/unarchive")] [RequireFeature(FeatureFlagKeys.ArchiveVaultItems)] - public async Task PutUnarchive(Guid id) + public async Task PutUnarchive(Guid id) { var userId = _userService.GetProperUserId(User).Value; @@ -1120,12 +1122,16 @@ public class CiphersController : Controller throw new BadRequestException("Cipher was not unarchived. Ensure the provided ID is correct and you have permission to archive it."); } - return new CipherMiniResponseModel(unarchivedCipherDetails.First(), _globalSettings, unarchivedCipherDetails.First().OrganizationUseTotp); + return new CipherResponseModel(unarchivedCipherDetails.First(), + await _userService.GetUserByPrincipalAsync(User), + await _applicationCacheService.GetOrganizationAbilitiesAsync(), + _globalSettings + ); } [HttpPut("unarchive")] [RequireFeature(FeatureFlagKeys.ArchiveVaultItems)] - public async Task> PutUnarchiveMany([FromBody] CipherBulkUnarchiveRequestModel model) + public async Task> PutUnarchiveMany([FromBody] CipherBulkUnarchiveRequestModel model) { if (!_globalSettings.SelfHosted && model.Ids.Count() > 500) { @@ -1133,6 +1139,8 @@ public class CiphersController : Controller } var userId = _userService.GetProperUserId(User).Value; + var user = await _userService.GetUserByPrincipalAsync(User); + var organizationAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync(); var cipherIdsToUnarchive = new HashSet(model.Ids); @@ -1143,9 +1151,9 @@ public class CiphersController : Controller throw new BadRequestException("Ciphers were not unarchived. Ensure the provided ID is correct and you have permission to archive it."); } - var responses = unarchivedCipherOrganizationDetails.Select(c => new CipherMiniResponseModel(c, _globalSettings, c.OrganizationUseTotp)); + var responses = unarchivedCipherOrganizationDetails.Select(c => new CipherResponseModel(c, user, organizationAbilities, _globalSettings)); - return new ListResponseModel(responses); + return new ListResponseModel(responses); } [HttpPut("{id}/restore")] diff --git a/src/Api/Vault/Models/Request/CipherRequestModel.cs b/src/Api/Vault/Models/Request/CipherRequestModel.cs index 18a1aec559..9a2c279a28 100644 --- a/src/Api/Vault/Models/Request/CipherRequestModel.cs +++ b/src/Api/Vault/Models/Request/CipherRequestModel.cs @@ -80,6 +80,7 @@ public class CipherRequestModel { existingCipher.FolderId = string.IsNullOrWhiteSpace(FolderId) ? null : (Guid?)new Guid(FolderId); existingCipher.Favorite = Favorite; + existingCipher.ArchivedDate = ArchivedDate; ToCipher(existingCipher); return existingCipher; } @@ -127,9 +128,9 @@ public class CipherRequestModel var userIdKey = userId.HasValue ? userId.ToString().ToUpperInvariant() : null; existingCipher.Reprompt = Reprompt; existingCipher.Key = Key; - existingCipher.ArchivedDate = ArchivedDate; existingCipher.Folders = UpdateUserSpecificJsonField(existingCipher.Folders, userIdKey, FolderId); existingCipher.Favorites = UpdateUserSpecificJsonField(existingCipher.Favorites, userIdKey, Favorite); + existingCipher.Archives = UpdateUserSpecificJsonField(existingCipher.Archives, userIdKey, ArchivedDate); var hasAttachments2 = (Attachments2?.Count ?? 0) > 0; var hasAttachments = (Attachments?.Count ?? 0) > 0; diff --git a/src/Api/Vault/Models/Response/CipherResponseModel.cs b/src/Api/Vault/Models/Response/CipherResponseModel.cs index dfacc1a551..ac11eb3cd3 100644 --- a/src/Api/Vault/Models/Response/CipherResponseModel.cs +++ b/src/Api/Vault/Models/Response/CipherResponseModel.cs @@ -70,7 +70,6 @@ public class CipherMiniResponseModel : ResponseModel DeletedDate = cipher.DeletedDate; Reprompt = cipher.Reprompt.GetValueOrDefault(CipherRepromptType.None); Key = cipher.Key; - ArchivedDate = cipher.ArchivedDate; } public Guid Id { get; set; } @@ -111,7 +110,6 @@ public class CipherMiniResponseModel : ResponseModel public DateTime? DeletedDate { get; set; } public CipherRepromptType Reprompt { get; set; } public string Key { get; set; } - public DateTime? ArchivedDate { get; set; } } public class CipherResponseModel : CipherMiniResponseModel @@ -127,6 +125,7 @@ public class CipherResponseModel : CipherMiniResponseModel FolderId = cipher.FolderId; Favorite = cipher.Favorite; Edit = cipher.Edit; + ArchivedDate = cipher.ArchivedDate; ViewPassword = cipher.ViewPassword; Permissions = new CipherPermissionsResponseModel(user, cipher, organizationAbilities); } @@ -135,6 +134,7 @@ public class CipherResponseModel : CipherMiniResponseModel public bool Favorite { get; set; } public bool Edit { get; set; } public bool ViewPassword { get; set; } + public DateTime? ArchivedDate { get; set; } public CipherPermissionsResponseModel Permissions { get; set; } } diff --git a/src/Api/Vault/Models/Response/SyncResponseModel.cs b/src/Api/Vault/Models/Response/SyncResponseModel.cs index 1981ac834e..c965320b94 100644 --- a/src/Api/Vault/Models/Response/SyncResponseModel.cs +++ b/src/Api/Vault/Models/Response/SyncResponseModel.cs @@ -56,7 +56,7 @@ public class SyncResponseModel() : ResponseModel("sync") c => new CollectionDetailsResponseModel(c)) ?? new List(); Domains = excludeDomains ? null : new DomainsResponseModel(user, false); Policies = policies?.Select(p => new PolicyResponseModel(p)) ?? new List(); - Sends = sends.Select(s => new SendResponseModel(s, globalSettings)); + Sends = sends.Select(s => new SendResponseModel(s)); UserDecryption = new UserDecryptionResponseModel { MasterPasswordUnlock = user.HasMasterPassword() diff --git a/src/Billing/Billing.csproj b/src/Billing/Billing.csproj index 69999dc795..27ee9a7ce3 100644 --- a/src/Billing/Billing.csproj +++ b/src/Billing/Billing.csproj @@ -3,12 +3,13 @@ bitwarden-Billing + + $(WarningsNotAsErrors);CA1305 false - false false diff --git a/src/Billing/Jobs/ReconcileAdditionalStorageJob.cs b/src/Billing/Jobs/ReconcileAdditionalStorageJob.cs index 312ed3122b..7dfc44069c 100644 --- a/src/Billing/Jobs/ReconcileAdditionalStorageJob.cs +++ b/src/Billing/Jobs/ReconcileAdditionalStorageJob.cs @@ -4,6 +4,7 @@ using Bit.Billing.Services; using Bit.Core; using Bit.Core.Billing.Constants; using Bit.Core.Jobs; +using Bit.Core.Repositories; using Bit.Core.Services; using Quartz; using Stripe; @@ -13,12 +14,23 @@ namespace Bit.Billing.Jobs; public class ReconcileAdditionalStorageJob( IStripeFacade stripeFacade, ILogger logger, - IFeatureService featureService) : BaseJob(logger) + IFeatureService featureService, + IUserRepository userRepository, + IOrganizationRepository organizationRepository, + IStripeEventUtilityService stripeEventUtilityService) : BaseJob(logger) { private const string _storageGbMonthlyPriceId = "storage-gb-monthly"; private const string _storageGbAnnuallyPriceId = "storage-gb-annually"; private const string _personalStorageGbAnnuallyPriceId = "personal-storage-gb-annually"; private const int _storageGbToRemove = 4; + private const short _includedStorageGb = 5; + + public enum SubscriptionPlanTier + { + Personal, + Organization, + Unknown + } protected override async Task ExecuteJobAsync(IJobExecutionContext context) { @@ -34,6 +46,7 @@ public class ReconcileAdditionalStorageJob( var subscriptionsFound = 0; var subscriptionsUpdated = 0; var subscriptionsWithErrors = 0; + var databaseUpdatesFailed = 0; var failures = new List(); logger.LogInformation("Starting ReconcileAdditionalStorageJob (live mode: {LiveMode})", liveMode); @@ -51,11 +64,13 @@ public class ReconcileAdditionalStorageJob( { logger.LogWarning( "Job cancelled!! Exiting. Progress at time of cancellation: Subscriptions found: {SubscriptionsFound}, " + - "Updated: {SubscriptionsUpdated}, Errors: {SubscriptionsWithErrors}{Failures}", + "Stripe updates: {StripeUpdates}, Database updates: {DatabaseFailed} failed, " + + "Errors: {SubscriptionsWithErrors}{Failures}", subscriptionsFound, liveMode ? subscriptionsUpdated : $"(In live mode, would have updated) {subscriptionsUpdated}", + databaseUpdatesFailed, subscriptionsWithErrors, failures.Count > 0 ? $", Failures: {Environment.NewLine}{string.Join(Environment.NewLine, failures)}" @@ -99,20 +114,68 @@ public class ReconcileAdditionalStorageJob( subscriptionsUpdated++; - if (!liveMode) + // Now, prepare the database update so we can log details out if not in live mode + var (organizationId, userId, _) = stripeEventUtilityService.GetIdsFromMetadata(subscription.Metadata ?? new Dictionary()); + var subscriptionPlanTier = DetermineSubscriptionPlanTier(userId, organizationId); + + if (subscriptionPlanTier == SubscriptionPlanTier.Unknown) { - logger.LogInformation( - "Not live mode (dry-run): Would have updated subscription {SubscriptionId} with item changes: {NewLine}{UpdateOptions}", - subscription.Id, - Environment.NewLine, - JsonSerializer.Serialize(updateOptions)); + logger.LogError( + "Cannot determine subscription plan tier for {SubscriptionId}. Skipping subscription. ", + subscription.Id); + subscriptionsWithErrors++; continue; } + var entityId = + subscriptionPlanTier switch + { + SubscriptionPlanTier.Personal => userId!.Value, + SubscriptionPlanTier.Organization => organizationId!.Value, + _ => throw new ArgumentOutOfRangeException(nameof(subscriptionPlanTier), subscriptionPlanTier, null) + }; + + // Calculate new MaxStorageGb + var currentStorageQuantity = GetCurrentStorageQuantityFromSubscription(subscription, priceId); + var newMaxStorageGb = CalculateNewMaxStorageGb(currentStorageQuantity, updateOptions); + + if (!liveMode) + { + logger.LogInformation( + "Not live mode (dry-run): Would have updated subscription {SubscriptionId} with item changes: {NewLine}{UpdateOptions}" + + "{NewLine2}And would have updated database record tier: {Tier} to new MaxStorageGb: {MaxStorageGb}", + subscription.Id, + Environment.NewLine, + JsonSerializer.Serialize(updateOptions), + Environment.NewLine, + subscriptionPlanTier, + newMaxStorageGb); + continue; + } + + // Live mode enabled - continue with updates to stripe and database try { await stripeFacade.UpdateSubscription(subscription.Id, updateOptions); - logger.LogInformation("Successfully updated subscription: {SubscriptionId}", subscription.Id); + logger.LogInformation("Successfully updated Stripe subscription: {SubscriptionId}", subscription.Id); + + logger.LogInformation( + "Updating MaxStorageGb in database for subscription {SubscriptionId} ({Type}): New MaxStorageGb: {MaxStorage}", + subscription.Id, + subscriptionPlanTier, + newMaxStorageGb); + + var dbUpdateSuccess = await UpdateDatabaseMaxStorageAsync( + subscriptionPlanTier, + entityId, + newMaxStorageGb, + subscription.Id); + + if (!dbUpdateSuccess) + { + databaseUpdatesFailed++; + failures.Add($"Subscription {subscription.Id}: Database update failed"); + } } catch (Exception ex) { @@ -125,12 +188,14 @@ public class ReconcileAdditionalStorageJob( } logger.LogInformation( - "ReconcileAdditionalStorageJob completed. Subscriptions found: {SubscriptionsFound}, " + - "Updated: {SubscriptionsUpdated}, Errors: {SubscriptionsWithErrors}{Failures}", + "ReconcileAdditionalStorageJob FINISHED. Subscriptions found: {SubscriptionsFound}, " + + "Subscriptions updated: {SubscriptionsUpdated}, Database failures: {DatabaseFailed}, " + + "Total Subscriptions With Errors: {SubscriptionsWithErrors}{Failures}", subscriptionsFound, liveMode ? subscriptionsUpdated : $"(In live mode, would have updated) {subscriptionsUpdated}", + databaseUpdatesFailed, subscriptionsWithErrors, failures.Count > 0 ? $", Failures: {Environment.NewLine}{string.Join(Environment.NewLine, failures)}" @@ -182,6 +247,117 @@ public class ReconcileAdditionalStorageJob( return hasUpdates ? updateOptions : null; } + public SubscriptionPlanTier DetermineSubscriptionPlanTier( + Guid? userId, + Guid? organizationId) + { + return userId.HasValue + ? SubscriptionPlanTier.Personal + : organizationId.HasValue + ? SubscriptionPlanTier.Organization + : SubscriptionPlanTier.Unknown; + } + + public long GetCurrentStorageQuantityFromSubscription( + Subscription subscription, + string storagePriceId) + { + return subscription.Items?.Data?.FirstOrDefault(item => item?.Price?.Id == storagePriceId)?.Quantity ?? 0; + } + + public short CalculateNewMaxStorageGb( + long currentQuantity, + SubscriptionUpdateOptions? updateOptions) + { + if (updateOptions?.Items == null) + { + return (short)(_includedStorageGb + currentQuantity); + } + + // If the update marks item as deleted, new quantity is whatever the base storage gb + if (updateOptions.Items.Any(i => i.Deleted == true)) + { + return _includedStorageGb; + } + + // If the update has a new quantity, use it to calculate the new max + var updatedItem = updateOptions.Items.FirstOrDefault(i => i.Quantity.HasValue); + if (updatedItem?.Quantity != null) + { + return (short)(_includedStorageGb + updatedItem.Quantity.Value); + } + + // Otherwise, no change + return (short)(_includedStorageGb + currentQuantity); + } + + public async Task UpdateDatabaseMaxStorageAsync( + SubscriptionPlanTier subscriptionPlanTier, + Guid entityId, + short newMaxStorageGb, + string subscriptionId) + { + try + { + switch (subscriptionPlanTier) + { + case SubscriptionPlanTier.Personal: + { + var user = await userRepository.GetByIdAsync(entityId); + if (user == null) + { + logger.LogError( + "User not found for subscription {SubscriptionId}. Database not updated.", + subscriptionId); + return false; + } + + user.MaxStorageGb = newMaxStorageGb; + await userRepository.ReplaceAsync(user); + + logger.LogInformation( + "Successfully updated User {UserId} MaxStorageGb to {MaxStorageGb} for subscription {SubscriptionId}", + user.Id, + newMaxStorageGb, + subscriptionId); + return true; + } + case SubscriptionPlanTier.Organization: + { + var organization = await organizationRepository.GetByIdAsync(entityId); + if (organization == null) + { + logger.LogError( + "Organization not found for subscription {SubscriptionId}. Database not updated.", + subscriptionId); + return false; + } + + organization.MaxStorageGb = newMaxStorageGb; + await organizationRepository.ReplaceAsync(organization); + + logger.LogInformation( + "Successfully updated Organization {OrganizationId} MaxStorageGb to {MaxStorageGb} for subscription {SubscriptionId}", + organization.Id, + newMaxStorageGb, + subscriptionId); + return true; + } + case SubscriptionPlanTier.Unknown: + default: + return false; + } + } + catch (Exception ex) + { + logger.LogError(ex, + "Failed to update database MaxStorageGb for subscription {SubscriptionId} (Plan Tier: {SubscriptionType})", + subscriptionId, + subscriptionPlanTier); + return false; + } + } + public static ITrigger GetTrigger() { return TriggerBuilder.Create() diff --git a/src/Billing/Models/PayPalIPNTransactionModel.cs b/src/Billing/Models/PayPalIPNTransactionModel.cs index 34db5fdd04..240fa5ab76 100644 --- a/src/Billing/Models/PayPalIPNTransactionModel.cs +++ b/src/Billing/Models/PayPalIPNTransactionModel.cs @@ -43,7 +43,7 @@ public class PayPalIPNTransactionModel var merchantGross = Extract(data, "mc_gross"); if (!string.IsNullOrEmpty(merchantGross)) { - MerchantGross = decimal.Parse(merchantGross); + MerchantGross = decimal.Parse(merchantGross, CultureInfo.InvariantCulture); } MerchantCurrency = Extract(data, "mc_currency"); diff --git a/src/Billing/Services/Implementations/InvoiceCreatedHandler.cs b/src/Billing/Services/Implementations/InvoiceCreatedHandler.cs index 101b0e26b9..0db498844e 100644 --- a/src/Billing/Services/Implementations/InvoiceCreatedHandler.cs +++ b/src/Billing/Services/Implementations/InvoiceCreatedHandler.cs @@ -1,12 +1,13 @@ using Bit.Core.Billing.Constants; +using Bit.Core.Services; using Event = Stripe.Event; namespace Bit.Billing.Services.Implementations; public class InvoiceCreatedHandler( + IBraintreeService braintreeService, ILogger logger, IStripeEventService stripeEventService, - IStripeEventUtilityService stripeEventUtilityService, IProviderEventService providerEventService) : IInvoiceCreatedHandler { @@ -29,9 +30,9 @@ public class InvoiceCreatedHandler( { try { - var invoice = await stripeEventService.GetInvoice(parsedEvent, true, ["customer"]); + var invoice = await stripeEventService.GetInvoice(parsedEvent, true, ["customer", "parent.subscription_details.subscription"]); - var usingPayPal = invoice.Customer?.Metadata.ContainsKey("btCustomerId") ?? false; + var usingPayPal = invoice.Customer.Metadata.ContainsKey("btCustomerId"); if (usingPayPal && invoice is { @@ -39,13 +40,12 @@ public class InvoiceCreatedHandler( Status: not StripeConstants.InvoiceStatus.Paid, CollectionMethod: "charge_automatically", BillingReason: - "subscription_create" or "subscription_cycle" or "automatic_pending_invoice_item_invoice", - Parent.SubscriptionDetails: not null + Parent.SubscriptionDetails.Subscription: not null }) { - await stripeEventUtilityService.AttemptToPayInvoiceAsync(invoice); + await braintreeService.PayInvoice(invoice.Parent.SubscriptionDetails.Subscription, invoice); } } catch (Exception exception) diff --git a/src/Billing/Startup.cs b/src/Billing/Startup.cs index 30f4f5f562..f5f98bfd53 100644 --- a/src/Billing/Startup.cs +++ b/src/Billing/Startup.cs @@ -48,6 +48,7 @@ public class Startup // Repositories services.AddDatabaseRepositories(globalSettings); + services.AddTestPlayIdTracking(globalSettings); // PayPal IPN Client services.AddHttpClient(); diff --git a/src/Core/AdminConsole/Entities/Organization.cs b/src/Core/AdminConsole/Entities/Organization.cs index 338b150de6..266779d574 100644 --- a/src/Core/AdminConsole/Entities/Organization.cs +++ b/src/Core/AdminConsole/Entities/Organization.cs @@ -134,6 +134,11 @@ public class Organization : ITableObject, IStorableSubscriber, IRevisable /// public bool UseAutomaticUserConfirmation { get; set; } + /// + /// If set to true, disables Secrets Manager ads for users in the organization + /// + public bool UseDisableSmAdsForUsers { get; set; } + /// /// If set to true, the organization has phishing protection enabled. /// @@ -338,6 +343,7 @@ public class Organization : ITableObject, IStorableSubscriber, IRevisable UseRiskInsights = license.UseRiskInsights; UseOrganizationDomains = license.UseOrganizationDomains; UseAdminSponsoredFamilies = license.UseAdminSponsoredFamilies; + UseDisableSmAdsForUsers = license.UseDisableSmAdsForUsers; UseAutomaticUserConfirmation = license.UseAutomaticUserConfirmation; UsePhishingBlocker = license.UsePhishingBlocker; } diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogIntegration.cs b/src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogIntegration.cs deleted file mode 100644 index 8785a74896..0000000000 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogIntegration.cs +++ /dev/null @@ -1,3 +0,0 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; - -public record DatadogIntegration(string ApiKey, Uri Uri); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegration.cs b/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegration.cs deleted file mode 100644 index dc2733c889..0000000000 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegration.cs +++ /dev/null @@ -1,3 +0,0 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; - -public record SlackIntegration(string Token); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegrationConfiguration.cs b/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegrationConfiguration.cs deleted file mode 100644 index 5b4fae0c76..0000000000 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegrationConfiguration.cs +++ /dev/null @@ -1,3 +0,0 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; - -public record SlackIntegrationConfiguration(string ChannelId); diff --git a/src/Core/AdminConsole/Models/Data/IProfileOrganizationDetails.cs b/src/Core/AdminConsole/Models/Data/IProfileOrganizationDetails.cs index 0368678641..ed1d9e5f13 100644 --- a/src/Core/AdminConsole/Models/Data/IProfileOrganizationDetails.cs +++ b/src/Core/AdminConsole/Models/Data/IProfileOrganizationDetails.cs @@ -53,5 +53,7 @@ public interface IProfileOrganizationDetails bool UseAdminSponsoredFamilies { get; set; } bool UseOrganizationDomains { get; set; } bool UseAutomaticUserConfirmation { get; set; } + bool UseDisableSMAdsForUsers { get; set; } + bool UsePhishingBlocker { get; set; } } diff --git a/src/Core/AdminConsole/Models/Data/Organizations/OrganizationUsers/OrganizationUserOrganizationDetails.cs b/src/Core/AdminConsole/Models/Data/Organizations/OrganizationUsers/OrganizationUserOrganizationDetails.cs index 00b9280337..2a7c2cb628 100644 --- a/src/Core/AdminConsole/Models/Data/Organizations/OrganizationUsers/OrganizationUserOrganizationDetails.cs +++ b/src/Core/AdminConsole/Models/Data/Organizations/OrganizationUsers/OrganizationUserOrganizationDetails.cs @@ -65,5 +65,6 @@ public class OrganizationUserOrganizationDetails : IProfileOrganizationDetails public bool UseAdminSponsoredFamilies { get; set; } public bool? IsAdminInitiated { get; set; } public bool UseAutomaticUserConfirmation { get; set; } + public bool UseDisableSMAdsForUsers { get; set; } public bool UsePhishingBlocker { get; set; } } diff --git a/src/Core/AdminConsole/Models/Data/Organizations/SelfHostedOrganizationDetails.cs b/src/Core/AdminConsole/Models/Data/Organizations/SelfHostedOrganizationDetails.cs index 484320c271..5ec9dc255a 100644 --- a/src/Core/AdminConsole/Models/Data/Organizations/SelfHostedOrganizationDetails.cs +++ b/src/Core/AdminConsole/Models/Data/Organizations/SelfHostedOrganizationDetails.cs @@ -128,6 +128,7 @@ public class SelfHostedOrganizationDetails : Organization UseApi = UseApi, UseResetPassword = UseResetPassword, UseSecretsManager = UseSecretsManager, + UsePasswordManager = UsePasswordManager, SelfHost = SelfHost, UsersGetPremium = UsersGetPremium, UseCustomPermissions = UseCustomPermissions, @@ -154,7 +155,10 @@ public class SelfHostedOrganizationDetails : Organization Status = Status, UseRiskInsights = UseRiskInsights, UseAdminSponsoredFamilies = UseAdminSponsoredFamilies, + UseDisableSmAdsForUsers = UseDisableSmAdsForUsers, UsePhishingBlocker = UsePhishingBlocker, + UseOrganizationDomains = UseOrganizationDomains, + UseAutomaticUserConfirmation = UseAutomaticUserConfirmation, }; } } diff --git a/src/Core/AdminConsole/Models/Data/Provider/ProviderUserOrganizationDetails.cs b/src/Core/AdminConsole/Models/Data/Provider/ProviderUserOrganizationDetails.cs index dcec028dcc..69b17a9a80 100644 --- a/src/Core/AdminConsole/Models/Data/Provider/ProviderUserOrganizationDetails.cs +++ b/src/Core/AdminConsole/Models/Data/Provider/ProviderUserOrganizationDetails.cs @@ -56,5 +56,6 @@ public class ProviderUserOrganizationDetails : IProfileOrganizationDetails public string? SsoExternalId { get; set; } public string? Permissions { get; set; } public string? ResetPasswordKey { get; set; } + public bool UseDisableSMAdsForUsers { get; set; } public bool UsePhishingBlocker { get; set; } } diff --git a/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationBaseView.cs b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationBaseView.cs new file mode 100644 index 0000000000..f888496fe8 --- /dev/null +++ b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationBaseView.cs @@ -0,0 +1,12 @@ +using Bit.Core.Platform.Mail.Mailer; + +namespace Bit.Core.AdminConsole.Models.Mail.Mailer.OrganizationConfirmation; + +public abstract class OrganizationConfirmationBaseView : BaseMailView +{ + public required string OrganizationName { get; set; } + public required string TitleFirst { get; set; } + public required string TitleSecondBold { get; set; } + public required string TitleThird { get; set; } + public required string WebVaultUrl { get; set; } +} diff --git a/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationEnterpriseTeamsView.cs b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationEnterpriseTeamsView.cs new file mode 100644 index 0000000000..6a8a0e18fa --- /dev/null +++ b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationEnterpriseTeamsView.cs @@ -0,0 +1,12 @@ +using Bit.Core.Platform.Mail.Mailer; + +namespace Bit.Core.AdminConsole.Models.Mail.Mailer.OrganizationConfirmation; + +public class OrganizationConfirmationEnterpriseTeamsView : OrganizationConfirmationBaseView +{ +} + +public class OrganizationConfirmationEnterpriseTeams : BaseMail +{ + public override required string Subject { get; set; } +} diff --git a/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationEnterpriseTeamsView.html.hbs b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationEnterpriseTeamsView.html.hbs new file mode 100644 index 0000000000..3c8f498403 --- /dev/null +++ b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationEnterpriseTeamsView.html.hbs @@ -0,0 +1,814 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+ + + + + + + +
+ + + + + + + + +
+ + + + + +
+ + + + + + + +
+ + +
+ + + + + + + + + + + + + + + + + +
+ + + + + + + +
+ + + +
+ +
+ +

+ You can now share passwords with members of {{OrganizationName}}! +

+ +
+ + + + + + + +
+ + Log in + +
+ +
+ +
+ + + +
+ + + + + + + + + +
+ + + + + + + +
+ + + +
+ +
+ +
+ + +
+ +
+ + + + + +
+ + +
+ +
+ + + + + + + + + +
+ + + + + + + +
+ + + +
+ + + + + + + +
+ + +
+ + + + + + + + + +
+ +
As a member of {{OrganizationName}}:
+ +
+ +
+ + +
+ +
+ + + + + +
+ + + + + + + +
+ + +
+ + +
+ + + + + + + + + +
+ + + + + + + +
+ + Organization Icon + +
+ +
+ +
+ + + +
+ + + + + + + + + +
+ +
Your account is owned by {{OrganizationName}} and is subject to their security and management policies.
+ +
+ +
+ + +
+ + +
+ +
+ + + + + +
+ + + + + + + +
+ + +
+ + +
+ + + + + + + + + +
+ + + + + + + +
+ + Group Users Icon + +
+ +
+ +
+ + + +
+ + + + + + + + + + + + + +
+ +
You can easily access and share passwords with your team.
+ +
+ + + +
+ +
+ + +
+ + +
+ +
+ + + + + +
+ + + + + + + +
+ +
+ +
+ + + +
+ +
+ + + + + + + + + +
+ + + + + + + +
+ + + +
+ + + + + + + +
+ + +
+ + + + + + + + + +
+ +

+ Learn more about Bitwarden +

+ Find user guides, product documentation, and videos on the + Bitwarden Help Center.
+ +
+ +
+ + + +
+ + + + + + + + + +
+ +
+ + +
+ +
+ + + +
+ +
+ + + + + + + + + +
+ + + + + + + +
+ + +
+ + + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + +
+ +

+ © 2025 Bitwarden Inc. 1 N. Calle Cesar Chavez, Suite 102, Santa + Barbara, CA, USA +

+

+ Always confirm you are on a trusted Bitwarden domain before logging + in:
+ bitwarden.com | + Learn why we include this +

+ +
+ +
+ + +
+ +
+ + + + + +
+ + + diff --git a/src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-enterprise-teams.text.hbs b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationEnterpriseTeamsView.text.hbs similarity index 100% rename from src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-enterprise-teams.text.hbs rename to src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationEnterpriseTeamsView.text.hbs diff --git a/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationFamilyFreeView.cs b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationFamilyFreeView.cs new file mode 100644 index 0000000000..9228ec2208 --- /dev/null +++ b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationFamilyFreeView.cs @@ -0,0 +1,12 @@ +using Bit.Core.Platform.Mail.Mailer; + +namespace Bit.Core.AdminConsole.Models.Mail.Mailer.OrganizationConfirmation; + +public class OrganizationConfirmationFamilyFreeView : OrganizationConfirmationBaseView +{ +} + +public class OrganizationConfirmationFamilyFree : BaseMail +{ + public override required string Subject { get; set; } +} diff --git a/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationFamilyFreeView.html.hbs b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationFamilyFreeView.html.hbs new file mode 100644 index 0000000000..c0f838e0c7 --- /dev/null +++ b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationFamilyFreeView.html.hbs @@ -0,0 +1,983 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+ + + + + + + +
+ + + + + + + + +
+ + + + + +
+ + + + + + + +
+ + +
+ + + + + + + + + + + + + + + + + +
+ + + + + + + +
+ + + +
+ +
+ +

+ You can now share passwords with members of {{OrganizationName}}! +

+ +
+ + + + + + + +
+ + Log in + +
+ +
+ +
+ + + +
+ + + + + + + + + +
+ + + + + + + +
+ + + +
+ +
+ +
+ + +
+ +
+ + + + + +
+ + +
+ +
+ + + + + + + + + +
+ + + + + + + +
+ + + +
+ + + + + + + +
+ + +
+ + + + + + + + + +
+ +
As a member of {{OrganizationName}}:
+ +
+ +
+ + +
+ +
+ + + + + +
+ + + + + + + +
+ + +
+ + +
+ + + + + + + + + +
+ + + + + + + +
+ + Collections Icon + +
+ +
+ +
+ + + +
+ + + + + + + + + +
+ +
You can access passwords {{OrganizationName}} has shared with you.
+ +
+ +
+ + +
+ + +
+ +
+ + + + + +
+ + + + + + + +
+ + +
+ + +
+ + + + + + + + + +
+ + + + + + + +
+ + Group Users Icon + +
+ +
+ +
+ + + +
+ + + + + + + + + + + + + +
+ +
You can easily share passwords with friends, family, or coworkers.
+ +
+ + + +
+ +
+ + +
+ + +
+ +
+ + + + + +
+ + + + + + + +
+ +
+ +
+ + + +
+ +
+ + + + + + + + + +
+ + + + + + + +
+ + + +
+ + + + + + + +
+ + +
+ + + + + + + + + + + + + +
+ +
Download Bitwarden on all devices
+ +
+ +
Already using the browser extension? + Download the Bitwarden mobile app from the + App Store + or Google Play + to quickly save logins and autofill forms on the go.
+ +
+ +
+ + +
+ +
+ + + + + +
+ + + + + + + +
+ + +
+ + +
+ + + + + + + + + +
+ + + + + + + +
+ + + + Download on the App Store + + + +
+ +
+ +
+ + + +
+ + + + + + + + + +
+ + + + + + + +
+ + + + Get it on Google Play + + + +
+ +
+ +
+ + +
+ + +
+ +
+ + + +
+ +
+ + + + + + + + + +
+ + + + + + + +
+ + + +
+ + + + + + + +
+ + +
+ + + + + + + + + +
+ +

+ Learn more about Bitwarden +

+ Find user guides, product documentation, and videos on the + Bitwarden Help Center.
+ +
+ +
+ + + +
+ + + + + + + + + +
+ +
+ + +
+ +
+ + + +
+ +
+ + + + + + + + + +
+ + + + + + + +
+ + +
+ + + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + + + + + + + + +
+ + + + + + +
+ + + +
+
+ + + +
+ +

+ © 2025 Bitwarden Inc. 1 N. Calle Cesar Chavez, Suite 102, Santa + Barbara, CA, USA +

+

+ Always confirm you are on a trusted Bitwarden domain before logging + in:
+ bitwarden.com | + Learn why we include this +

+ +
+ +
+ + +
+ +
+ + + + + +
+ + + + diff --git a/src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-family-free.text.hbs b/src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationFamilyFreeView.text.hbs similarity index 100% rename from src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-family-free.text.hbs rename to src/Core/AdminConsole/Models/Mail/Mailer/OrganizationConfirmation/OrganizationConfirmationFamilyFreeView.text.hbs diff --git a/src/Core/AdminConsole/Models/Data/Organizations/OrganizationAbility.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationAbility/OrganizationAbility.cs similarity index 95% rename from src/Core/AdminConsole/Models/Data/Organizations/OrganizationAbility.cs rename to src/Core/AdminConsole/OrganizationFeatures/OrganizationAbility/OrganizationAbility.cs index 7c8389c103..40249fa2be 100644 --- a/src/Core/AdminConsole/Models/Data/Organizations/OrganizationAbility.cs +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationAbility/OrganizationAbility.cs @@ -29,6 +29,7 @@ public class OrganizationAbility UseOrganizationDomains = organization.UseOrganizationDomains; UseAdminSponsoredFamilies = organization.UseAdminSponsoredFamilies; UseAutomaticUserConfirmation = organization.UseAutomaticUserConfirmation; + UseDisableSmAdsForUsers = organization.UseDisableSmAdsForUsers; UsePhishingBlocker = organization.UsePhishingBlocker; } @@ -52,5 +53,6 @@ public class OrganizationAbility public bool UseOrganizationDomains { get; set; } public bool UseAdminSponsoredFamilies { get; set; } public bool UseAutomaticUserConfirmation { get; set; } + public bool UseDisableSmAdsForUsers { get; set; } public bool UsePhishingBlocker { get; set; } } diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationAbility/README.md b/src/Core/AdminConsole/OrganizationFeatures/OrganizationAbility/README.md new file mode 100644 index 0000000000..7b92ba3fef --- /dev/null +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationAbility/README.md @@ -0,0 +1,141 @@ +# Organization Ability Flags + +## Overview + +Many Bitwarden features are tied to specific subscription plans. For example, SCIM and SSO are Enterprise features, +while Event Logs are available to Teams and Enterprise plans. When developing features that require plan-based access +control, we use **Organization Ability Flags** (or simply _abilities_) — explicit boolean properties on the Organization +entity that indicate whether an organization can use a specific feature. + +## The Rule + +**Never check plan types to control feature access.** Always use a dedicated ability flag on the Organization entity. + +### ❌ Don't Do This + +```csharp +// Checking plan type directly +if (organization.PlanType == PlanType.Enterprise || + organization.PlanType == PlanType.Teams || + organization.PlanType == PlanType.Family) +{ + // allow feature... +} +``` + +### ❌ Don't Do This + +```csharp +// Piggybacking off another feature's ability +if (organization.PlanType == PlanType.Enterprise && organization.UseEvents) +{ + // assume they can use some other feature... +} +``` + +### ✅ Do This Instead + +```csharp +// Check the explicit ability flag +if (organization.UseEvents) +{ + // allow UseEvents feature... +} +``` + +## Why This Pattern Matters + +Using explicit ability flags instead of plan type checks provides several benefits: + +1. **Simplicity** — A single boolean check is cleaner and less error-prone than maintaining lists of plan types. + +2. **Centralized Control** — Feature access is managed in one place: the ability assignment during organization + creation/upgrade. No need to hunt through the codebase for scattered plan type checks. + +3. **Flexibility** — Abilities can be set independently of plan type, enabling: + + - Early access programs for features not yet tied to a plan + - Trial access to help customers evaluate a feature before upgrading + - Custom arrangements for specific customers + - A/B testing of features across different cohorts + +4. **Safe Refactoring** — When plans change (e.g., adding a new plan tier, renaming plans, or moving features between + tiers), we only update the ability assignment logic—not every place the feature is used. + +5. **Graceful Downgrades** — When an organization downgrades, we update their abilities. All feature checks + automatically respect the new access level. + +## How It Works + +### Ability Assignment at Signup/Upgrade + +When an organization is created or changes plans, the ability flags are set based on the plan's capabilities: + +```csharp +// During organization creation or plan change +organization.UseGroups = plan.HasGroups; +organization.UseSso = plan.HasSso; +organization.UseScim = plan.HasScim; +organization.UsePolicies = plan.HasPolicies; +organization.UseEvents = plan.HasEvents; +// ... etc +``` + +### Modifying Abilities for Existing Organizations + +To change abilities for existing organizations (e.g., rolling out a feature to a new plan tier), create a database +migration that updates the relevant flag: + +```sql +-- Example: Enable UseEvents for all Teams organizations +UPDATE [dbo].[Organization] +SET UseEvents = 1 +WHERE PlanType IN (17, 18) -- TeamsMonthly = 17, TeamsAnnually = 18 +``` + +Then update the plan-to-ability assignment code so new organizations get the correct value. + +## Adding a New Ability + +When developing a new plan-gated feature: + +1. **Add the ability to the Organization and OrganizationAbility entities** — Create a `Use[FeatureName]` boolean + property. + +2. **Add a database migration** — Add the new column to the Organization table. + +3. **Update plan definitions** — Add a corresponding `Has[FeatureName]` property to the Plan model and configure which + plans include it. + +4. **Update organization creation/upgrade logic** — Ensure the ability is set based on the plan. + +5. **Update the organization license claims** (if applicable) - to make the feature available on self-hosted instances. + +6. **Implement checks throughout client and server** — Use the ability consistently everywhere the feature is accessed. + - Clients: get the organization object from `OrganizationService`. + - Server: if you already have the full `Organization` object in scope, you can use it directly. If not, use the + `IApplicationCacheService` to retrieve the `OrganizationAbility`, which is a simplified, cached representation + of the organization ability flags. Note that some older flags may be missing from `OrganizationAbility` but + can be added if needed. + +## Existing Abilities + +For reference, here are some current organization ability flags (not a complete list): + +| Ability | Description | Plans | +|--------------------------|-------------------------------|-------------------| +| `UseGroups` | Group-based collection access | Teams, Enterprise | +| `UseDirectory` | Directory Connector sync | Teams, Enterprise | +| `UseEvents` | Event logging | Teams, Enterprise | +| `UseTotp` | Authenticator (TOTP) | Teams, Enterprise | +| `UseSso` | Single Sign-On | Enterprise | +| `UseScim` | SCIM provisioning | Teams, Enterprise | +| `UsePolicies` | Enterprise policies | Enterprise | +| `UseResetPassword` | Admin password reset | Enterprise | +| `UseOrganizationDomains` | Domain verification/claiming | Enterprise | + +## Questions? + +If you're unsure whether your feature needs a new ability or which existing ability to use, reach out to your team lead +or members of the Admin Console or Architecture teams. When in doubt, adding an explicit ability is almost always the +right choice—it's easy to do and keeps our access control clean and maintainable. diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/AutoConfirmUser/AutomaticallyConfirmOrganizationUserCommand.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/AutoConfirmUser/AutomaticallyConfirmOrganizationUserCommand.cs index 67b5f0da80..1b488677ae 100644 --- a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/AutoConfirmUser/AutomaticallyConfirmOrganizationUserCommand.cs +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/AutoConfirmUser/AutomaticallyConfirmOrganizationUserCommand.cs @@ -1,5 +1,7 @@ -using Bit.Core.AdminConsole.Models.Data.OrganizationUsers; +using Bit.Core.AdminConsole.Entities; +using Bit.Core.AdminConsole.Models.Data.OrganizationUsers; using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.Interfaces; +using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.OrganizationConfirmation; using Bit.Core.AdminConsole.OrganizationFeatures.Policies; using Bit.Core.AdminConsole.OrganizationFeatures.Policies.PolicyRequirements; using Bit.Core.Entities; @@ -25,6 +27,8 @@ public class AutomaticallyConfirmOrganizationUserCommand(IOrganizationUserReposi IPushNotificationService pushNotificationService, IPolicyRequirementQuery policyRequirementQuery, ICollectionRepository collectionRepository, + IFeatureService featureService, + ISendOrganizationConfirmationCommand sendOrganizationConfirmationCommand, TimeProvider timeProvider, ILogger logger) : IAutomaticallyConfirmOrganizationUserCommand { @@ -143,9 +147,7 @@ public class AutomaticallyConfirmOrganizationUserCommand(IOrganizationUserReposi { var user = await userRepository.GetByIdAsync(request.OrganizationUser!.UserId!.Value); - await mailService.SendOrganizationConfirmedEmailAsync(request.Organization!.Name, - user!.Email, - request.OrganizationUser.AccessSecretsManager); + await SendOrganizationConfirmedEmailAsync(request.Organization!, user!.Email, request.OrganizationUser.AccessSecretsManager); } catch (Exception ex) { @@ -183,4 +185,23 @@ public class AutomaticallyConfirmOrganizationUserCommand(IOrganizationUserReposi Organization = await organizationRepository.GetByIdAsync(request.OrganizationId) }; } + + /// + /// Sends the organization confirmed email using either the new mailer pattern or the legacy mail service, + /// depending on the feature flag. + /// + /// The organization the user was confirmed to. + /// The email address of the confirmed user. + /// Whether the user has access to Secrets Manager. + internal async Task SendOrganizationConfirmedEmailAsync(Organization organization, string userEmail, bool accessSecretsManager) + { + if (featureService.IsEnabled(FeatureFlagKeys.OrganizationConfirmationEmail)) + { + await sendOrganizationConfirmationCommand.SendConfirmationAsync(organization, userEmail, accessSecretsManager); + } + else + { + await mailService.SendOrganizationConfirmedEmailAsync(organization.Name, userEmail, accessSecretsManager); + } + } } diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/ConfirmOrganizationUserCommand.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/ConfirmOrganizationUserCommand.cs index b6b49e93e9..0b82ac7ea4 100644 --- a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/ConfirmOrganizationUserCommand.cs +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/ConfirmOrganizationUserCommand.cs @@ -1,8 +1,10 @@ // FIXME: Update this file to be null safe and then delete the line below #nullable disable +using Bit.Core.AdminConsole.Entities; using Bit.Core.AdminConsole.Enums; using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.Interfaces; +using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.OrganizationConfirmation; using Bit.Core.AdminConsole.OrganizationFeatures.Policies; using Bit.Core.AdminConsole.OrganizationFeatures.Policies.Enforcement.AutoConfirm; using Bit.Core.AdminConsole.OrganizationFeatures.Policies.PolicyRequirements; @@ -35,7 +37,7 @@ public class ConfirmOrganizationUserCommand : IConfirmOrganizationUserCommand private readonly IFeatureService _featureService; private readonly ICollectionRepository _collectionRepository; private readonly IAutomaticUserConfirmationPolicyEnforcementValidator _automaticUserConfirmationPolicyEnforcementValidator; - + private readonly ISendOrganizationConfirmationCommand _sendOrganizationConfirmationCommand; public ConfirmOrganizationUserCommand( IOrganizationRepository organizationRepository, IOrganizationUserRepository organizationUserRepository, @@ -50,7 +52,7 @@ public class ConfirmOrganizationUserCommand : IConfirmOrganizationUserCommand IPolicyRequirementQuery policyRequirementQuery, IFeatureService featureService, ICollectionRepository collectionRepository, - IAutomaticUserConfirmationPolicyEnforcementValidator automaticUserConfirmationPolicyEnforcementValidator) + IAutomaticUserConfirmationPolicyEnforcementValidator automaticUserConfirmationPolicyEnforcementValidator, ISendOrganizationConfirmationCommand sendOrganizationConfirmationCommand) { _organizationRepository = organizationRepository; _organizationUserRepository = organizationUserRepository; @@ -66,8 +68,8 @@ public class ConfirmOrganizationUserCommand : IConfirmOrganizationUserCommand _featureService = featureService; _collectionRepository = collectionRepository; _automaticUserConfirmationPolicyEnforcementValidator = automaticUserConfirmationPolicyEnforcementValidator; + _sendOrganizationConfirmationCommand = sendOrganizationConfirmationCommand; } - public async Task ConfirmUserAsync(Guid organizationId, Guid organizationUserId, string key, Guid confirmingUserId, string defaultUserCollectionName = null) { @@ -170,7 +172,7 @@ public class ConfirmOrganizationUserCommand : IConfirmOrganizationUserCommand orgUser.Email = null; await _eventService.LogOrganizationUserEventAsync(orgUser, EventType.OrganizationUser_Confirmed); - await _mailService.SendOrganizationConfirmedEmailAsync(organization.DisplayName(), user.Email, orgUser.AccessSecretsManager); + await SendOrganizationConfirmedEmailAsync(organization, user.Email, orgUser.AccessSecretsManager); succeededUsers.Add(orgUser); result.Add(Tuple.Create(orgUser, "")); } @@ -280,11 +282,6 @@ public class ConfirmOrganizationUserCommand : IConfirmOrganizationUserCommand /// The encrypted default user collection name. private async Task CreateDefaultCollectionAsync(OrganizationUser organizationUser, string defaultUserCollectionName) { - if (!_featureService.IsEnabled(FeatureFlagKeys.CreateDefaultLocation)) - { - return; - } - // Skip if no collection name provided (backwards compatibility) if (string.IsNullOrWhiteSpace(defaultUserCollectionName)) { @@ -323,11 +320,6 @@ public class ConfirmOrganizationUserCommand : IConfirmOrganizationUserCommand private async Task CreateManyDefaultCollectionsAsync(Guid organizationId, IEnumerable confirmedOrganizationUsers, string defaultUserCollectionName) { - if (!_featureService.IsEnabled(FeatureFlagKeys.CreateDefaultLocation)) - { - return; - } - // Skip if no collection name provided (backwards compatibility) if (string.IsNullOrWhiteSpace(defaultUserCollectionName)) { @@ -349,4 +341,23 @@ public class ConfirmOrganizationUserCommand : IConfirmOrganizationUserCommand await _collectionRepository.UpsertDefaultCollectionsAsync(organizationId, eligibleOrganizationUserIds, defaultUserCollectionName); } + + /// + /// Sends the organization confirmed email using either the new mailer pattern or the legacy mail service, + /// depending on the feature flag. + /// + /// The organization the user was confirmed to. + /// The email address of the confirmed user. + /// Whether the user has access to Secrets Manager. + internal async Task SendOrganizationConfirmedEmailAsync(Organization organization, string userEmail, bool accessSecretsManager) + { + if (_featureService.IsEnabled(FeatureFlagKeys.OrganizationConfirmationEmail)) + { + await _sendOrganizationConfirmationCommand.SendConfirmationAsync(organization, userEmail, accessSecretsManager); + } + else + { + await _mailService.SendOrganizationConfirmedEmailAsync(organization.DisplayName(), userEmail, accessSecretsManager); + } + } } diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/OrganizationConfirmation/ISendOrganizationConfirmationCommand.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/OrganizationConfirmation/ISendOrganizationConfirmationCommand.cs new file mode 100644 index 0000000000..ae4d7acda5 --- /dev/null +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/OrganizationConfirmation/ISendOrganizationConfirmationCommand.cs @@ -0,0 +1,22 @@ +using Bit.Core.AdminConsole.Entities; + +namespace Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.OrganizationConfirmation; + +public interface ISendOrganizationConfirmationCommand +{ + /// + /// Sends an organization confirmation email to the specified user. + /// + /// The organization to send the confirmation email for. + /// The email address of the user to send the confirmation to. + /// Whether the user has access to Secrets Manager. + Task SendConfirmationAsync(Organization organization, string userEmail, bool accessSecretsManager); + + /// + /// Sends organization confirmation emails to multiple users. + /// + /// The organization to send the confirmation emails for. + /// The email addresses of the users to send confirmations to. + /// Whether the users have access to Secrets Manager. + Task SendConfirmationsAsync(Organization organization, IEnumerable userEmails, bool accessSecretsManager); +} diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/OrganizationConfirmation/SendOrganizationConfirmationCommand.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/OrganizationConfirmation/SendOrganizationConfirmationCommand.cs new file mode 100644 index 0000000000..952478ce36 --- /dev/null +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/OrganizationConfirmation/SendOrganizationConfirmationCommand.cs @@ -0,0 +1,110 @@ +using System.Net; +using Bit.Core.AdminConsole.Entities; +using Bit.Core.AdminConsole.Models.Mail.Mailer.OrganizationConfirmation; +using Bit.Core.Billing.Enums; +using Bit.Core.Platform.Mail.Mailer; +using Bit.Core.Settings; + +namespace Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.OrganizationConfirmation; + +public class SendOrganizationConfirmationCommand(IMailer mailer, GlobalSettings globalSettings) : ISendOrganizationConfirmationCommand +{ + private const string _titleFirst = "You're confirmed as a member of "; + private const string _titleThird = "!"; + + private static string GetConfirmationSubject(string organizationName) => + $"You can now access items from {organizationName}"; + private string GetWebVaultUrl(bool accessSecretsManager) => accessSecretsManager + ? globalSettings.BaseServiceUri.VaultWithHashAndSecretManagerProduct + : globalSettings.BaseServiceUri.VaultWithHash; + + public async Task SendConfirmationAsync(Organization organization, string userEmail, bool accessSecretsManager = false) + { + await SendConfirmationsAsync(organization, [userEmail], accessSecretsManager); + } + + public async Task SendConfirmationsAsync(Organization organization, IEnumerable userEmails, bool accessSecretsManager = false) + { + var userEmailsList = userEmails.ToList(); + + if (userEmailsList.Count == 0) + { + return; + } + + var organizationName = WebUtility.HtmlDecode(organization.Name); + + if (IsEnterpriseOrTeamsPlan(organization.PlanType)) + { + await SendEnterpriseTeamsEmailsAsync(userEmailsList, organizationName, accessSecretsManager); + return; + } + + await SendFamilyFreeConfirmEmailsAsync(userEmailsList, organizationName, accessSecretsManager); + } + + private async Task SendEnterpriseTeamsEmailsAsync(List userEmailsList, string organizationName, bool accessSecretsManager) + { + var mail = new OrganizationConfirmationEnterpriseTeams + { + ToEmails = userEmailsList, + Subject = GetConfirmationSubject(organizationName), + View = new OrganizationConfirmationEnterpriseTeamsView + { + OrganizationName = organizationName, + TitleFirst = _titleFirst, + TitleSecondBold = organizationName, + TitleThird = _titleThird, + WebVaultUrl = GetWebVaultUrl(accessSecretsManager) + } + }; + + await mailer.SendEmail(mail); + } + + private async Task SendFamilyFreeConfirmEmailsAsync(List userEmailsList, string organizationName, bool accessSecretsManager) + { + var mail = new OrganizationConfirmationFamilyFree + { + ToEmails = userEmailsList, + Subject = GetConfirmationSubject(organizationName), + View = new OrganizationConfirmationFamilyFreeView + { + OrganizationName = organizationName, + TitleFirst = _titleFirst, + TitleSecondBold = organizationName, + TitleThird = _titleThird, + WebVaultUrl = GetWebVaultUrl(accessSecretsManager) + } + }; + + await mailer.SendEmail(mail); + } + + + private static bool IsEnterpriseOrTeamsPlan(PlanType planType) + { + return planType switch + { + PlanType.TeamsMonthly2019 or + PlanType.TeamsAnnually2019 or + PlanType.TeamsMonthly2020 or + PlanType.TeamsAnnually2020 or + PlanType.TeamsMonthly2023 or + PlanType.TeamsAnnually2023 or + PlanType.TeamsStarter2023 or + PlanType.TeamsMonthly or + PlanType.TeamsAnnually or + PlanType.TeamsStarter or + PlanType.EnterpriseMonthly2019 or + PlanType.EnterpriseAnnually2019 or + PlanType.EnterpriseMonthly2020 or + PlanType.EnterpriseAnnually2020 or + PlanType.EnterpriseMonthly2023 or + PlanType.EnterpriseAnnually2023 or + PlanType.EnterpriseMonthly or + PlanType.EnterpriseAnnually => true, + _ => false + }; + } +} diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/RevokeUser/v1/IRevokeOrganizationUserCommand.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/RevokeUser/v1/IRevokeOrganizationUserCommand.cs index 7b5541c3ce..313c01af7c 100644 --- a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/RevokeUser/v1/IRevokeOrganizationUserCommand.cs +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/RevokeUser/v1/IRevokeOrganizationUserCommand.cs @@ -7,6 +7,4 @@ public interface IRevokeOrganizationUserCommand { Task RevokeUserAsync(OrganizationUser organizationUser, Guid? revokingUserId); Task RevokeUserAsync(OrganizationUser organizationUser, EventSystemUser systemUser); - Task>> RevokeUsersAsync(Guid organizationId, - IEnumerable organizationUserIds, Guid? revokingUserId); } diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/RevokeUser/v1/RevokeOrganizationUserCommand.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/RevokeUser/v1/RevokeOrganizationUserCommand.cs index 7aa67f0813..750ebf2518 100644 --- a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/RevokeUser/v1/RevokeOrganizationUserCommand.cs +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/RevokeUser/v1/RevokeOrganizationUserCommand.cs @@ -68,68 +68,4 @@ public class RevokeOrganizationUserCommand( await organizationUserRepository.RevokeAsync(organizationUser.Id); organizationUser.Status = OrganizationUserStatusType.Revoked; } - - public async Task>> RevokeUsersAsync(Guid organizationId, - IEnumerable organizationUserIds, Guid? revokingUserId) - { - var orgUsers = await organizationUserRepository.GetManyAsync(organizationUserIds); - var filteredUsers = orgUsers.Where(u => u.OrganizationId == organizationId) - .ToList(); - - if (!filteredUsers.Any()) - { - throw new BadRequestException("Users invalid."); - } - - if (!await hasConfirmedOwnersExceptQuery.HasConfirmedOwnersExceptAsync(organizationId, organizationUserIds)) - { - throw new BadRequestException("Organization must have at least one confirmed owner."); - } - - var deletingUserIsOwner = false; - if (revokingUserId.HasValue) - { - deletingUserIsOwner = await currentContext.OrganizationOwner(organizationId); - } - - var result = new List>(); - - foreach (var organizationUser in filteredUsers) - { - try - { - if (organizationUser.Status == OrganizationUserStatusType.Revoked) - { - throw new BadRequestException("Already revoked."); - } - - if (revokingUserId.HasValue && organizationUser.UserId == revokingUserId) - { - throw new BadRequestException("You cannot revoke yourself."); - } - - if (organizationUser.Type == OrganizationUserType.Owner && revokingUserId.HasValue && - !deletingUserIsOwner) - { - throw new BadRequestException("Only owners can revoke other owners."); - } - - await organizationUserRepository.RevokeAsync(organizationUser.Id); - organizationUser.Status = OrganizationUserStatusType.Revoked; - await eventService.LogOrganizationUserEventAsync(organizationUser, EventType.OrganizationUser_Revoked); - if (organizationUser.UserId.HasValue) - { - await pushNotificationService.PushSyncOrgKeysAsync(organizationUser.UserId.Value); - } - - result.Add(Tuple.Create(organizationUser, "")); - } - catch (BadRequestException e) - { - result.Add(Tuple.Create(organizationUser, e.Message)); - } - } - - return result; - } } diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/Errors.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/Errors.cs new file mode 100644 index 0000000000..8c19544aa9 --- /dev/null +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/Errors.cs @@ -0,0 +1,7 @@ +using Bit.Core.AdminConsole.Utilities.v2; + +namespace Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.SelfRevokeUser; + +public record OrganizationUserNotFound() : NotFoundError("Organization user not found."); +public record NotEligibleForSelfRevoke() : BadRequestError("User is not eligible for self-revocation. The organization data ownership policy must be enabled and the user must be a confirmed member."); +public record LastOwnerCannotSelfRevoke() : BadRequestError("The last owner cannot revoke themselves."); diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/ISelfRevokeOrganizationUserCommand.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/ISelfRevokeOrganizationUserCommand.cs new file mode 100644 index 0000000000..3153465a38 --- /dev/null +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/ISelfRevokeOrganizationUserCommand.cs @@ -0,0 +1,22 @@ +using Bit.Core.AdminConsole.Utilities.v2.Results; + +namespace Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.SelfRevokeUser; + +/// +/// Allows users to revoke themselves from an organization when declining to migrate personal items +/// under the OrganizationDataOwnership policy. +/// +public interface ISelfRevokeOrganizationUserCommand +{ + /// + /// Revokes a user from an organization. + /// + /// The organization ID. + /// The user ID to revoke. + /// A indicating success or containing an error. + /// + /// Validates the OrganizationDataOwnership policy is enabled and applies to the user (currently Owners/Admins are exempt), + /// the user is a confirmed member, and prevents the last owner from revoking themselves. + /// + Task SelfRevokeUserAsync(Guid organizationId, Guid userId); +} diff --git a/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/SelfRevokeOrganizationUserCommand.cs b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/SelfRevokeOrganizationUserCommand.cs new file mode 100644 index 0000000000..afc0236af4 --- /dev/null +++ b/src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/SelfRevokeUser/SelfRevokeOrganizationUserCommand.cs @@ -0,0 +1,56 @@ +using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.Interfaces; +using Bit.Core.AdminConsole.OrganizationFeatures.Policies; +using Bit.Core.AdminConsole.OrganizationFeatures.Policies.PolicyRequirements; +using Bit.Core.AdminConsole.Utilities.v2.Results; +using Bit.Core.Enums; +using Bit.Core.Platform.Push; +using Bit.Core.Repositories; +using Bit.Core.Services; +using OneOf.Types; + +namespace Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.SelfRevokeUser; + +public class SelfRevokeOrganizationUserCommand( + IOrganizationUserRepository organizationUserRepository, + IPolicyRequirementQuery policyRequirementQuery, + IHasConfirmedOwnersExceptQuery hasConfirmedOwnersExceptQuery, + IEventService eventService, + IPushNotificationService pushNotificationService) + : ISelfRevokeOrganizationUserCommand +{ + public async Task SelfRevokeUserAsync(Guid organizationId, Guid userId) + { + var organizationUser = await organizationUserRepository.GetByOrganizationAsync(organizationId, userId); + if (organizationUser == null) + { + return new OrganizationUserNotFound(); + } + + var policyRequirement = await policyRequirementQuery.GetAsync(userId); + + if (!policyRequirement.EligibleForSelfRevoke(organizationId)) + { + return new NotEligibleForSelfRevoke(); + } + + // Prevent the last owner from revoking themselves, which would brick the organization + if (organizationUser.Type == OrganizationUserType.Owner) + { + var hasOtherOwner = await hasConfirmedOwnersExceptQuery.HasConfirmedOwnersExceptAsync( + organizationId, + [organizationUser.Id], + includeProvider: true); + + if (!hasOtherOwner) + { + return new LastOwnerCannotSelfRevoke(); + } + } + + await organizationUserRepository.RevokeAsync(organizationUser.Id); + await eventService.LogOrganizationUserEventAsync(organizationUser, EventType.OrganizationUser_SelfRevoked); + await pushNotificationService.PushSyncOrgKeysAsync(organizationUser.UserId!.Value); + + return new None(); + } +} diff --git a/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyRequirements/OrganizationDataOwnershipPolicyRequirement.cs b/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyRequirements/OrganizationDataOwnershipPolicyRequirement.cs index 28d6614dcb..d30ba5c39f 100644 --- a/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyRequirements/OrganizationDataOwnershipPolicyRequirement.cs +++ b/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyRequirements/OrganizationDataOwnershipPolicyRequirement.cs @@ -72,6 +72,35 @@ public class OrganizationDataOwnershipPolicyRequirement : IPolicyRequirement { return _policyDetails.Any(p => p.OrganizationId == organizationId); } + + /// + /// Ignore storage limits if the organization has data ownership policy enabled. + /// Allows users to seamlessly migrate their data into the organization without being blocked by storage limits. + /// Organization admins will need to manage storage after migration should overages occur. + /// + public bool IgnoreStorageLimitsOnMigration(Guid organizationId) + { + return _policyDetails.Any(p => p.OrganizationId == organizationId && + p.OrganizationUserStatus == OrganizationUserStatusType.Confirmed); + } + + /// + /// Determines if a user is eligible for self-revocation under the Organization Data Ownership policy. + /// A user is eligible if they are a confirmed member of the organization and the policy is enabled. + /// This also handles exempt roles (Owner/Admin) and policy disabled state via the factory's Enforce predicate. + /// + /// The organization ID to check. + /// True if the user is eligible for self-revocation (policy applies to them), false otherwise. + /// + /// Self-revoke is used to opt out of migrating the user's personal vault to the organization as required by this policy. + /// + public bool EligibleForSelfRevoke(Guid organizationId) + { + var policyDetail = _policyDetails + .FirstOrDefault(p => p.OrganizationId == organizationId); + + return policyDetail?.HasStatus([OrganizationUserStatusType.Confirmed]) ?? false; + } } public record DefaultCollectionRequest(Guid OrganizationUserId, bool ShouldCreateDefaultCollection) diff --git a/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyValidators/AutomaticUserConfirmationPolicyEventHandler.cs b/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyValidators/AutomaticUserConfirmationPolicyEventHandler.cs index 86c94147f4..213d18c27d 100644 --- a/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyValidators/AutomaticUserConfirmationPolicyEventHandler.cs +++ b/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyValidators/AutomaticUserConfirmationPolicyEventHandler.cs @@ -74,8 +74,12 @@ public class AutomaticUserConfirmationPolicyEventHandler( private async Task ValidateUserComplianceWithSingleOrgAsync(Guid organizationId, ICollection organizationUsers) { - var hasNonCompliantUser = (await organizationUserRepository.GetManyByManyUsersAsync( - organizationUsers.Select(ou => ou.UserId!.Value))) + var userIds = organizationUsers.Where( + u => u.UserId is not null && + u.Status != OrganizationUserStatusType.Invited) + .Select(u => u.UserId!.Value); + + var hasNonCompliantUser = (await organizationUserRepository.GetManyByManyUsersAsync(userIds)) .Any(uo => uo.OrganizationId != organizationId && uo.Status != OrganizationUserStatusType.Invited); diff --git a/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyValidators/OrganizationDataOwnershipPolicyValidator.cs b/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyValidators/OrganizationDataOwnershipPolicyValidator.cs index 0bee2a55af..7a47baa65a 100644 --- a/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyValidators/OrganizationDataOwnershipPolicyValidator.cs +++ b/src/Core/AdminConsole/OrganizationFeatures/Policies/PolicyValidators/OrganizationDataOwnershipPolicyValidator.cs @@ -6,15 +6,13 @@ using Bit.Core.AdminConsole.OrganizationFeatures.Policies.PolicyRequirements; using Bit.Core.AdminConsole.OrganizationFeatures.Policies.PolicyUpdateEvents.Interfaces; using Bit.Core.AdminConsole.Repositories; using Bit.Core.Repositories; -using Bit.Core.Services; namespace Bit.Core.AdminConsole.OrganizationFeatures.Policies.PolicyValidators; public class OrganizationDataOwnershipPolicyValidator( IPolicyRepository policyRepository, ICollectionRepository collectionRepository, - IEnumerable> factories, - IFeatureService featureService) + IEnumerable> factories) : OrganizationPolicyValidator(policyRepository, factories), IPostSavePolicySideEffect, IOnPolicyPostUpdateEvent { public PolicyType Type => PolicyType.OrganizationDataOwnership; @@ -32,11 +30,6 @@ public class OrganizationDataOwnershipPolicyValidator( Policy postUpdatedPolicy, Policy? previousPolicyState) { - if (!featureService.IsEnabled(FeatureFlagKeys.CreateDefaultLocation)) - { - return; - } - if (policyRequest.Metadata is not OrganizationModelOwnershipPolicyModel metadata) { return; diff --git a/src/Core/AdminConsole/Services/IIntegrationConfigurationDetailsCache.cs b/src/Core/AdminConsole/Services/IIntegrationConfigurationDetailsCache.cs deleted file mode 100644 index ad27429112..0000000000 --- a/src/Core/AdminConsole/Services/IIntegrationConfigurationDetailsCache.cs +++ /dev/null @@ -1,14 +0,0 @@ -#nullable enable - -using Bit.Core.Enums; -using Bit.Core.Models.Data.Organizations; - -namespace Bit.Core.Services; - -public interface IIntegrationConfigurationDetailsCache -{ - List GetConfigurationDetails( - Guid organizationId, - IntegrationType integrationType, - EventType eventType); -} diff --git a/src/Core/AdminConsole/Services/OrganizationFactory.cs b/src/Core/AdminConsole/Services/OrganizationFactory.cs index 0c64a27431..fadafd179c 100644 --- a/src/Core/AdminConsole/Services/OrganizationFactory.cs +++ b/src/Core/AdminConsole/Services/OrganizationFactory.cs @@ -62,6 +62,8 @@ public static class OrganizationFactory UseAdminSponsoredFamilies = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseAdminSponsoredFamilies), UseAutomaticUserConfirmation = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseAutomaticUserConfirmation), + UseDisableSmAdsForUsers = + claimsPrincipal.GetValue(OrganizationLicenseConstants.UseDisableSmAdsForUsers), UsePhishingBlocker = claimsPrincipal.GetValue(OrganizationLicenseConstants.UsePhishingBlocker), }; @@ -113,6 +115,7 @@ public static class OrganizationFactory UseOrganizationDomains = license.UseOrganizationDomains, UseAdminSponsoredFamilies = license.UseAdminSponsoredFamilies, UseAutomaticUserConfirmation = license.UseAutomaticUserConfirmation, + UseDisableSmAdsForUsers = license.UseDisableSmAdsForUsers, UsePhishingBlocker = license.UsePhishingBlocker, }; } diff --git a/src/Core/Auth/Entities/EmergencyAccess.cs b/src/Core/Auth/Entities/EmergencyAccess.cs index d855126468..36aaf46a8c 100644 --- a/src/Core/Auth/Entities/EmergencyAccess.cs +++ b/src/Core/Auth/Entities/EmergencyAccess.cs @@ -18,7 +18,7 @@ public class EmergencyAccess : ITableObject public string KeyEncrypted { get; set; } public EmergencyAccessType Type { get; set; } public EmergencyAccessStatusType Status { get; set; } - public int WaitTimeDays { get; set; } + public short WaitTimeDays { get; set; } public DateTime? RecoveryInitiatedDate { get; set; } public DateTime? LastNotificationDate { get; set; } public DateTime CreationDate { get; set; } = DateTime.UtcNow; diff --git a/src/Core/Auth/Identity/Policies.cs b/src/Core/Auth/Identity/Policies.cs index b2d94b0a6e..698a890006 100644 --- a/src/Core/Auth/Identity/Policies.cs +++ b/src/Core/Auth/Identity/Policies.cs @@ -5,12 +5,94 @@ public static class Policies /// /// Policy for managing access to the Send feature. /// - public const string Send = "Send"; // [Authorize(Policy = Policies.Send)] - public const string Application = "Application"; // [Authorize(Policy = Policies.Application)] - public const string Web = "Web"; // [Authorize(Policy = Policies.Web)] - public const string Push = "Push"; // [Authorize(Policy = Policies.Push)] + /// + /// + /// Can be used with the Authorize attribute, for example: + /// + /// [Authorize(Policy = Policies.Send)] + /// + /// + /// + public const string Send = "Send"; + + /// + /// Policy to manage access to general API endpoints. + /// + /// + /// + /// Can be used with the Authorize attribute, for example: + /// + /// [Authorize(Policy = Policies.Application)] + /// + /// + /// + public const string Application = "Application"; + + /// + /// Policy to manage access to API endpoints intended for use by the Web Vault and browser extension only. + /// + /// + /// + /// Can be used with the Authorize attribute, for example: + /// + /// [Authorize(Policy = Policies.Web)] + /// + /// + /// + public const string Web = "Web"; + + /// + /// Policy to restrict access to API endpoints for the Push feature. + /// + /// + /// + /// Can be used with the Authorize attribute, for example: + /// + /// [Authorize(Policy = Policies.Push)] + /// + /// + /// + public const string Push = "Push"; + + // TODO: This is unused public const string Licensing = "Licensing"; // [Authorize(Policy = Policies.Licensing)] - public const string Organization = "Organization"; // [Authorize(Policy = Policies.Organization)] - public const string Installation = "Installation"; // [Authorize(Policy = Policies.Installation)] - public const string Secrets = "Secrets"; // [Authorize(Policy = Policies.Secrets)] + + /// + /// Policy to restrict access to API endpoints related to the Organization features. + /// + /// + /// + /// Can be used with the Authorize attribute, for example: + /// + /// [Authorize(Policy = Policies.Licensing)] + /// + /// + /// + public const string Organization = "Organization"; + + /// + /// Policy to restrict access to API endpoints related to the setting up new installations. + /// + /// + /// + /// Can be used with the Authorize attribute, for example: + /// + /// [Authorize(Policy = Policies.Installation)] + /// + /// + /// + public const string Installation = "Installation"; + + /// + /// Policy to restrict access to API endpoints for Secrets Manager features. + /// + /// + /// + /// Can be used with the Authorize attribute, for example: + /// + /// [Authorize(Policy = Policies.Secrets)] + /// + /// + /// + public const string Secrets = "Secrets"; } diff --git a/src/Core/Auth/Models/Data/SetInitialMasterPasswordDataModel.cs b/src/Core/Auth/Models/Data/SetInitialMasterPasswordDataModel.cs new file mode 100644 index 0000000000..82bcb3da5e --- /dev/null +++ b/src/Core/Auth/Models/Data/SetInitialMasterPasswordDataModel.cs @@ -0,0 +1,23 @@ +using Bit.Core.KeyManagement.Models.Data; + +namespace Bit.Core.Auth.Models.Data; + +/// +/// Data model for setting an initial master password for a user. +/// +public class SetInitialMasterPasswordDataModel +{ + public required MasterPasswordAuthenticationData MasterPasswordAuthentication { get; set; } + public required MasterPasswordUnlockData MasterPasswordUnlock { get; set; } + + /// + /// Organization SSO identifier. + /// + public required string OrgSsoIdentifier { get; set; } + + /// + /// User account keys. Required for Master Password decryption user. + /// + public required UserAccountKeysData? AccountKeys { get; set; } + public string? MasterPasswordHint { get; set; } +} diff --git a/src/Core/Auth/Services/EmergencyAccess/EmergencyAccessService.cs b/src/Core/Auth/Services/EmergencyAccess/EmergencyAccessService.cs index 4331179554..0072f85e61 100644 --- a/src/Core/Auth/Services/EmergencyAccess/EmergencyAccessService.cs +++ b/src/Core/Auth/Services/EmergencyAccess/EmergencyAccessService.cs @@ -79,7 +79,7 @@ public class EmergencyAccessService : IEmergencyAccessService Email = emergencyContactEmail.ToLowerInvariant(), Status = EmergencyAccessStatusType.Invited, Type = accessType, - WaitTimeDays = waitTime, + WaitTimeDays = (short)waitTime, CreationDate = DateTime.UtcNow, RevisionDate = DateTime.UtcNow, }; diff --git a/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ISetInitialMasterPasswordCommand.cs b/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ISetInitialMasterPasswordCommand.cs index 31dd19d5bf..d695f2586c 100644 --- a/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ISetInitialMasterPasswordCommand.cs +++ b/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ISetInitialMasterPasswordCommand.cs @@ -1,19 +1,25 @@ -using Bit.Core.Entities; -using Microsoft.AspNetCore.Identity; +using Bit.Core.Auth.Models.Data; +using Bit.Core.Entities; +using Bit.Core.Exceptions; namespace Bit.Core.Auth.UserFeatures.UserMasterPassword.Interfaces; /// /// Manages the setting of the initial master password for a in an organization. -/// This class is primarily invoked in two scenarios: -/// 1) In organizations configured with Single Sign-On (SSO) and master password decryption: +/// In organizations configured with Single Sign-On (SSO) and master password decryption: /// just in time (JIT) provisioned users logging in via SSO are required to set a master password. -/// 2) In organizations configured with SSO and trusted devices decryption: -/// Users who are upgraded to have admin account recovery permissions must set a master password -/// to ensure their ability to reset other users' accounts. /// public interface ISetInitialMasterPasswordCommand { - public Task SetInitialMasterPasswordAsync(User user, string masterPassword, string key, - string orgSsoIdentifier); + /// + /// Sets the initial master password and account keys for the specified user. + /// + /// User to set the master password for + /// Initial master password setup data + /// A task that completes when the operation succeeds + /// + /// Thrown if the user's master password is already set, the organization is not found, + /// the user is not a member of the organization, or the account keys are missing. + /// + public Task SetInitialMasterPasswordAsync(User user, SetInitialMasterPasswordDataModel masterPasswordDataModel); } diff --git a/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ISetInitialMasterPasswordCommandV1.cs b/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ISetInitialMasterPasswordCommandV1.cs new file mode 100644 index 0000000000..7f4818a535 --- /dev/null +++ b/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ISetInitialMasterPasswordCommandV1.cs @@ -0,0 +1,21 @@ +using Bit.Core.Entities; +using Microsoft.AspNetCore.Identity; + +namespace Bit.Core.Auth.UserFeatures.UserMasterPassword.Interfaces; + +/// +/// Manages the setting of the initial master password for a in an organization. +/// This class is primarily invoked in two scenarios: +/// 1) In organizations configured with Single Sign-On (SSO) and master password decryption: +/// just in time (JIT) provisioned users logging in via SSO are required to set a master password. +/// 2) In organizations configured with SSO and trusted devices decryption: +/// Users who are upgraded to have admin account recovery permissions must set a master password +/// to ensure their ability to reset other users' accounts. +/// +// TODO removed with https://bitwarden.atlassian.net/browse/PM-27327 +[Obsolete("Use ISetInitialMasterPasswordCommand instead")] +public interface ISetInitialMasterPasswordCommandV1 +{ + public Task SetInitialMasterPasswordAsync(User user, string masterPassword, string key, + string orgSsoIdentifier); +} diff --git a/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ITdeSetPasswordCommand.cs b/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ITdeSetPasswordCommand.cs new file mode 100644 index 0000000000..4815aea8a0 --- /dev/null +++ b/src/Core/Auth/UserFeatures/UserMasterPassword/Interfaces/ITdeSetPasswordCommand.cs @@ -0,0 +1,26 @@ +using Bit.Core.Auth.Models.Data; +using Bit.Core.Entities; +using Bit.Core.Exceptions; + +namespace Bit.Core.Auth.UserFeatures.UserMasterPassword.Interfaces; + +/// +/// Manages the setting of the master password for a TDE in an organization. +/// In organizations configured with SSO and trusted devices decryption: +/// Users who are upgraded to have admin account recovery permissions must set a master password +/// to ensure their ability to reset other users' accounts. +/// +public interface ITdeSetPasswordCommand +{ + /// + /// Sets the master password for the specified TDE user. + /// + /// User to set the master password for + /// Master password setup data + /// A task that completes when the operation succeeds + /// + /// Thrown if the user's master password is already set, the organization is not found, + /// the user is not a member of the organization, or the user is a TDE user without account keys set. + /// + Task SetMasterPasswordAsync(User user, SetInitialMasterPasswordDataModel masterPasswordDataModel); +} diff --git a/src/Core/Auth/UserFeatures/UserMasterPassword/SetInitialMasterPasswordCommand.cs b/src/Core/Auth/UserFeatures/UserMasterPassword/SetInitialMasterPasswordCommand.cs index 32966f5710..b91ac61f7f 100644 --- a/src/Core/Auth/UserFeatures/UserMasterPassword/SetInitialMasterPasswordCommand.cs +++ b/src/Core/Auth/UserFeatures/UserMasterPassword/SetInitialMasterPasswordCommand.cs @@ -1,4 +1,5 @@ -using Bit.Core.Auth.UserFeatures.UserMasterPassword.Interfaces; +using Bit.Core.Auth.Models.Data; +using Bit.Core.Auth.UserFeatures.UserMasterPassword.Interfaces; using Bit.Core.Entities; using Bit.Core.Enums; using Bit.Core.Exceptions; @@ -6,98 +7,74 @@ using Bit.Core.OrganizationFeatures.OrganizationUsers.Interfaces; using Bit.Core.Repositories; using Bit.Core.Services; using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Logging; namespace Bit.Core.Auth.UserFeatures.UserMasterPassword; public class SetInitialMasterPasswordCommand : ISetInitialMasterPasswordCommand { - private readonly ILogger _logger; - private readonly IdentityErrorDescriber _identityErrorDescriber; private readonly IUserService _userService; private readonly IUserRepository _userRepository; - private readonly IEventService _eventService; private readonly IAcceptOrgUserCommand _acceptOrgUserCommand; private readonly IOrganizationUserRepository _organizationUserRepository; private readonly IOrganizationRepository _organizationRepository; + private readonly IPasswordHasher _passwordHasher; + private readonly IEventService _eventService; - - public SetInitialMasterPasswordCommand( - ILogger logger, - IdentityErrorDescriber identityErrorDescriber, - IUserService userService, - IUserRepository userRepository, - IEventService eventService, - IAcceptOrgUserCommand acceptOrgUserCommand, - IOrganizationUserRepository organizationUserRepository, - IOrganizationRepository organizationRepository) + public SetInitialMasterPasswordCommand(IUserService userService, IUserRepository userRepository, + IAcceptOrgUserCommand acceptOrgUserCommand, IOrganizationUserRepository organizationUserRepository, + IOrganizationRepository organizationRepository, IPasswordHasher passwordHasher, + IEventService eventService) { - _logger = logger; - _identityErrorDescriber = identityErrorDescriber; _userService = userService; _userRepository = userRepository; - _eventService = eventService; _acceptOrgUserCommand = acceptOrgUserCommand; _organizationUserRepository = organizationUserRepository; _organizationRepository = organizationRepository; + _passwordHasher = passwordHasher; + _eventService = eventService; } - public async Task SetInitialMasterPasswordAsync(User user, string masterPassword, string key, - string orgSsoIdentifier) + public async Task SetInitialMasterPasswordAsync(User user, + SetInitialMasterPasswordDataModel masterPasswordDataModel) { - if (user == null) + if (user.Key != null) { - throw new ArgumentNullException(nameof(user)); + throw new BadRequestException("User already has a master password set."); } - if (!string.IsNullOrWhiteSpace(user.MasterPassword)) + if (masterPasswordDataModel.AccountKeys == null) { - _logger.LogWarning("Change password failed for user {userId} - already has password.", user.Id); - return IdentityResult.Failed(_identityErrorDescriber.UserAlreadyHasPassword()); + throw new BadRequestException("Account keys are required."); } - var result = await _userService.UpdatePasswordHash(user, masterPassword, validatePassword: true, refreshStamp: false); - if (!result.Succeeded) - { - return result; - } - - user.RevisionDate = user.AccountRevisionDate = DateTime.UtcNow; - user.Key = key; - - await _userRepository.ReplaceAsync(user); - await _eventService.LogUserEventAsync(user.Id, EventType.User_ChangedPassword); - - - if (string.IsNullOrWhiteSpace(orgSsoIdentifier)) - { - throw new BadRequestException("Organization SSO Identifier required."); - } - - var org = await _organizationRepository.GetByIdentifierAsync(orgSsoIdentifier); + // Prevent a de-synced salt value from creating an un-decryptable unlock method + masterPasswordDataModel.MasterPasswordAuthentication.ValidateSaltUnchangedForUser(user); + masterPasswordDataModel.MasterPasswordUnlock.ValidateSaltUnchangedForUser(user); + var org = await _organizationRepository.GetByIdentifierAsync(masterPasswordDataModel.OrgSsoIdentifier); if (org == null) { - throw new BadRequestException("Organization invalid."); + throw new BadRequestException("Organization SSO identifier is invalid."); } var orgUser = await _organizationUserRepository.GetByOrganizationAsync(org.Id, user.Id); - if (orgUser == null) { throw new BadRequestException("User not found within organization."); } - // TDE users who go from a user without admin acct recovery permission to having it will be - // required to set a MP for the first time and we don't want to re-execute the accept logic - // as they are already confirmed. - // TLDR: only accept post SSO user if they are invited - if (orgUser.Status == OrganizationUserStatusType.Invited) - { - await _acceptOrgUserCommand.AcceptOrgUserAsync(orgUser, user, _userService); - } + // Hash the provided user master password authentication hash on the server side + var serverSideHashedMasterPasswordAuthenticationHash = _passwordHasher.HashPassword(user, + masterPasswordDataModel.MasterPasswordAuthentication.MasterPasswordAuthenticationHash); - return IdentityResult.Success; + var setMasterPasswordTask = _userRepository.SetMasterPassword(user.Id, + masterPasswordDataModel.MasterPasswordUnlock, serverSideHashedMasterPasswordAuthenticationHash, + masterPasswordDataModel.MasterPasswordHint); + await _userRepository.SetV2AccountCryptographicStateAsync(user.Id, masterPasswordDataModel.AccountKeys, + [setMasterPasswordTask]); + + await _eventService.LogUserEventAsync(user.Id, EventType.User_ChangedPassword); + + await _acceptOrgUserCommand.AcceptOrgUserAsync(orgUser, user, _userService); } - } diff --git a/src/Core/Auth/UserFeatures/UserMasterPassword/SetInitialMasterPasswordCommandV1.cs b/src/Core/Auth/UserFeatures/UserMasterPassword/SetInitialMasterPasswordCommandV1.cs new file mode 100644 index 0000000000..df5f0d02f7 --- /dev/null +++ b/src/Core/Auth/UserFeatures/UserMasterPassword/SetInitialMasterPasswordCommandV1.cs @@ -0,0 +1,103 @@ +using Bit.Core.Auth.UserFeatures.UserMasterPassword.Interfaces; +using Bit.Core.Entities; +using Bit.Core.Enums; +using Bit.Core.Exceptions; +using Bit.Core.OrganizationFeatures.OrganizationUsers.Interfaces; +using Bit.Core.Repositories; +using Bit.Core.Services; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; + +namespace Bit.Core.Auth.UserFeatures.UserMasterPassword; + +public class SetInitialMasterPasswordCommandV1 : ISetInitialMasterPasswordCommandV1 +{ + private readonly ILogger _logger; + private readonly IdentityErrorDescriber _identityErrorDescriber; + private readonly IUserService _userService; + private readonly IUserRepository _userRepository; + private readonly IEventService _eventService; + private readonly IAcceptOrgUserCommand _acceptOrgUserCommand; + private readonly IOrganizationUserRepository _organizationUserRepository; + private readonly IOrganizationRepository _organizationRepository; + + + public SetInitialMasterPasswordCommandV1( + ILogger logger, + IdentityErrorDescriber identityErrorDescriber, + IUserService userService, + IUserRepository userRepository, + IEventService eventService, + IAcceptOrgUserCommand acceptOrgUserCommand, + IOrganizationUserRepository organizationUserRepository, + IOrganizationRepository organizationRepository) + { + _logger = logger; + _identityErrorDescriber = identityErrorDescriber; + _userService = userService; + _userRepository = userRepository; + _eventService = eventService; + _acceptOrgUserCommand = acceptOrgUserCommand; + _organizationUserRepository = organizationUserRepository; + _organizationRepository = organizationRepository; + } + + public async Task SetInitialMasterPasswordAsync(User user, string masterPassword, string key, + string orgSsoIdentifier) + { + if (user == null) + { + throw new ArgumentNullException(nameof(user)); + } + + if (!string.IsNullOrWhiteSpace(user.MasterPassword)) + { + _logger.LogWarning("Change password failed for user {userId} - already has password.", user.Id); + return IdentityResult.Failed(_identityErrorDescriber.UserAlreadyHasPassword()); + } + + var result = await _userService.UpdatePasswordHash(user, masterPassword, validatePassword: true, refreshStamp: false); + if (!result.Succeeded) + { + return result; + } + + user.RevisionDate = user.AccountRevisionDate = DateTime.UtcNow; + user.Key = key; + + await _userRepository.ReplaceAsync(user); + await _eventService.LogUserEventAsync(user.Id, EventType.User_ChangedPassword); + + + if (string.IsNullOrWhiteSpace(orgSsoIdentifier)) + { + throw new BadRequestException("Organization SSO Identifier required."); + } + + var org = await _organizationRepository.GetByIdentifierAsync(orgSsoIdentifier); + + if (org == null) + { + throw new BadRequestException("Organization invalid."); + } + + var orgUser = await _organizationUserRepository.GetByOrganizationAsync(org.Id, user.Id); + + if (orgUser == null) + { + throw new BadRequestException("User not found within organization."); + } + + // TDE users who go from a user without admin acct recovery permission to having it will be + // required to set a MP for the first time and we don't want to re-execute the accept logic + // as they are already confirmed. + // TLDR: only accept post SSO user if they are invited + if (orgUser.Status == OrganizationUserStatusType.Invited) + { + await _acceptOrgUserCommand.AcceptOrgUserAsync(orgUser, user, _userService); + } + + return IdentityResult.Success; + } + +} diff --git a/src/Core/Auth/UserFeatures/UserMasterPassword/TdeSetPasswordCommand.cs b/src/Core/Auth/UserFeatures/UserMasterPassword/TdeSetPasswordCommand.cs new file mode 100644 index 0000000000..afd28e95d9 --- /dev/null +++ b/src/Core/Auth/UserFeatures/UserMasterPassword/TdeSetPasswordCommand.cs @@ -0,0 +1,70 @@ +using Bit.Core.Auth.Models.Data; +using Bit.Core.Auth.UserFeatures.UserMasterPassword.Interfaces; +using Bit.Core.Entities; +using Bit.Core.Enums; +using Bit.Core.Exceptions; +using Bit.Core.Repositories; +using Bit.Core.Services; +using Microsoft.AspNetCore.Identity; + +namespace Bit.Core.Auth.UserFeatures.UserMasterPassword; + +public class TdeSetPasswordCommand : ITdeSetPasswordCommand +{ + private readonly IUserRepository _userRepository; + private readonly IOrganizationUserRepository _organizationUserRepository; + private readonly IOrganizationRepository _organizationRepository; + private readonly IPasswordHasher _passwordHasher; + private readonly IEventService _eventService; + + public TdeSetPasswordCommand(IUserRepository userRepository, + IOrganizationUserRepository organizationUserRepository, IOrganizationRepository organizationRepository, + IPasswordHasher passwordHasher, IEventService eventService) + { + _userRepository = userRepository; + _organizationUserRepository = organizationUserRepository; + _organizationRepository = organizationRepository; + _passwordHasher = passwordHasher; + _eventService = eventService; + } + + public async Task SetMasterPasswordAsync(User user, SetInitialMasterPasswordDataModel masterPasswordDataModel) + { + if (user.Key != null) + { + throw new BadRequestException("User already has a master password set."); + } + + if (user.PublicKey == null || user.PrivateKey == null) + { + throw new BadRequestException("TDE user account keys must be set before setting initial master password."); + } + + // Prevent a de-synced salt value from creating an un-decryptable unlock method + masterPasswordDataModel.MasterPasswordAuthentication.ValidateSaltUnchangedForUser(user); + masterPasswordDataModel.MasterPasswordUnlock.ValidateSaltUnchangedForUser(user); + + var org = await _organizationRepository.GetByIdentifierAsync(masterPasswordDataModel.OrgSsoIdentifier); + if (org == null) + { + throw new BadRequestException("Organization SSO identifier is invalid."); + } + + var orgUser = await _organizationUserRepository.GetByOrganizationAsync(org.Id, user.Id); + if (orgUser == null) + { + throw new BadRequestException("User not found within organization."); + } + + // Hash the provided user master password authentication hash on the server side + var serverSideHashedMasterPasswordAuthenticationHash = _passwordHasher.HashPassword(user, + masterPasswordDataModel.MasterPasswordAuthentication.MasterPasswordAuthenticationHash); + + var setMasterPasswordTask = _userRepository.SetMasterPassword(user.Id, + masterPasswordDataModel.MasterPasswordUnlock, serverSideHashedMasterPasswordAuthenticationHash, + masterPasswordDataModel.MasterPasswordHint); + await _userRepository.UpdateUserDataAsync([setMasterPasswordTask]); + + await _eventService.LogUserEventAsync(user.Id, EventType.User_ChangedPassword); + } +} diff --git a/src/Core/Auth/UserFeatures/UserServiceCollectionExtensions.cs b/src/Core/Auth/UserFeatures/UserServiceCollectionExtensions.cs index 7c50f7f17b..6249d1cb1c 100644 --- a/src/Core/Auth/UserFeatures/UserServiceCollectionExtensions.cs +++ b/src/Core/Auth/UserFeatures/UserServiceCollectionExtensions.cs @@ -44,6 +44,8 @@ public static class UserServiceCollectionExtensions private static void AddUserPasswordCommands(this IServiceCollection services) { services.AddScoped(); + services.AddScoped(); + services.AddScoped(); } private static void AddTdeOffboardingPasswordCommands(this IServiceCollection services) diff --git a/src/Core/Billing/Constants/StripeConstants.cs b/src/Core/Billing/Constants/StripeConstants.cs index dc128127ae..e9c34d7e06 100644 --- a/src/Core/Billing/Constants/StripeConstants.cs +++ b/src/Core/Billing/Constants/StripeConstants.cs @@ -42,6 +42,7 @@ public static class StripeConstants public static class ErrorCodes { public const string CustomerTaxLocationInvalid = "customer_tax_location_invalid"; + public const string InvoiceUpcomingNone = "invoice_upcoming_none"; public const string PaymentMethodMicroDepositVerificationAttemptsExceeded = "payment_method_microdeposit_verification_attempts_exceeded"; public const string PaymentMethodMicroDepositVerificationDescriptorCodeMismatch = "payment_method_microdeposit_verification_descriptor_code_mismatch"; public const string PaymentMethodMicroDepositVerificationTimeout = "payment_method_microdeposit_verification_timeout"; @@ -65,8 +66,14 @@ public static class StripeConstants public static class MetadataKeys { public const string BraintreeCustomerId = "btCustomerId"; + public const string BraintreeTransactionId = "btTransactionId"; public const string InvoiceApproved = "invoice_approved"; public const string OrganizationId = "organizationId"; + public const string PayPalTransactionId = "btPayPalTransactionId"; + public const string PreviousAdditionalStorage = "previous_additional_storage"; + public const string PreviousPeriodEndDate = "previous_period_end_date"; + public const string PreviousPremiumPriceId = "previous_premium_price_id"; + public const string PreviousPremiumUserId = "previous_premium_user_id"; public const string ProviderId = "providerId"; public const string Region = "region"; public const string RetiredBraintreeCustomerId = "btCustomerId_old"; diff --git a/src/Core/Billing/Enums/PlanCadenceType.cs b/src/Core/Billing/Enums/PlanCadenceType.cs index 9e6fa69832..20421bc2af 100644 --- a/src/Core/Billing/Enums/PlanCadenceType.cs +++ b/src/Core/Billing/Enums/PlanCadenceType.cs @@ -1,7 +1,11 @@ -namespace Bit.Core.Billing.Enums; +using System.Runtime.Serialization; + +namespace Bit.Core.Billing.Enums; public enum PlanCadenceType { + [EnumMember(Value = "annually")] Annually, + [EnumMember(Value = "monthly")] Monthly } diff --git a/src/Core/Billing/Extensions/DiscountExtensions.cs b/src/Core/Billing/Extensions/DiscountExtensions.cs new file mode 100644 index 0000000000..6d5b91bd89 --- /dev/null +++ b/src/Core/Billing/Extensions/DiscountExtensions.cs @@ -0,0 +1,12 @@ +using Stripe; + +namespace Bit.Core.Billing.Extensions; + +public static class DiscountExtensions +{ + public static bool AppliesTo(this Discount discount, SubscriptionItem subscriptionItem) + => discount.Coupon.AppliesTo.Products.Contains(subscriptionItem.Price.Product.Id); + + public static bool IsValid(this Discount? discount) + => discount?.Coupon?.Valid ?? false; +} diff --git a/src/Core/Billing/Extensions/ServiceCollectionExtensions.cs b/src/Core/Billing/Extensions/ServiceCollectionExtensions.cs index 5ceefed603..c61c4e6279 100644 --- a/src/Core/Billing/Extensions/ServiceCollectionExtensions.cs +++ b/src/Core/Billing/Extensions/ServiceCollectionExtensions.cs @@ -1,5 +1,6 @@ using Bit.Core.Billing.Caches; using Bit.Core.Billing.Caches.Implementations; +using Bit.Core.Billing.Licenses; using Bit.Core.Billing.Licenses.Extensions; using Bit.Core.Billing.Organizations.Commands; using Bit.Core.Billing.Organizations.Queries; @@ -11,8 +12,11 @@ using Bit.Core.Billing.Pricing; using Bit.Core.Billing.Services; using Bit.Core.Billing.Services.Implementations; using Bit.Core.Billing.Subscriptions.Commands; +using Bit.Core.Billing.Subscriptions.Queries; using Bit.Core.Billing.Tax.Services; using Bit.Core.Billing.Tax.Services.Implementations; +using Bit.Core.Services; +using Bit.Core.Services.Implementations; namespace Bit.Core.Billing.Extensions; @@ -28,6 +32,7 @@ public static class ServiceCollectionExtensions services.AddTransient(); services.AddTransient(); services.AddLicenseServices(); + services.AddLicenseOperations(); services.AddPricingClient(); services.AddPaymentOperations(); services.AddOrganizationLicenseCommandsQueries(); @@ -37,6 +42,9 @@ public static class ServiceCollectionExtensions services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } private static void AddOrganizationLicenseCommandsQueries(this IServiceCollection services) @@ -51,6 +59,8 @@ public static class ServiceCollectionExtensions services.AddScoped(); services.AddScoped(); services.AddTransient(); + services.AddScoped(); + services.AddScoped(); } private static void AddPremiumQueries(this IServiceCollection services) diff --git a/src/Core/Billing/Licenses/LicenseConstants.cs b/src/Core/Billing/Licenses/LicenseConstants.cs index 727bcbc229..e7188c5d6f 100644 --- a/src/Core/Billing/Licenses/LicenseConstants.cs +++ b/src/Core/Billing/Licenses/LicenseConstants.cs @@ -44,6 +44,7 @@ public static class OrganizationLicenseConstants public const string UseAdminSponsoredFamilies = nameof(UseAdminSponsoredFamilies); public const string UseOrganizationDomains = nameof(UseOrganizationDomains); public const string UseAutomaticUserConfirmation = nameof(UseAutomaticUserConfirmation); + public const string UseDisableSmAdsForUsers = nameof(UseDisableSmAdsForUsers); public const string UsePhishingBlocker = nameof(UsePhishingBlocker); } diff --git a/src/Core/Billing/Licenses/Models/Api/Response/LicenseResponseModel.cs b/src/Core/Billing/Licenses/Models/Api/Response/LicenseResponseModel.cs new file mode 100644 index 0000000000..60f8f0e81a --- /dev/null +++ b/src/Core/Billing/Licenses/Models/Api/Response/LicenseResponseModel.cs @@ -0,0 +1,44 @@ +using System.Security.Claims; +using Bit.Core.Billing.Licenses.Extensions; +using Bit.Core.Billing.Models.Business; +using Bit.Core.Models.Api; + +namespace Bit.Core.Billing.Licenses.Models.Api.Response; + +/// +/// Response model containing user license information. +/// Separated from subscription data to maintain separation of concerns. +/// +public class LicenseResponseModel : ResponseModel +{ + public LicenseResponseModel(UserLicense license, ClaimsPrincipal? claimsPrincipal) + : base("license") + { + License = license; + + // CRITICAL: When a license has a Token (JWT), ALWAYS use the expiration from the token claim + // The token's expiration is cryptographically secured and cannot be tampered with + // The file's Expires property can be manually edited and should NOT be trusted for display + if (claimsPrincipal != null) + { + Expiration = claimsPrincipal.GetValue(UserLicenseConstants.Expires); + } + else + { + // No token - use the license file expiration (for older licenses without tokens) + Expiration = license.Expires; + } + } + + /// + /// The user's license containing feature entitlements and metadata. + /// + public UserLicense License { get; set; } + + /// + /// The license expiration date. + /// Extracted from the cryptographically secured JWT token when available, + /// otherwise falls back to the license file's expiration date. + /// + public DateTime? Expiration { get; set; } +} diff --git a/src/Core/Billing/Licenses/Queries/GetUserLicenseQuery.cs b/src/Core/Billing/Licenses/Queries/GetUserLicenseQuery.cs new file mode 100644 index 0000000000..16344116cb --- /dev/null +++ b/src/Core/Billing/Licenses/Queries/GetUserLicenseQuery.cs @@ -0,0 +1,23 @@ +using Bit.Core.Billing.Licenses.Models.Api.Response; +using Bit.Core.Billing.Services; +using Bit.Core.Entities; +using Bit.Core.Services; + +namespace Bit.Core.Billing.Licenses.Queries; + +public interface IGetUserLicenseQuery +{ + Task Run(User user); +} + +public class GetUserLicenseQuery( + IUserService userService, + ILicensingService licensingService) : IGetUserLicenseQuery +{ + public async Task Run(User user) + { + var license = await userService.GenerateLicenseAsync(user); + var claimsPrincipal = licensingService.GetClaimsPrincipalFromLicense(license); + return new LicenseResponseModel(license, claimsPrincipal); + } +} diff --git a/src/Core/Billing/Licenses/Registrations.cs b/src/Core/Billing/Licenses/Registrations.cs new file mode 100644 index 0000000000..74c449a355 --- /dev/null +++ b/src/Core/Billing/Licenses/Registrations.cs @@ -0,0 +1,13 @@ +using Bit.Core.Billing.Licenses.Queries; +using Microsoft.Extensions.DependencyInjection; + +namespace Bit.Core.Billing.Licenses; + +public static class Registrations +{ + public static void AddLicenseOperations(this IServiceCollection services) + { + // Queries + services.AddTransient(); + } +} diff --git a/src/Core/Billing/Licenses/Services/Implementations/OrganizationLicenseClaimsFactory.cs b/src/Core/Billing/Licenses/Services/Implementations/OrganizationLicenseClaimsFactory.cs index 4a4771857e..67e47a742a 100644 --- a/src/Core/Billing/Licenses/Services/Implementations/OrganizationLicenseClaimsFactory.cs +++ b/src/Core/Billing/Licenses/Services/Implementations/OrganizationLicenseClaimsFactory.cs @@ -57,6 +57,7 @@ public class OrganizationLicenseClaimsFactory : ILicenseClaimsFactory(OrganizationLicenseConstants.Name); + license.BillingEmail = claimsPrincipal.GetValue(OrganizationLicenseConstants.BillingEmail); + license.BusinessName = claimsPrincipal.GetValue(OrganizationLicenseConstants.BusinessName); + license.PlanType = claimsPrincipal.GetValue(OrganizationLicenseConstants.PlanType); + license.Seats = claimsPrincipal.GetValue(OrganizationLicenseConstants.Seats); + license.MaxCollections = claimsPrincipal.GetValue(OrganizationLicenseConstants.MaxCollections); + license.UsePolicies = claimsPrincipal.GetValue(OrganizationLicenseConstants.UsePolicies); + license.UseSso = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseSso); + license.UseKeyConnector = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseKeyConnector); + license.UseScim = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseScim); + license.UseGroups = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseGroups); + license.UseDirectory = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseDirectory); + license.UseEvents = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseEvents); + license.UseTotp = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseTotp); + license.Use2fa = claimsPrincipal.GetValue(OrganizationLicenseConstants.Use2fa); + license.UseApi = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseApi); + license.UseResetPassword = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseResetPassword); + license.Plan = claimsPrincipal.GetValue(OrganizationLicenseConstants.Plan); + license.SelfHost = claimsPrincipal.GetValue(OrganizationLicenseConstants.SelfHost); + license.UsersGetPremium = claimsPrincipal.GetValue(OrganizationLicenseConstants.UsersGetPremium); + license.UseCustomPermissions = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseCustomPermissions); + license.Enabled = claimsPrincipal.GetValue(OrganizationLicenseConstants.Enabled); + license.Expires = claimsPrincipal.GetValue(OrganizationLicenseConstants.Expires); + license.LicenseKey = claimsPrincipal.GetValue(OrganizationLicenseConstants.LicenseKey); + license.UsePasswordManager = claimsPrincipal.GetValue(OrganizationLicenseConstants.UsePasswordManager); + license.UseSecretsManager = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseSecretsManager); + license.SmSeats = claimsPrincipal.GetValue(OrganizationLicenseConstants.SmSeats); + license.SmServiceAccounts = claimsPrincipal.GetValue(OrganizationLicenseConstants.SmServiceAccounts); + license.UseRiskInsights = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseRiskInsights); + license.UseOrganizationDomains = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseOrganizationDomains); + license.UseAdminSponsoredFamilies = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseAdminSponsoredFamilies); + license.UseAutomaticUserConfirmation = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseAutomaticUserConfirmation); + license.UseDisableSmAdsForUsers = claimsPrincipal.GetValue(OrganizationLicenseConstants.UseDisableSmAdsForUsers); + license.UsePhishingBlocker = claimsPrincipal.GetValue(OrganizationLicenseConstants.UsePhishingBlocker); + license.MaxStorageGb = claimsPrincipal.GetValue(OrganizationLicenseConstants.MaxStorageGb); + license.InstallationId = claimsPrincipal.GetValue(OrganizationLicenseConstants.InstallationId); + license.LicenseType = claimsPrincipal.GetValue(OrganizationLicenseConstants.LicenseType); + license.Issued = claimsPrincipal.GetValue(OrganizationLicenseConstants.Issued); + license.Refresh = claimsPrincipal.GetValue(OrganizationLicenseConstants.Refresh); + license.ExpirationWithoutGracePeriod = claimsPrincipal.GetValue(OrganizationLicenseConstants.ExpirationWithoutGracePeriod); + license.Trial = claimsPrincipal.GetValue(OrganizationLicenseConstants.Trial); + license.LimitCollectionCreationDeletion = claimsPrincipal.GetValue(OrganizationLicenseConstants.LimitCollectionCreationDeletion); + license.AllowAdminAccessToAllCollectionItems = claimsPrincipal.GetValue(OrganizationLicenseConstants.AllowAdminAccessToAllCollectionItems); + } + var canUse = license.CanUse(_globalSettings, _licensingService, claimsPrincipal, out var exception) && selfHostedOrganization.CanUseLicense(license, out exception); @@ -54,12 +107,6 @@ public class UpdateOrganizationLicenseCommand : IUpdateOrganizationLicenseComman throw new BadRequestException(exception); } - var useAutomaticUserConfirmation = claimsPrincipal? - .GetValue(OrganizationLicenseConstants.UseAutomaticUserConfirmation) ?? false; - - selfHostedOrganization.UseAutomaticUserConfirmation = useAutomaticUserConfirmation; - license.UseAutomaticUserConfirmation = useAutomaticUserConfirmation; - await WriteLicenseFileAsync(selfHostedOrganization, license); await UpdateOrganizationAsync(selfHostedOrganization, license); } diff --git a/src/Core/Billing/Organizations/Models/OrganizationLicense.cs b/src/Core/Billing/Organizations/Models/OrganizationLicense.cs index 584021f22f..cfa20c418e 100644 --- a/src/Core/Billing/Organizations/Models/OrganizationLicense.cs +++ b/src/Core/Billing/Organizations/Models/OrganizationLicense.cs @@ -155,6 +155,7 @@ public class OrganizationLicense : ILicense public bool UseOrganizationDomains { get; set; } public bool UseAdminSponsoredFamilies { get; set; } public bool UseAutomaticUserConfirmation { get; set; } + public bool UseDisableSmAdsForUsers { get; set; } public string Hash { get; set; } public string Signature { get; set; } public string Token { get; set; } @@ -230,6 +231,7 @@ public class OrganizationLicense : ILicense !p.Name.Equals(nameof(UseAdminSponsoredFamilies)) && !p.Name.Equals(nameof(UseOrganizationDomains)) && !p.Name.Equals(nameof(UseAutomaticUserConfirmation)) && + !p.Name.Equals(nameof(UseDisableSmAdsForUsers)) && !p.Name.Equals(nameof(UsePhishingBlocker))) .OrderBy(p => p.Name) .Select(p => $"{p.Name}:{Core.Utilities.CoreHelpers.FormatLicenseSignatureValue(p.GetValue(this, null))}") @@ -425,6 +427,7 @@ public class OrganizationLicense : ILicense var useAdminSponsoredFamilies = claimsPrincipal.GetValue(nameof(UseAdminSponsoredFamilies)); var useOrganizationDomains = claimsPrincipal.GetValue(nameof(UseOrganizationDomains)); var useAutomaticUserConfirmation = claimsPrincipal.GetValue(nameof(UseAutomaticUserConfirmation)); + var useDisableSmAdsForUsers = claimsPrincipal.GetValue(nameof(UseDisableSmAdsForUsers)); var claimedPlanType = claimsPrincipal.GetValue(nameof(PlanType)); @@ -461,7 +464,8 @@ public class OrganizationLicense : ILicense smServiceAccounts == organization.SmServiceAccounts && useAdminSponsoredFamilies == organization.UseAdminSponsoredFamilies && useOrganizationDomains == organization.UseOrganizationDomains && - useAutomaticUserConfirmation == organization.UseAutomaticUserConfirmation; + useAutomaticUserConfirmation == organization.UseAutomaticUserConfirmation && + useDisableSmAdsForUsers == organization.UseDisableSmAdsForUsers; } diff --git a/src/Core/Billing/Premium/Commands/CreatePremiumCloudHostedSubscriptionCommand.cs b/src/Core/Billing/Premium/Commands/CreatePremiumCloudHostedSubscriptionCommand.cs index ed60e2f11c..764406ee56 100644 --- a/src/Core/Billing/Premium/Commands/CreatePremiumCloudHostedSubscriptionCommand.cs +++ b/src/Core/Billing/Premium/Commands/CreatePremiumCloudHostedSubscriptionCommand.cs @@ -7,6 +7,7 @@ using Bit.Core.Billing.Payment.Models; using Bit.Core.Billing.Payment.Queries; using Bit.Core.Billing.Pricing; using Bit.Core.Billing.Services; +using Bit.Core.Billing.Subscriptions.Models; using Bit.Core.Entities; using Bit.Core.Enums; using Bit.Core.Platform.Push; @@ -49,6 +50,7 @@ public interface ICreatePremiumCloudHostedSubscriptionCommand public class CreatePremiumCloudHostedSubscriptionCommand( IBraintreeGateway braintreeGateway, + IBraintreeService braintreeService, IGlobalSettings globalSettings, ISetupIntentCache setupIntentCache, IStripeAdapter stripeAdapter, @@ -300,6 +302,7 @@ public class CreatePremiumCloudHostedSubscriptionCommand( ValidateLocation = ValidateTaxLocationTiming.Immediately } }; + return await stripeAdapter.UpdateCustomerAsync(customer.Id, options); } @@ -351,14 +354,19 @@ public class CreatePremiumCloudHostedSubscriptionCommand( var subscription = await stripeAdapter.CreateSubscriptionAsync(subscriptionCreateOptions); - if (usingPayPal) + if (!usingPayPal) { - await stripeAdapter.UpdateInvoiceAsync(subscription.LatestInvoiceId, new InvoiceUpdateOptions - { - AutoAdvance = false - }); + return subscription; } + var invoice = await stripeAdapter.UpdateInvoiceAsync(subscription.LatestInvoiceId, new InvoiceUpdateOptions + { + AutoAdvance = false, + Expand = ["customer"] + }); + + await braintreeService.PayInvoice(new UserId(userId), invoice); + return subscription; } } diff --git a/src/Core/Billing/Premium/Commands/UpdatePremiumStorageCommand.cs b/src/Core/Billing/Premium/Commands/UpdatePremiumStorageCommand.cs new file mode 100644 index 0000000000..176c77bf57 --- /dev/null +++ b/src/Core/Billing/Premium/Commands/UpdatePremiumStorageCommand.cs @@ -0,0 +1,144 @@ +using Bit.Core.Billing.Commands; +using Bit.Core.Billing.Constants; +using Bit.Core.Billing.Pricing; +using Bit.Core.Billing.Services; +using Bit.Core.Entities; +using Bit.Core.Services; +using Bit.Core.Utilities; +using Microsoft.Extensions.Logging; +using OneOf.Types; +using Stripe; + +namespace Bit.Core.Billing.Premium.Commands; + +using static StripeConstants; + +/// +/// Updates the storage allocation for a premium user's subscription. +/// Handles both increases and decreases in storage in an idempotent manner. +/// +public interface IUpdatePremiumStorageCommand +{ + /// + /// Updates the user's storage by the specified additional amount. + /// + /// The premium user whose storage should be updated. + /// The additional storage amount in GB beyond base storage. + /// A billing command result indicating success or failure. + Task> Run(User user, short additionalStorageGb); +} + +public class UpdatePremiumStorageCommand( + IStripeAdapter stripeAdapter, + IUserService userService, + IPricingClient pricingClient, + ILogger logger) + : BaseBillingCommand(logger), IUpdatePremiumStorageCommand +{ + public Task> Run(User user, short additionalStorageGb) => HandleAsync(async () => + { + if (user is not { Premium: true, GatewaySubscriptionId: not null and not "" }) + { + return new BadRequest("User does not have a premium subscription."); + } + + if (!user.MaxStorageGb.HasValue) + { + return new BadRequest("User has no access to storage."); + } + + // Fetch all premium plans and the user's subscription to find which plan they're on + var premiumPlans = await pricingClient.ListPremiumPlans(); + var subscription = await stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId); + + // Find the password manager subscription item (seat, not storage) and match it to a plan + var passwordManagerItem = subscription.Items.Data.FirstOrDefault(i => + premiumPlans.Any(p => p.Seat.StripePriceId == i.Price.Id)); + + if (passwordManagerItem == null) + { + return new Conflict("Premium subscription does not have a Password Manager line item."); + } + + var premiumPlan = premiumPlans.First(p => p.Seat.StripePriceId == passwordManagerItem.Price.Id); + + var baseStorageGb = (short)premiumPlan.Storage.Provided; + + if (additionalStorageGb < 0) + { + return new BadRequest("Additional storage cannot be negative."); + } + + var maxStorageGb = (short)(baseStorageGb + additionalStorageGb); + + if (maxStorageGb > 100) + { + return new BadRequest("Maximum storage is 100 GB."); + } + + // Idempotency check: if user already has the requested storage, return success + if (user.MaxStorageGb == maxStorageGb) + { + return new None(); + } + + var remainingStorage = user.StorageBytesRemaining(maxStorageGb); + if (remainingStorage < 0) + { + return new BadRequest( + $"You are currently using {CoreHelpers.ReadableBytesSize(user.Storage.GetValueOrDefault(0))} of storage. " + + "Delete some stored data first."); + } + + // Find the storage line item in the subscription + var storageItem = subscription.Items.Data.FirstOrDefault(i => i.Price.Id == premiumPlan.Storage.StripePriceId); + + var subscriptionItemOptions = new List(); + + if (additionalStorageGb > 0) + { + if (storageItem != null) + { + // Update existing storage item + subscriptionItemOptions.Add(new SubscriptionItemOptions + { + Id = storageItem.Id, + Price = premiumPlan.Storage.StripePriceId, + Quantity = additionalStorageGb + }); + } + else + { + // Add new storage item + subscriptionItemOptions.Add(new SubscriptionItemOptions + { + Price = premiumPlan.Storage.StripePriceId, + Quantity = additionalStorageGb + }); + } + } + else if (storageItem != null) + { + // Remove storage item if setting to 0 + subscriptionItemOptions.Add(new SubscriptionItemOptions + { + Id = storageItem.Id, + Deleted = true + }); + } + + var subscriptionUpdateOptions = new SubscriptionUpdateOptions + { + Items = subscriptionItemOptions, + ProrationBehavior = ProrationBehavior.AlwaysInvoice + }; + + await stripeAdapter.UpdateSubscriptionAsync(subscription.Id, subscriptionUpdateOptions); + + // Update the user's max storage + user.MaxStorageGb = maxStorageGb; + await userService.SaveUserAsync(user); + + return new None(); + }); +} diff --git a/src/Core/Billing/Premium/Commands/UpgradePremiumToOrganizationCommand.cs b/src/Core/Billing/Premium/Commands/UpgradePremiumToOrganizationCommand.cs new file mode 100644 index 0000000000..81bc5c9e2c --- /dev/null +++ b/src/Core/Billing/Premium/Commands/UpgradePremiumToOrganizationCommand.cs @@ -0,0 +1,228 @@ +using Bit.Core.AdminConsole.Entities; +using Bit.Core.Billing.Commands; +using Bit.Core.Billing.Constants; +using Bit.Core.Billing.Enums; +using Bit.Core.Billing.Extensions; +using Bit.Core.Billing.Pricing; +using Bit.Core.Billing.Services; +using Bit.Core.Entities; +using Bit.Core.Enums; +using Bit.Core.Repositories; +using Bit.Core.Services; +using Bit.Core.Utilities; +using Microsoft.Extensions.Logging; +using OneOf.Types; +using Stripe; + +namespace Bit.Core.Billing.Premium.Commands; +/// +/// Upgrades a user's Premium subscription to an Organization plan by creating a new Organization +/// and transferring the subscription from the User to the Organization. +/// +public interface IUpgradePremiumToOrganizationCommand +{ + /// + /// Upgrades a Premium subscription to an Organization subscription. + /// + /// The user with an active Premium subscription to upgrade. + /// The name for the new organization. + /// The encrypted organization key for the owner. + /// The target organization plan type to upgrade to. + /// A billing command result indicating success or failure with appropriate error details. + Task> Run( + User user, + string organizationName, + string key, + PlanType targetPlanType); +} + +public class UpgradePremiumToOrganizationCommand( + ILogger logger, + IPricingClient pricingClient, + IStripeAdapter stripeAdapter, + IUserService userService, + IOrganizationRepository organizationRepository, + IOrganizationUserRepository organizationUserRepository, + IOrganizationApiKeyRepository organizationApiKeyRepository, + IApplicationCacheService applicationCacheService) + : BaseBillingCommand(logger), IUpgradePremiumToOrganizationCommand +{ + public Task> Run( + User user, + string organizationName, + string key, + PlanType targetPlanType) => HandleAsync(async () => + { + // Validate that the user has an active Premium subscription + if (user is not { Premium: true, GatewaySubscriptionId: not null and not "" }) + { + return new BadRequest("User does not have an active Premium subscription."); + } + + // Hardcode seats to 1 for upgrade flow + const int seats = 1; + + // Fetch the current Premium subscription from Stripe + var currentSubscription = await stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId); + + // Fetch all premium plans to find which specific plan the user is on + var premiumPlans = await pricingClient.ListPremiumPlans(); + + // Find the password manager subscription item (seat, not storage) and match it to a plan + var passwordManagerItem = currentSubscription.Items.Data.FirstOrDefault(i => + premiumPlans.Any(p => p.Seat.StripePriceId == i.Price.Id)); + + if (passwordManagerItem == null) + { + return new BadRequest("Premium subscription item not found."); + } + + var usersPremiumPlan = premiumPlans.First(p => p.Seat.StripePriceId == passwordManagerItem.Price.Id); + + // Get the target organization plan + var targetPlan = await pricingClient.GetPlanOrThrow(targetPlanType); + + // Build the list of subscription item updates + var subscriptionItemOptions = new List(); + + // Delete the user's specific password manager item + subscriptionItemOptions.Add(new SubscriptionItemOptions + { + Id = passwordManagerItem.Id, + Deleted = true + }); + + // Delete the storage item if it exists for this user's plan + var storageItem = currentSubscription.Items.Data.FirstOrDefault(i => + i.Price.Id == usersPremiumPlan.Storage.StripePriceId); + + // Capture the previous additional storage quantity for potential revert + var previousAdditionalStorage = storageItem?.Quantity ?? 0; + + if (storageItem != null) + { + subscriptionItemOptions.Add(new SubscriptionItemOptions + { + Id = storageItem.Id, + Deleted = true + }); + } + + // Add new organization subscription items + if (targetPlan.HasNonSeatBasedPasswordManagerPlan()) + { + subscriptionItemOptions.Add(new SubscriptionItemOptions + { + Price = targetPlan.PasswordManager.StripePlanId, + Quantity = 1 + }); + } + else + { + subscriptionItemOptions.Add(new SubscriptionItemOptions + { + Price = targetPlan.PasswordManager.StripeSeatPlanId, + Quantity = seats + }); + } + + // Generate organization ID early to include in metadata + var organizationId = CoreHelpers.GenerateComb(); + + // Build the subscription update options + var subscriptionUpdateOptions = new SubscriptionUpdateOptions + { + Items = subscriptionItemOptions, + ProrationBehavior = StripeConstants.ProrationBehavior.None, + Metadata = new Dictionary + { + [StripeConstants.MetadataKeys.OrganizationId] = organizationId.ToString(), + [StripeConstants.MetadataKeys.PreviousPremiumPriceId] = usersPremiumPlan.Seat.StripePriceId, + [StripeConstants.MetadataKeys.PreviousPeriodEndDate] = currentSubscription.GetCurrentPeriodEnd()?.ToString("O") ?? string.Empty, + [StripeConstants.MetadataKeys.PreviousAdditionalStorage] = previousAdditionalStorage.ToString(), + [StripeConstants.MetadataKeys.PreviousPremiumUserId] = user.Id.ToString(), + [StripeConstants.MetadataKeys.UserId] = string.Empty // Remove userId to unlink subscription from User + } + }; + + // Create the Organization entity + var organization = new Organization + { + Id = organizationId, + Name = organizationName, + BillingEmail = user.Email, + PlanType = targetPlan.Type, + Seats = (short)seats, + MaxCollections = targetPlan.PasswordManager.MaxCollections, + MaxStorageGb = targetPlan.PasswordManager.BaseStorageGb, + UsePolicies = targetPlan.HasPolicies, + UseSso = targetPlan.HasSso, + UseGroups = targetPlan.HasGroups, + UseEvents = targetPlan.HasEvents, + UseDirectory = targetPlan.HasDirectory, + UseTotp = targetPlan.HasTotp, + Use2fa = targetPlan.Has2fa, + UseApi = targetPlan.HasApi, + UseResetPassword = targetPlan.HasResetPassword, + SelfHost = targetPlan.HasSelfHost, + UsersGetPremium = targetPlan.UsersGetPremium, + UseCustomPermissions = targetPlan.HasCustomPermissions, + UseScim = targetPlan.HasScim, + Plan = targetPlan.Name, + Gateway = GatewayType.Stripe, + Enabled = true, + LicenseKey = CoreHelpers.SecureRandomString(20), + CreationDate = DateTime.UtcNow, + RevisionDate = DateTime.UtcNow, + Status = OrganizationStatusType.Created, + UsePasswordManager = true, + UseSecretsManager = false, + UseOrganizationDomains = targetPlan.HasOrganizationDomains, + GatewayCustomerId = user.GatewayCustomerId, + GatewaySubscriptionId = currentSubscription.Id + }; + + // Update the subscription in Stripe + await stripeAdapter.UpdateSubscriptionAsync(currentSubscription.Id, subscriptionUpdateOptions); + + // Save the organization + await organizationRepository.CreateAsync(organization); + + // Create organization API key + await organizationApiKeyRepository.CreateAsync(new OrganizationApiKey + { + OrganizationId = organization.Id, + ApiKey = CoreHelpers.SecureRandomString(30), + Type = OrganizationApiKeyType.Default, + RevisionDate = DateTime.UtcNow, + }); + + // Update cache + await applicationCacheService.UpsertOrganizationAbilityAsync(organization); + + // Create OrganizationUser for the upgrading user as owner + var organizationUser = new OrganizationUser + { + OrganizationId = organization.Id, + UserId = user.Id, + Key = key, + AccessSecretsManager = false, + Type = OrganizationUserType.Owner, + Status = OrganizationUserStatusType.Confirmed, + CreationDate = organization.CreationDate, + RevisionDate = organization.CreationDate + }; + organizationUser.SetNewId(); + await organizationUserRepository.CreateAsync(organizationUser); + + // Remove subscription from user + user.Premium = false; + user.PremiumExpirationDate = null; + user.GatewaySubscriptionId = null; + user.GatewayCustomerId = null; + user.RevisionDate = DateTime.UtcNow; + await userService.SaveUserAsync(user); + + return new None(); + }); +} diff --git a/src/Core/Billing/Subscriptions/Commands/ReinstateSubscriptionCommand.cs b/src/Core/Billing/Subscriptions/Commands/ReinstateSubscriptionCommand.cs new file mode 100644 index 0000000000..e7d988a107 --- /dev/null +++ b/src/Core/Billing/Subscriptions/Commands/ReinstateSubscriptionCommand.cs @@ -0,0 +1,42 @@ +using Bit.Core.Billing.Commands; +using Bit.Core.Billing.Constants; +using Bit.Core.Billing.Services; +using Bit.Core.Entities; +using Microsoft.Extensions.Logging; +using OneOf.Types; +using Stripe; + +namespace Bit.Core.Billing.Subscriptions.Commands; + +using static StripeConstants; + +public interface IReinstateSubscriptionCommand +{ + Task> Run(ISubscriber subscriber); +} + +public class ReinstateSubscriptionCommand( + ILogger logger, + IStripeAdapter stripeAdapter) : BaseBillingCommand(logger), IReinstateSubscriptionCommand +{ + public Task> Run(ISubscriber subscriber) => HandleAsync(async () => + { + var subscription = await stripeAdapter.GetSubscriptionAsync(subscriber.GatewaySubscriptionId); + + if (subscription is not + { + Status: SubscriptionStatus.Trialing or SubscriptionStatus.Active, + CancelAt: not null + }) + { + return new BadRequest("Subscription is not pending cancellation."); + } + + await stripeAdapter.UpdateSubscriptionAsync(subscription.Id, new SubscriptionUpdateOptions + { + CancelAtPeriodEnd = false + }); + + return new None(); + }); +} diff --git a/src/Core/Billing/Subscriptions/Models/BitwardenDiscount.cs b/src/Core/Billing/Subscriptions/Models/BitwardenDiscount.cs new file mode 100644 index 0000000000..dde005b7bd --- /dev/null +++ b/src/Core/Billing/Subscriptions/Models/BitwardenDiscount.cs @@ -0,0 +1,61 @@ +using System.Runtime.Serialization; +using System.Text.Json.Serialization; +using Bit.Core.Utilities; +using Stripe; + +namespace Bit.Core.Billing.Subscriptions.Models; + +/// +/// The type of discounts Bitwarden supports. +/// +public enum BitwardenDiscountType +{ + [EnumMember(Value = "amount-off")] + AmountOff, + + [EnumMember(Value = "percent-off")] + PercentOff +} + +/// +/// A record representing a discount applied to a Bitwarden subscription. +/// +public record BitwardenDiscount +{ + /// + /// The type of the discount. + /// + [JsonConverter(typeof(EnumMemberJsonConverter))] + public required BitwardenDiscountType Type { get; init; } + + /// + /// The value of the discount. + /// + public required decimal Value { get; init; } + + public static implicit operator BitwardenDiscount(Discount? discount) + { + if (discount is not + { + Coupon.Valid: true + }) + { + return null!; + } + + return discount.Coupon switch + { + { AmountOff: > 0 } => new BitwardenDiscount + { + Type = BitwardenDiscountType.AmountOff, + Value = discount.Coupon.AmountOff.Value + }, + { PercentOff: > 0 } => new BitwardenDiscount + { + Type = BitwardenDiscountType.PercentOff, + Value = discount.Coupon.PercentOff.Value + }, + _ => null! + }; + } +} diff --git a/src/Core/Billing/Subscriptions/Models/BitwardenSubscription.cs b/src/Core/Billing/Subscriptions/Models/BitwardenSubscription.cs new file mode 100644 index 0000000000..5643b35cda --- /dev/null +++ b/src/Core/Billing/Subscriptions/Models/BitwardenSubscription.cs @@ -0,0 +1,52 @@ +namespace Bit.Core.Billing.Subscriptions.Models; + +public record BitwardenSubscription +{ + /// + /// The status of the subscription. + /// + public required string Status { get; init; } + + /// + /// The subscription's cart, including line items, any discounts, and estimated tax. + /// + public required Cart Cart { get; init; } + + /// + /// The amount of storage available and used for the subscription. + /// Allowed Subscribers: User, Organization + /// + public Storage? Storage { get; init; } + + /// + /// If the subscription is pending cancellation, the date at which the + /// subscription will be canceled. + /// Allowed Statuses: 'trialing', 'active' + /// + public DateTime? CancelAt { get; init; } + + /// + /// The date the subscription was canceled. + /// Allowed Statuses: 'canceled' + /// + public DateTime? Canceled { get; init; } + + /// + /// The date of the next charge for the subscription. + /// Allowed Statuses: 'trialing', 'active' + /// + public DateTime? NextCharge { get; init; } + + /// + /// The date the subscription will be or was suspended due to lack of payment. + /// Allowed Statuses: 'incomplete', 'incomplete_expired', 'past_due', 'unpaid' + /// + public DateTime? Suspension { get; init; } + + /// + /// The number of days after the subscription goes 'past_due' the subscriber has to resolve their + /// open invoices before the subscription is suspended. + /// Allowed Statuses: 'past_due' + /// + public int? GracePeriod { get; init; } +} diff --git a/src/Core/Billing/Subscriptions/Models/Cart.cs b/src/Core/Billing/Subscriptions/Models/Cart.cs new file mode 100644 index 0000000000..e7c08919d9 --- /dev/null +++ b/src/Core/Billing/Subscriptions/Models/Cart.cs @@ -0,0 +1,83 @@ +using System.Text.Json.Serialization; +using Bit.Core.Billing.Enums; +using Bit.Core.Utilities; + +namespace Bit.Core.Billing.Subscriptions.Models; + +public record CartItem +{ + /// + /// The client-side translation key for the name of the cart item. + /// + public required string TranslationKey { get; init; } + + /// + /// The quantity of the cart item. + /// + public required long Quantity { get; init; } + + /// + /// The unit-cost of the cart item. + /// + public required decimal Cost { get; init; } + + /// + /// An optional discount applied specifically to this cart item. + /// + public BitwardenDiscount? Discount { get; init; } +} + +public record PasswordManagerCartItems +{ + /// + /// The Password Manager seats in the cart. + /// + public required CartItem Seats { get; init; } + + /// + /// The additional storage in the cart. + /// + public CartItem? AdditionalStorage { get; init; } +} + +public record SecretsManagerCartItems +{ + /// + /// The Secrets Manager seats in the cart. + /// + public required CartItem Seats { get; init; } + + /// + /// The additional service accounts in the cart. + /// + public CartItem? AdditionalServiceAccounts { get; init; } +} + +public record Cart +{ + /// + /// The Password Manager items in the cart. + /// + public required PasswordManagerCartItems PasswordManager { get; init; } + + /// + /// The Secrets Manager items in the cart. + /// + public SecretsManagerCartItems? SecretsManager { get; init; } + + /// + /// The cart's billing cadence. + /// + [JsonConverter(typeof(EnumMemberJsonConverter))] + public PlanCadenceType Cadence { get; init; } + + /// + /// An optional discount applied to the entire cart. + /// + public BitwardenDiscount? Discount { get; init; } + + /// + /// The estimated tax for the cart. + /// + public required decimal EstimatedTax { get; init; } +} diff --git a/src/Core/Billing/Subscriptions/Models/Storage.cs b/src/Core/Billing/Subscriptions/Models/Storage.cs new file mode 100644 index 0000000000..cd26579bee --- /dev/null +++ b/src/Core/Billing/Subscriptions/Models/Storage.cs @@ -0,0 +1,52 @@ +using Bit.Core.AdminConsole.Entities; +using Bit.Core.Entities; +using Bit.Core.Utilities; +using OneOf; + +namespace Bit.Core.Billing.Subscriptions.Models; + +public record Storage +{ + private const double _bytesPerGibibyte = 1073741824D; + + /// + /// The amount of storage the subscriber has available. + /// + public required short Available { get; init; } + + /// + /// The amount of storage the subscriber has used. + /// + public required double Used { get; init; } + + /// + /// The amount of storage the subscriber has used, formatted as a human-readable string. + /// + public required string ReadableUsed { get; init; } + + public static implicit operator Storage(User user) => From(user); + public static implicit operator Storage(Organization organization) => From(organization); + + private static Storage From(OneOf subscriber) + { + var maxStorageGB = subscriber.Match( + user => user.MaxStorageGb, + organization => organization.MaxStorageGb); + + if (maxStorageGB == null) + { + return null!; + } + + var storage = subscriber.Match( + user => user.Storage, + organization => organization.Storage); + + return new Storage + { + Available = maxStorageGB.Value, + Used = Math.Round((storage ?? 0) / _bytesPerGibibyte, 2), + ReadableUsed = CoreHelpers.ReadableBytesSize(storage ?? 0) + }; + } +} diff --git a/src/Core/Billing/Subscriptions/Models/SubscriberId.cs b/src/Core/Billing/Subscriptions/Models/SubscriberId.cs new file mode 100644 index 0000000000..1ea842b0e6 --- /dev/null +++ b/src/Core/Billing/Subscriptions/Models/SubscriberId.cs @@ -0,0 +1,43 @@ +using Bit.Core.Billing.Constants; +using Bit.Core.Exceptions; +using OneOf; +using Stripe; + +namespace Bit.Core.Billing.Subscriptions.Models; + +using static StripeConstants; + +public record UserId(Guid Value); + +public record OrganizationId(Guid Value); + +public record ProviderId(Guid Value); + +public class SubscriberId : OneOfBase +{ + private SubscriberId(OneOf input) : base(input) { } + + public static implicit operator SubscriberId(UserId value) => new(value); + public static implicit operator SubscriberId(OrganizationId value) => new(value); + public static implicit operator SubscriberId(ProviderId value) => new(value); + + public static implicit operator SubscriberId(Subscription subscription) + { + if (subscription.Metadata.TryGetValue(MetadataKeys.UserId, out var userIdValue) + && Guid.TryParse(userIdValue, out var userId)) + { + return new UserId(userId); + } + + if (subscription.Metadata.TryGetValue(MetadataKeys.OrganizationId, out var organizationIdValue) + && Guid.TryParse(organizationIdValue, out var organizationId)) + { + return new OrganizationId(organizationId); + } + + return subscription.Metadata.TryGetValue(MetadataKeys.ProviderId, out var providerIdValue) && + Guid.TryParse(providerIdValue, out var providerId) + ? new ProviderId(providerId) + : throw new ConflictException("Subscription does not have a valid subscriber ID"); + } +} diff --git a/src/Core/Billing/Subscriptions/Queries/GetBitwardenSubscriptionQuery.cs b/src/Core/Billing/Subscriptions/Queries/GetBitwardenSubscriptionQuery.cs new file mode 100644 index 0000000000..cd7fa91fff --- /dev/null +++ b/src/Core/Billing/Subscriptions/Queries/GetBitwardenSubscriptionQuery.cs @@ -0,0 +1,201 @@ +using Bit.Core.Billing.Constants; +using Bit.Core.Billing.Enums; +using Bit.Core.Billing.Extensions; +using Bit.Core.Billing.Pricing; +using Bit.Core.Billing.Services; +using Bit.Core.Billing.Subscriptions.Models; +using Bit.Core.Entities; +using Bit.Core.Exceptions; +using Microsoft.Extensions.Logging; +using OneOf; +using Stripe; + +namespace Bit.Core.Billing.Subscriptions.Queries; + +using static StripeConstants; +using static Utilities; + +public interface IGetBitwardenSubscriptionQuery +{ + /// + /// Retrieves detailed subscription information for a user, including subscription status, + /// cart items, discounts, and billing details. + /// + /// The user whose subscription information to retrieve. + /// + /// A containing the subscription details, or null if no + /// subscription is found or the subscription status is not recognized. + /// + /// + /// Currently only supports subscribers. Future versions will support all + /// types (User and Organization). + /// + Task Run(User user); +} + +public class GetBitwardenSubscriptionQuery( + ILogger logger, + IPricingClient pricingClient, + IStripeAdapter stripeAdapter) : IGetBitwardenSubscriptionQuery +{ + public async Task Run(User user) + { + var subscription = await stripeAdapter.GetSubscriptionAsync(user.GatewaySubscriptionId, new SubscriptionGetOptions + { + Expand = + [ + "customer.discount.coupon.applies_to", + "discounts.coupon.applies_to", + "items.data.price.product", + "test_clock" + ] + }); + + var cart = await GetPremiumCartAsync(subscription); + + var baseSubscription = new BitwardenSubscription { Status = subscription.Status, Cart = cart, Storage = user }; + + switch (subscription.Status) + { + case SubscriptionStatus.Incomplete: + case SubscriptionStatus.IncompleteExpired: + return baseSubscription with { Suspension = subscription.Created.AddHours(23), GracePeriod = 1 }; + + case SubscriptionStatus.Trialing: + case SubscriptionStatus.Active: + return baseSubscription with + { + NextCharge = subscription.GetCurrentPeriodEnd(), + CancelAt = subscription.CancelAt + }; + + case SubscriptionStatus.PastDue: + case SubscriptionStatus.Unpaid: + var suspension = await GetSubscriptionSuspensionAsync(stripeAdapter, subscription); + if (suspension == null) + { + return baseSubscription; + } + return baseSubscription with { Suspension = suspension.SuspensionDate, GracePeriod = suspension.GracePeriod }; + + case SubscriptionStatus.Canceled: + return baseSubscription with { Canceled = subscription.CanceledAt }; + + default: + { + logger.LogError("Subscription ({SubscriptionID}) has an unmanaged status ({Status})", subscription.Id, subscription.Status); + throw new ConflictException("Subscription is in an invalid state. Please contact support for assistance."); + } + } + } + + private async Task GetPremiumCartAsync( + Subscription subscription) + { + var plans = await pricingClient.ListPremiumPlans(); + + var passwordManagerSeatsItem = subscription.Items.FirstOrDefault(item => + plans.Any(plan => plan.Seat.StripePriceId == item.Price.Id)); + + if (passwordManagerSeatsItem == null) + { + throw new ConflictException("Premium subscription does not have a Password Manager line item."); + } + + var additionalStorageItem = subscription.Items.FirstOrDefault(item => + plans.Any(plan => plan.Storage.StripePriceId == item.Price.Id)); + + var (cartLevelDiscount, productLevelDiscounts) = GetStripeDiscounts(subscription); + + var passwordManagerSeats = new CartItem + { + TranslationKey = "premiumMembership", + Quantity = passwordManagerSeatsItem.Quantity, + Cost = GetCost(passwordManagerSeatsItem), + Discount = productLevelDiscounts.FirstOrDefault(discount => discount.AppliesTo(passwordManagerSeatsItem)) + }; + + var additionalStorage = additionalStorageItem != null + ? new CartItem + { + TranslationKey = "additionalStorageGB", + Quantity = additionalStorageItem.Quantity, + Cost = GetCost(additionalStorageItem), + Discount = productLevelDiscounts.FirstOrDefault(discount => discount.AppliesTo(additionalStorageItem)) + } + : null; + + var estimatedTax = await EstimateTaxAsync(subscription); + + return new Cart + { + PasswordManager = new PasswordManagerCartItems + { + Seats = passwordManagerSeats, + AdditionalStorage = additionalStorage + }, + Cadence = PlanCadenceType.Annually, + Discount = cartLevelDiscount, + EstimatedTax = estimatedTax + }; + } + + #region Utilities + + private async Task EstimateTaxAsync(Subscription subscription) + { + try + { + var invoice = await stripeAdapter.CreateInvoicePreviewAsync(new InvoiceCreatePreviewOptions + { + Customer = subscription.Customer.Id, + Subscription = subscription.Id + }); + + return GetCost(invoice.TotalTaxes); + } + catch (StripeException stripeException) when + (stripeException.StripeError.Code == ErrorCodes.InvoiceUpcomingNone) + { + return 0; + } + } + + private static decimal GetCost(OneOf> value) => + value.Match( + item => (item.Price.UnitAmountDecimal ?? 0) / 100M, + taxes => taxes.Sum(invoiceTotalTax => invoiceTotalTax.Amount) / 100M); + + private static (Discount? CartLevel, List ProductLevel) GetStripeDiscounts( + Subscription subscription) + { + var discounts = new List(); + + if (subscription.Customer.Discount.IsValid()) + { + discounts.Add(subscription.Customer.Discount); + } + + discounts.AddRange(subscription.Discounts.Where(discount => discount.IsValid())); + + var cartLevel = new List(); + var productLevel = new List(); + + foreach (var discount in discounts) + { + switch (discount) + { + case { Coupon.AppliesTo.Products: null or { Count: 0 } }: + cartLevel.Add(discount); + break; + case { Coupon.AppliesTo.Products.Count: > 0 }: + productLevel.Add(discount); + break; + } + } + + return (cartLevel.FirstOrDefault(), productLevel); + } + + #endregion +} diff --git a/src/Core/Constants.cs b/src/Core/Constants.cs index c3c009a2d5..7cf00621c1 100644 --- a/src/Core/Constants.cs +++ b/src/Core/Constants.cs @@ -142,8 +142,7 @@ public static class FeatureFlagKeys public const string PM23845_VNextApplicationCache = "pm-24957-refactor-memory-application-cache"; public const string BlockClaimedDomainAccountCreation = "pm-28297-block-uninvited-claimed-domain-registration"; public const string IncreaseBulkReinviteLimitForCloud = "pm-28251-increase-bulk-reinvite-limit-for-cloud"; - public const string BulkRevokeUsersV2 = "pm-28456-bulk-revoke-users-v2"; - public const string PremiumAccessQuery = "pm-21411-premium-access-query"; + public const string PremiumAccessQuery = "pm-29495-refactor-premium-interface"; /* Architecture */ public const string DesktopMigrationMilestone1 = "desktop-ui-migration-milestone-1"; @@ -159,36 +158,25 @@ public static class FeatureFlagKeys public const string Otp6Digits = "pm-18612-otp-6-digits"; public const string PM24579_PreventSsoOnExistingNonCompliantUsers = "pm-24579-prevent-sso-on-existing-non-compliant-users"; public const string DisableAlternateLoginMethods = "pm-22110-disable-alternate-login-methods"; - public const string PM23174ManageAccountRecoveryPermissionDrivesTheNeedToSetMasterPassword = - "pm-23174-manage-account-recovery-permission-drives-the-need-to-set-master-password"; public const string MJMLBasedEmailTemplates = "mjml-based-email-templates"; public const string MjmlWelcomeEmailTemplates = "pm-21741-mjml-welcome-email"; + public const string OrganizationConfirmationEmail = "pm-28402-update-confirmed-to-org-email-template"; public const string MarketingInitiatedPremiumFlow = "pm-26140-marketing-initiated-premium-flow"; public const string RedirectOnSsoRequired = "pm-1632-redirect-on-sso-required"; + public const string PrefetchPasswordPrelogin = "pm-23801-prefetch-password-prelogin"; /* Autofill Team */ - public const string IdpAutoSubmitLogin = "idp-auto-submit-login"; - public const string UseTreeWalkerApiForPageDetailsCollection = "use-tree-walker-api-for-page-details-collection"; - public const string InlineMenuFieldQualification = "inline-menu-field-qualification"; - public const string InlineMenuPositioningImprovements = "inline-menu-positioning-improvements"; public const string SSHAgent = "ssh-agent"; public const string SSHAgentV2 = "ssh-agent-v2"; public const string SSHVersionCheckQAOverride = "ssh-version-check-qa-override"; - public const string GenerateIdentityFillScriptRefactor = "generate-identity-fill-script-refactor"; - public const string DelayFido2PageScriptInitWithinMv2 = "delay-fido2-page-script-init-within-mv2"; - public const string NotificationBarAddLoginImprovements = "notification-bar-add-login-improvements"; - public const string BlockBrowserInjectionsByDomain = "block-browser-injections-by-domain"; public const string NotificationRefresh = "notification-refresh"; - public const string EnableNewCardCombinedExpiryAutofill = "enable-new-card-combined-expiry-autofill"; public const string MacOsNativeCredentialSync = "macos-native-credential-sync"; - public const string InlineMenuTotp = "inline-menu-totp"; public const string WindowsDesktopAutotype = "windows-desktop-autotype"; public const string WindowsDesktopAutotypeGA = "windows-desktop-autotype-ga"; /* Billing Team */ public const string TrialPayment = "PM-8163-trial-payment"; public const string PM25379_UseNewOrganizationMetadataStructure = "pm-25379-use-new-organization-metadata-structure"; - public const string PM24996ImplementUpgradeFromFreeDialog = "pm-24996-implement-upgrade-from-free-dialog"; public const string PM24032_NewNavigationPremiumUpgradeButton = "pm-24032-new-navigation-premium-upgrade-button"; public const string PM23713_PremiumBadgeOpensNewPremiumUpgradeDialog = "pm-23713-premium-badge-opens-new-premium-upgrade-dialog"; public const string PM26793_FetchPremiumPriceFromPricingService = "pm-26793-fetch-premium-price-from-pricing-service"; @@ -196,6 +184,7 @@ public static class FeatureFlagKeys public const string PM26462_Milestone_3 = "pm-26462-milestone-3"; public const string PM28265_EnableReconcileAdditionalStorageJob = "pm-28265-enable-reconcile-additional-storage-job"; public const string PM28265_ReconcileAdditionalStorageJobEnableLiveMode = "pm-28265-reconcile-additional-storage-job-enable-live-mode"; + public const string PM29594_UpdateIndividualSubscriptionPage = "pm-29594-update-individual-subscription-page"; /* Key Management Team */ public const string PrivateKeyRegeneration = "pm-12241-private-key-regeneration"; @@ -212,6 +201,8 @@ public static class FeatureFlagKeys public const string V2RegistrationTDEJIT = "pm-27279-v2-registration-tde-jit"; public const string DataRecoveryTool = "pm-28813-data-recovery-tool"; public const string EnableAccountEncryptionV2KeyConnectorRegistration = "enable-account-encryption-v2-key-connector-registration"; + public const string SdkKeyRotation = "pm-30144-sdk-key-rotation"; + public const string EnableAccountEncryptionV2JitPasswordRegistration = "enable-account-encryption-v2-jit-password-registration"; /* Mobile Team */ public const string AndroidImportLoginsFlow = "import-logins-flow"; @@ -234,7 +225,10 @@ public static class FeatureFlagKeys public const string PushNotificationsWhenInactive = "pm-25130-receive-push-notifications-for-inactive-users"; /* Tools Team */ - public const string DesktopSendUIRefresh = "desktop-send-ui-refresh"; + /// + /// Enable this flag to share the send view used by the web and browser clients + /// on the desktop client. + /// public const string UseSdkPasswordGenerators = "pm-19976-use-sdk-password-generators"; public const string UseChromiumImporter = "pm-23982-chromium-importer"; public const string ChromiumImporterWithABE = "pm-25855-chromium-importer-abe"; @@ -252,18 +246,21 @@ public static class FeatureFlagKeys public const string VaultLoadingSkeletons = "pm-25081-vault-skeleton-loaders"; public const string BrowserPremiumSpotlight = "pm-23384-browser-premium-spotlight"; public const string MigrateMyVaultToMyItems = "pm-20558-migrate-myvault-to-myitems"; + public const string PM27632_CipherCrudOperationsToSdk = "pm-27632-cipher-crud-operations-to-sdk"; /* Innovation Team */ public const string ArchiveVaultItems = "pm-19148-innovation-archive"; /* DIRT Team */ - public const string PM22887_RiskInsightsActivityTab = "pm-22887-risk-insights-activity-tab"; public const string EventManagementForDataDogAndCrowdStrike = "event-management-for-datadog-and-crowdstrike"; public const string EventDiagnosticLogging = "pm-27666-siem-event-log-debugging"; /* UIF Team */ public const string RouterFocusManagement = "router-focus-management"; + /* Secrets Manager Team */ + public const string SM1719_RemoveSecretsManagerAds = "sm-1719-remove-secrets-manager-ads"; + public static List GetAllKeys() { return typeof(FeatureFlagKeys).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) diff --git a/src/Core/Core.csproj b/src/Core/Core.csproj index 1313637219..a423d9377d 100644 --- a/src/Core/Core.csproj +++ b/src/Core/Core.csproj @@ -3,6 +3,8 @@ false bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml + + $(WarningsNotAsErrors);CA1304;CA1305 @@ -36,7 +38,7 @@ - + diff --git a/src/Core/AdminConsole/Entities/OrganizationIntegration.cs b/src/Core/Dirt/Entities/OrganizationIntegration.cs similarity index 83% rename from src/Core/AdminConsole/Entities/OrganizationIntegration.cs rename to src/Core/Dirt/Entities/OrganizationIntegration.cs index f1c96c8b98..42b4e89e27 100644 --- a/src/Core/AdminConsole/Entities/OrganizationIntegration.cs +++ b/src/Core/Dirt/Entities/OrganizationIntegration.cs @@ -1,8 +1,8 @@ -using Bit.Core.Entities; -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; +using Bit.Core.Entities; using Bit.Core.Utilities; -namespace Bit.Core.AdminConsole.Entities; +namespace Bit.Core.Dirt.Entities; public class OrganizationIntegration : ITableObject { diff --git a/src/Core/AdminConsole/Entities/OrganizationIntegrationConfiguration.cs b/src/Core/Dirt/Entities/OrganizationIntegrationConfiguration.cs similarity index 93% rename from src/Core/AdminConsole/Entities/OrganizationIntegrationConfiguration.cs rename to src/Core/Dirt/Entities/OrganizationIntegrationConfiguration.cs index a9ce676062..2b8dbf9220 100644 --- a/src/Core/AdminConsole/Entities/OrganizationIntegrationConfiguration.cs +++ b/src/Core/Dirt/Entities/OrganizationIntegrationConfiguration.cs @@ -2,7 +2,7 @@ using Bit.Core.Enums; using Bit.Core.Utilities; -namespace Bit.Core.AdminConsole.Entities; +namespace Bit.Core.Dirt.Entities; public class OrganizationIntegrationConfiguration : ITableObject { diff --git a/src/Core/Dirt/Enums/EventType.cs b/src/Core/Dirt/Enums/EventType.cs index 916f408fe6..61372fc4e0 100644 --- a/src/Core/Dirt/Enums/EventType.cs +++ b/src/Core/Dirt/Enums/EventType.cs @@ -61,6 +61,7 @@ public enum EventType : int OrganizationUser_Deleted = 1515, // Both user and organization user data were deleted OrganizationUser_Left = 1516, // User voluntarily left the organization OrganizationUser_AutomaticallyConfirmed = 1517, + OrganizationUser_SelfRevoked = 1518, // User self-revoked due to declining organization data ownership policy Organization_Updated = 1600, Organization_PurgedVault = 1601, diff --git a/src/Core/AdminConsole/Enums/IntegrationType.cs b/src/Core/Dirt/Enums/IntegrationType.cs similarity index 96% rename from src/Core/AdminConsole/Enums/IntegrationType.cs rename to src/Core/Dirt/Enums/IntegrationType.cs index 84e4de94e9..767f2feb06 100644 --- a/src/Core/AdminConsole/Enums/IntegrationType.cs +++ b/src/Core/Dirt/Enums/IntegrationType.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.Enums; +namespace Bit.Core.Dirt.Enums; public enum IntegrationType : int { diff --git a/src/Core/AdminConsole/Enums/OrganizationIntegrationStatus.cs b/src/Core/Dirt/Enums/OrganizationIntegrationStatus.cs similarity index 66% rename from src/Core/AdminConsole/Enums/OrganizationIntegrationStatus.cs rename to src/Core/Dirt/Enums/OrganizationIntegrationStatus.cs index 78a7bc6d63..aad0530971 100644 --- a/src/Core/AdminConsole/Enums/OrganizationIntegrationStatus.cs +++ b/src/Core/Dirt/Enums/OrganizationIntegrationStatus.cs @@ -1,4 +1,4 @@ -namespace Bit.Api.AdminConsole.Models.Response.Organizations; +namespace Bit.Core.Dirt.Enums; public enum OrganizationIntegrationStatus : int { diff --git a/src/Core/AdminConsole/EventIntegrations/EventIntegrationsServiceCollectionExtensions.cs b/src/Core/Dirt/EventIntegrations/EventIntegrationsServiceCollectionExtensions.cs similarity index 98% rename from src/Core/AdminConsole/EventIntegrations/EventIntegrationsServiceCollectionExtensions.cs rename to src/Core/Dirt/EventIntegrations/EventIntegrationsServiceCollectionExtensions.cs index ebeef44484..b03a68cfa6 100644 --- a/src/Core/AdminConsole/EventIntegrations/EventIntegrationsServiceCollectionExtensions.cs +++ b/src/Core/Dirt/EventIntegrations/EventIntegrationsServiceCollectionExtensions.cs @@ -1,13 +1,15 @@ using Azure.Messaging.ServiceBus; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; -using Bit.Core.AdminConsole.Models.Teams; using Bit.Core.AdminConsole.Repositories; -using Bit.Core.AdminConsole.Services; -using Bit.Core.AdminConsole.Services.NoopImplementations; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Core.Dirt.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.Teams; +using Bit.Core.Dirt.Repositories; +using Bit.Core.Dirt.Services; +using Bit.Core.Dirt.Services.Implementations; +using Bit.Core.Dirt.Services.NoopImplementations; using Bit.Core.Repositories; using Bit.Core.Services; using Bit.Core.Settings; diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/CreateOrganizationIntegrationConfigurationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/CreateOrganizationIntegrationConfigurationCommand.cs similarity index 89% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/CreateOrganizationIntegrationConfigurationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/CreateOrganizationIntegrationConfigurationCommand.cs index cb3ce8b9ea..478b43bb7e 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/CreateOrganizationIntegrationConfigurationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/CreateOrganizationIntegrationConfigurationCommand.cs @@ -1,13 +1,13 @@ -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; -using Bit.Core.AdminConsole.Services; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +using Bit.Core.Dirt.Repositories; +using Bit.Core.Dirt.Services; using Bit.Core.Exceptions; -using Bit.Core.Repositories; using Bit.Core.Utilities; using Microsoft.Extensions.DependencyInjection; using ZiggyCreatures.Caching.Fusion; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations; /// /// Command implementation for creating organization integration configurations with validation and cache invalidation support. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/DeleteOrganizationIntegrationConfigurationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/DeleteOrganizationIntegrationConfigurationCommand.cs similarity index 90% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/DeleteOrganizationIntegrationConfigurationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/DeleteOrganizationIntegrationConfigurationCommand.cs index 78768fd0d4..d6369f1b1b 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/DeleteOrganizationIntegrationConfigurationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/DeleteOrganizationIntegrationConfigurationCommand.cs @@ -1,11 +1,11 @@ -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +using Bit.Core.Dirt.Repositories; using Bit.Core.Exceptions; -using Bit.Core.Repositories; using Bit.Core.Utilities; using Microsoft.Extensions.DependencyInjection; using ZiggyCreatures.Caching.Fusion; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations; /// /// Command implementation for deleting organization integration configurations with cache invalidation support. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/GetOrganizationIntegrationConfigurationsQuery.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/GetOrganizationIntegrationConfigurationsQuery.cs similarity index 78% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/GetOrganizationIntegrationConfigurationsQuery.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/GetOrganizationIntegrationConfigurationsQuery.cs index a2078c3c98..6dfe2949a4 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/GetOrganizationIntegrationConfigurationsQuery.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/GetOrganizationIntegrationConfigurationsQuery.cs @@ -1,9 +1,9 @@ -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +using Bit.Core.Dirt.Repositories; using Bit.Core.Exceptions; -using Bit.Core.Repositories; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations; /// /// Query implementation for retrieving organization integration configurations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/ICreateOrganizationIntegrationConfigurationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/ICreateOrganizationIntegrationConfigurationCommand.cs similarity index 88% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/ICreateOrganizationIntegrationConfigurationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/ICreateOrganizationIntegrationConfigurationCommand.cs index 140cc79d1a..629a1ee8ed 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/ICreateOrganizationIntegrationConfigurationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/ICreateOrganizationIntegrationConfigurationCommand.cs @@ -1,6 +1,6 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; /// /// Command interface for creating organization integration configurations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IDeleteOrganizationIntegrationConfigurationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IDeleteOrganizationIntegrationConfigurationCommand.cs similarity index 89% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IDeleteOrganizationIntegrationConfigurationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IDeleteOrganizationIntegrationConfigurationCommand.cs index 3970676d40..d6866443c2 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IDeleteOrganizationIntegrationConfigurationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IDeleteOrganizationIntegrationConfigurationCommand.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; /// /// Command interface for deleting organization integration configurations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IGetOrganizationIntegrationConfigurationsQuery.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IGetOrganizationIntegrationConfigurationsQuery.cs similarity index 85% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IGetOrganizationIntegrationConfigurationsQuery.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IGetOrganizationIntegrationConfigurationsQuery.cs index 2bf806c458..a6635cb3be 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IGetOrganizationIntegrationConfigurationsQuery.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IGetOrganizationIntegrationConfigurationsQuery.cs @@ -1,6 +1,6 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; /// /// Query interface for retrieving organization integration configurations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IUpdateOrganizationIntegrationConfigurationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IUpdateOrganizationIntegrationConfigurationCommand.cs similarity index 90% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IUpdateOrganizationIntegrationConfigurationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IUpdateOrganizationIntegrationConfigurationCommand.cs index 3e60a0af07..3ed680b808 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IUpdateOrganizationIntegrationConfigurationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/Interfaces/IUpdateOrganizationIntegrationConfigurationCommand.cs @@ -1,6 +1,6 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; /// /// Command interface for updating organization integration configurations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/UpdateOrganizationIntegrationConfigurationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/UpdateOrganizationIntegrationConfigurationCommand.cs similarity index 92% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/UpdateOrganizationIntegrationConfigurationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/UpdateOrganizationIntegrationConfigurationCommand.cs index f619e2ddf2..69c28f3e7e 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrationConfigurations/UpdateOrganizationIntegrationConfigurationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrationConfigurations/UpdateOrganizationIntegrationConfigurationCommand.cs @@ -1,13 +1,13 @@ -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; -using Bit.Core.AdminConsole.Services; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations.Interfaces; +using Bit.Core.Dirt.Repositories; +using Bit.Core.Dirt.Services; using Bit.Core.Exceptions; -using Bit.Core.Repositories; using Bit.Core.Utilities; using Microsoft.Extensions.DependencyInjection; using ZiggyCreatures.Caching.Fusion; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrationConfigurations; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrationConfigurations; /// /// Command implementation for updating organization integration configurations with validation and cache invalidation support. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/CreateOrganizationIntegrationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/CreateOrganizationIntegrationCommand.cs similarity index 85% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/CreateOrganizationIntegrationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrations/CreateOrganizationIntegrationCommand.cs index 376451977c..4423c103f9 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/CreateOrganizationIntegrationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/CreateOrganizationIntegrationCommand.cs @@ -1,12 +1,12 @@ -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Core.Dirt.Repositories; using Bit.Core.Exceptions; -using Bit.Core.Repositories; using Bit.Core.Utilities; using Microsoft.Extensions.DependencyInjection; using ZiggyCreatures.Caching.Fusion; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations; /// /// Command implementation for creating organization integrations with cache invalidation support. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/DeleteOrganizationIntegrationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/DeleteOrganizationIntegrationCommand.cs similarity index 85% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/DeleteOrganizationIntegrationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrations/DeleteOrganizationIntegrationCommand.cs index 614693cd82..dc1e7fb1dc 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/DeleteOrganizationIntegrationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/DeleteOrganizationIntegrationCommand.cs @@ -1,11 +1,11 @@ -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Core.Dirt.Repositories; using Bit.Core.Exceptions; -using Bit.Core.Repositories; using Bit.Core.Utilities; using Microsoft.Extensions.DependencyInjection; using ZiggyCreatures.Caching.Fusion; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations; /// /// Command implementation for deleting organization integrations with cache invalidation support. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/GetOrganizationIntegrationsQuery.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/GetOrganizationIntegrationsQuery.cs similarity index 68% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/GetOrganizationIntegrationsQuery.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrations/GetOrganizationIntegrationsQuery.cs index f7bbaadb4a..807f0b0b59 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/GetOrganizationIntegrationsQuery.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/GetOrganizationIntegrationsQuery.cs @@ -1,8 +1,8 @@ -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; -using Bit.Core.Repositories; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Core.Dirt.Repositories; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations; /// /// Query implementation for retrieving organization integrations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/ICreateOrganizationIntegrationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/ICreateOrganizationIntegrationCommand.cs similarity index 83% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/ICreateOrganizationIntegrationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/ICreateOrganizationIntegrationCommand.cs index e7b79eab13..0b06d79bdb 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/ICreateOrganizationIntegrationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/ICreateOrganizationIntegrationCommand.cs @@ -1,6 +1,6 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; /// /// Command interface for creating an OrganizationIntegration. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IDeleteOrganizationIntegrationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IDeleteOrganizationIntegrationCommand.cs similarity index 87% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IDeleteOrganizationIntegrationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IDeleteOrganizationIntegrationCommand.cs index be22b4e482..8640f03ec8 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IDeleteOrganizationIntegrationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IDeleteOrganizationIntegrationCommand.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; /// /// Command interface for deleting organization integrations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IGetOrganizationIntegrationsQuery.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IGetOrganizationIntegrationsQuery.cs similarity index 80% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IGetOrganizationIntegrationsQuery.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IGetOrganizationIntegrationsQuery.cs index 8cdea7f301..1f378abe9b 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IGetOrganizationIntegrationsQuery.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IGetOrganizationIntegrationsQuery.cs @@ -1,6 +1,6 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; /// /// Query interface for retrieving organization integrations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IUpdateOrganizationIntegrationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IUpdateOrganizationIntegrationCommand.cs similarity index 87% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IUpdateOrganizationIntegrationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IUpdateOrganizationIntegrationCommand.cs index f40086600d..ddba2bd233 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/Interfaces/IUpdateOrganizationIntegrationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/Interfaces/IUpdateOrganizationIntegrationCommand.cs @@ -1,6 +1,6 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; /// /// Command interface for updating organization integrations. diff --git a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/UpdateOrganizationIntegrationCommand.cs b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/UpdateOrganizationIntegrationCommand.cs similarity index 86% rename from src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/UpdateOrganizationIntegrationCommand.cs rename to src/Core/Dirt/EventIntegrations/OrganizationIntegrations/UpdateOrganizationIntegrationCommand.cs index 12a8620926..77a3448276 100644 --- a/src/Core/AdminConsole/EventIntegrations/OrganizationIntegrations/UpdateOrganizationIntegrationCommand.cs +++ b/src/Core/Dirt/EventIntegrations/OrganizationIntegrations/UpdateOrganizationIntegrationCommand.cs @@ -1,12 +1,12 @@ -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations.Interfaces; +using Bit.Core.Dirt.Repositories; using Bit.Core.Exceptions; -using Bit.Core.Repositories; using Bit.Core.Utilities; using Microsoft.Extensions.DependencyInjection; using ZiggyCreatures.Caching.Fusion; -namespace Bit.Core.AdminConsole.EventIntegrations.OrganizationIntegrations; +namespace Bit.Core.Dirt.EventIntegrations.OrganizationIntegrations; /// /// Command implementation for updating organization integrations with cache invalidation support. diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/README.md b/src/Core/Dirt/EventIntegrations/README.md similarity index 100% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/README.md rename to src/Core/Dirt/EventIntegrations/README.md diff --git a/src/Core/Dirt/Models/Data/EventIntegrations/DatadogIntegration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/DatadogIntegration.cs new file mode 100644 index 0000000000..69a4deb66b --- /dev/null +++ b/src/Core/Dirt/Models/Data/EventIntegrations/DatadogIntegration.cs @@ -0,0 +1,3 @@ +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; + +public record DatadogIntegration(string ApiKey, Uri Uri); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogIntegrationConfigurationDetails.cs b/src/Core/Dirt/Models/Data/EventIntegrations/DatadogIntegrationConfigurationDetails.cs similarity index 54% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogIntegrationConfigurationDetails.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/DatadogIntegrationConfigurationDetails.cs index 07aafa4bd8..ed91c3828b 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogIntegrationConfigurationDetails.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/DatadogIntegrationConfigurationDetails.cs @@ -1,3 +1,3 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public record DatadogIntegrationConfigurationDetails(string ApiKey, Uri Uri); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/DatadogListenerConfiguration.cs similarity index 91% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/DatadogListenerConfiguration.cs index 1c74826791..ce35e29927 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/DatadogListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/DatadogListenerConfiguration.cs @@ -1,7 +1,7 @@ -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; using Bit.Core.Settings; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class DatadogListenerConfiguration(GlobalSettings globalSettings) : ListenerConfiguration(globalSettings), IIntegrationListenerConfiguration diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/HecIntegration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/HecIntegration.cs similarity index 58% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/HecIntegration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/HecIntegration.cs index 33ae5dadbe..df943e0bfc 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/HecIntegration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/HecIntegration.cs @@ -1,3 +1,3 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public record HecIntegration(Uri Uri, string Scheme, string Token, string? Service = null); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/HecListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/HecListenerConfiguration.cs similarity index 91% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/HecListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/HecListenerConfiguration.cs index 37a0d68beb..5ceb42be64 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/HecListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/HecListenerConfiguration.cs @@ -1,7 +1,7 @@ -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; using Bit.Core.Settings; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class HecListenerConfiguration(GlobalSettings globalSettings) : ListenerConfiguration(globalSettings), IIntegrationListenerConfiguration diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IEventListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IEventListenerConfiguration.cs similarity index 80% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IEventListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IEventListenerConfiguration.cs index 7df1459941..206dc2cc0b 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IEventListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IEventListenerConfiguration.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public interface IEventListenerConfiguration { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IIntegrationListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IIntegrationListenerConfiguration.cs similarity index 86% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IIntegrationListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IIntegrationListenerConfiguration.cs index 30401bb072..1fbfefa420 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IIntegrationListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IIntegrationListenerConfiguration.cs @@ -1,6 +1,6 @@ -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public interface IIntegrationListenerConfiguration : IEventListenerConfiguration { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IIntegrationMessage.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IIntegrationMessage.cs similarity index 77% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IIntegrationMessage.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IIntegrationMessage.cs index 5b6bfe2e53..2d333dfee4 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IIntegrationMessage.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IIntegrationMessage.cs @@ -1,6 +1,6 @@ -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public interface IIntegrationMessage { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFailureCategory.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFailureCategory.cs similarity index 93% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFailureCategory.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFailureCategory.cs index 544e671d51..f9d8f2ab68 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFailureCategory.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFailureCategory.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; /// /// Categories of event integration failures used for classification and retry logic. diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterGroup.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterGroup.cs similarity index 76% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterGroup.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterGroup.cs index 276ca3a14b..0c129883cf 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterGroup.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterGroup.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class IntegrationFilterGroup { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterOperation.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterOperation.cs similarity index 61% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterOperation.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterOperation.cs index fddf630e26..d98ab1e13e 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterOperation.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterOperation.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public enum IntegrationFilterOperation { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterRule.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterRule.cs similarity index 76% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterRule.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterRule.cs index b5f90f5e63..9ac3ef753e 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationFilterRule.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationFilterRule.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class IntegrationFilterRule { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationHandlerResult.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationHandlerResult.cs similarity index 97% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationHandlerResult.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IntegrationHandlerResult.cs index 375f2489cb..bbdce50ec0 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationHandlerResult.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationHandlerResult.cs @@ -1,4 +1,4 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; /// /// Represents the result of an integration handler operation, including success status, diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationMessage.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationMessage.cs similarity index 93% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationMessage.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IntegrationMessage.cs index b0fc2161ba..edf31a2a1f 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationMessage.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationMessage.cs @@ -1,7 +1,7 @@ using System.Text.Json; -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class IntegrationMessage : IIntegrationMessage { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationOAuthState.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationOAuthState.cs similarity index 95% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationOAuthState.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IntegrationOAuthState.cs index 3b29bbebb4..d75780d6c6 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationOAuthState.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationOAuthState.cs @@ -1,8 +1,8 @@ using System.Security.Cryptography; using System.Text; -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class IntegrationOAuthState { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationTemplateContext.cs b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationTemplateContext.cs similarity index 97% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationTemplateContext.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/IntegrationTemplateContext.cs index c44e550d15..3b527469fa 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/IntegrationTemplateContext.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/IntegrationTemplateContext.cs @@ -4,7 +4,7 @@ using Bit.Core.Enums; using Bit.Core.Models.Data; using Bit.Core.Models.Data.Organizations.OrganizationUsers; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class IntegrationTemplateContext(EventMessage eventMessage) { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/ListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/ListenerConfiguration.cs similarity index 94% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/ListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/ListenerConfiguration.cs index 40eb2b3e77..2a970ce670 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/ListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/ListenerConfiguration.cs @@ -1,6 +1,6 @@ using Bit.Core.Settings; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public abstract class ListenerConfiguration { diff --git a/src/Core/AdminConsole/Models/Data/Organizations/OrganizationIntegrationConfigurationDetails.cs b/src/Core/Dirt/Models/Data/EventIntegrations/OrganizationIntegrationConfigurationDetails.cs similarity index 95% rename from src/Core/AdminConsole/Models/Data/Organizations/OrganizationIntegrationConfigurationDetails.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/OrganizationIntegrationConfigurationDetails.cs index 5fdc760c90..6517ceccf0 100644 --- a/src/Core/AdminConsole/Models/Data/Organizations/OrganizationIntegrationConfigurationDetails.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/OrganizationIntegrationConfigurationDetails.cs @@ -1,9 +1,8 @@ using System.Text.Json.Nodes; +using Bit.Core.Dirt.Enums; using Bit.Core.Enums; -#nullable enable - -namespace Bit.Core.Models.Data.Organizations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class OrganizationIntegrationConfigurationDetails { diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/RepositoryListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/RepositoryListenerConfiguration.cs similarity index 87% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/RepositoryListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/RepositoryListenerConfiguration.cs index 118b3a17fe..20299dd651 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/RepositoryListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/RepositoryListenerConfiguration.cs @@ -1,6 +1,6 @@ using Bit.Core.Settings; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class RepositoryListenerConfiguration(GlobalSettings globalSettings) : ListenerConfiguration(globalSettings), IEventListenerConfiguration diff --git a/src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegration.cs new file mode 100644 index 0000000000..fcfd07f574 --- /dev/null +++ b/src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegration.cs @@ -0,0 +1,3 @@ +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; + +public record SlackIntegration(string Token); diff --git a/src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegrationConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegrationConfiguration.cs new file mode 100644 index 0000000000..164a132e8c --- /dev/null +++ b/src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegrationConfiguration.cs @@ -0,0 +1,3 @@ +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; + +public record SlackIntegrationConfiguration(string ChannelId); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegrationConfigurationDetails.cs b/src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegrationConfigurationDetails.cs similarity index 56% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegrationConfigurationDetails.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegrationConfigurationDetails.cs index d22f43bb92..b81617118d 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackIntegrationConfigurationDetails.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/SlackIntegrationConfigurationDetails.cs @@ -1,3 +1,3 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public record SlackIntegrationConfigurationDetails(string ChannelId, string Token); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/SlackListenerConfiguration.cs similarity index 91% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/SlackListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/SlackListenerConfiguration.cs index 7dd834f51e..ef2cf83837 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/SlackListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/SlackListenerConfiguration.cs @@ -1,7 +1,7 @@ -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; using Bit.Core.Settings; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class SlackListenerConfiguration(GlobalSettings globalSettings) : ListenerConfiguration(globalSettings), IIntegrationListenerConfiguration diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsIntegration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/TeamsIntegration.cs similarity index 71% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsIntegration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/TeamsIntegration.cs index 8390022839..fcb42a5261 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsIntegration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/TeamsIntegration.cs @@ -1,6 +1,6 @@ -using Bit.Core.Models.Teams; +using Bit.Core.Dirt.Models.Data.Teams; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public record TeamsIntegration( string TenantId, diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsIntegrationConfigurationDetails.cs b/src/Core/Dirt/Models/Data/EventIntegrations/TeamsIntegrationConfigurationDetails.cs similarity index 56% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsIntegrationConfigurationDetails.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/TeamsIntegrationConfigurationDetails.cs index 66fe558dff..a890f553f5 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsIntegrationConfigurationDetails.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/TeamsIntegrationConfigurationDetails.cs @@ -1,3 +1,3 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public record TeamsIntegrationConfigurationDetails(string ChannelId, Uri ServiceUrl); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/TeamsListenerConfiguration.cs similarity index 91% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/TeamsListenerConfiguration.cs index 24cf674648..4111c96601 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/TeamsListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/TeamsListenerConfiguration.cs @@ -1,7 +1,7 @@ -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; using Bit.Core.Settings; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class TeamsListenerConfiguration(GlobalSettings globalSettings) : ListenerConfiguration(globalSettings), IIntegrationListenerConfiguration diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegration.cs similarity index 57% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegration.cs index dcda4caa92..d12ea16ee1 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegration.cs @@ -1,3 +1,3 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public record WebhookIntegration(Uri Uri, string? Scheme = null, string? Token = null); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegrationConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegrationConfiguration.cs similarity index 60% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegrationConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegrationConfiguration.cs index 851bd3f411..8d7bf90e2c 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegrationConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegrationConfiguration.cs @@ -1,3 +1,3 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public record WebhookIntegrationConfiguration(Uri Uri, string? Scheme = null, string? Token = null); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegrationConfigurationDetails.cs b/src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegrationConfigurationDetails.cs similarity index 62% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegrationConfigurationDetails.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegrationConfigurationDetails.cs index dba9b1714d..49508f8454 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookIntegrationConfigurationDetails.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/WebhookIntegrationConfigurationDetails.cs @@ -1,3 +1,3 @@ -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public record WebhookIntegrationConfigurationDetails(Uri Uri, string? Scheme = null, string? Token = null); diff --git a/src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookListenerConfiguration.cs b/src/Core/Dirt/Models/Data/EventIntegrations/WebhookListenerConfiguration.cs similarity index 91% rename from src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookListenerConfiguration.cs rename to src/Core/Dirt/Models/Data/EventIntegrations/WebhookListenerConfiguration.cs index 9d5bf811c7..9afc26168c 100644 --- a/src/Core/AdminConsole/Models/Data/EventIntegrations/WebhookListenerConfiguration.cs +++ b/src/Core/Dirt/Models/Data/EventIntegrations/WebhookListenerConfiguration.cs @@ -1,7 +1,7 @@ -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; using Bit.Core.Settings; -namespace Bit.Core.AdminConsole.Models.Data.EventIntegrations; +namespace Bit.Core.Dirt.Models.Data.EventIntegrations; public class WebhookListenerConfiguration(GlobalSettings globalSettings) : ListenerConfiguration(globalSettings), IIntegrationListenerConfiguration diff --git a/src/Core/AdminConsole/Models/Slack/SlackApiResponse.cs b/src/Core/Dirt/Models/Data/Slack/SlackApiResponse.cs similarity index 97% rename from src/Core/AdminConsole/Models/Slack/SlackApiResponse.cs rename to src/Core/Dirt/Models/Data/Slack/SlackApiResponse.cs index 3c811e2b28..a70e623ae3 100644 --- a/src/Core/AdminConsole/Models/Slack/SlackApiResponse.cs +++ b/src/Core/Dirt/Models/Data/Slack/SlackApiResponse.cs @@ -1,6 +1,6 @@ using System.Text.Json.Serialization; -namespace Bit.Core.Models.Slack; +namespace Bit.Core.Dirt.Models.Data.Slack; public abstract class SlackApiResponse { diff --git a/src/Core/AdminConsole/Models/Teams/TeamsApiResponse.cs b/src/Core/Dirt/Models/Data/Teams/TeamsApiResponse.cs similarity index 97% rename from src/Core/AdminConsole/Models/Teams/TeamsApiResponse.cs rename to src/Core/Dirt/Models/Data/Teams/TeamsApiResponse.cs index 131e45264f..b4b6a2542d 100644 --- a/src/Core/AdminConsole/Models/Teams/TeamsApiResponse.cs +++ b/src/Core/Dirt/Models/Data/Teams/TeamsApiResponse.cs @@ -1,6 +1,6 @@ using System.Text.Json.Serialization; -namespace Bit.Core.Models.Teams; +namespace Bit.Core.Dirt.Models.Data.Teams; /// Represents the response returned by the Microsoft OAuth 2.0 token endpoint. /// See Microsoft identity platform and OAuth 2.0 diff --git a/src/Core/AdminConsole/Models/Teams/TeamsBotCredentialProvider.cs b/src/Core/Dirt/Models/Data/Teams/TeamsBotCredentialProvider.cs similarity index 94% rename from src/Core/AdminConsole/Models/Teams/TeamsBotCredentialProvider.cs rename to src/Core/Dirt/Models/Data/Teams/TeamsBotCredentialProvider.cs index eeb17131a3..d8740f9e90 100644 --- a/src/Core/AdminConsole/Models/Teams/TeamsBotCredentialProvider.cs +++ b/src/Core/Dirt/Models/Data/Teams/TeamsBotCredentialProvider.cs @@ -1,6 +1,6 @@ using Microsoft.Bot.Connector.Authentication; -namespace Bit.Core.AdminConsole.Models.Teams; +namespace Bit.Core.Dirt.Models.Data.Teams; public class TeamsBotCredentialProvider(string clientId, string clientSecret) : ICredentialProvider { diff --git a/src/Core/AdminConsole/Repositories/IOrganizationIntegrationConfigurationRepository.cs b/src/Core/Dirt/Repositories/IOrganizationIntegrationConfigurationRepository.cs similarity index 88% rename from src/Core/AdminConsole/Repositories/IOrganizationIntegrationConfigurationRepository.cs rename to src/Core/Dirt/Repositories/IOrganizationIntegrationConfigurationRepository.cs index fb42ffa000..f6f90c7c9f 100644 --- a/src/Core/AdminConsole/Repositories/IOrganizationIntegrationConfigurationRepository.cs +++ b/src/Core/Dirt/Repositories/IOrganizationIntegrationConfigurationRepository.cs @@ -1,8 +1,10 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Bit.Core.Enums; -using Bit.Core.Models.Data.Organizations; +using Bit.Core.Repositories; -namespace Bit.Core.Repositories; +namespace Bit.Core.Dirt.Repositories; public interface IOrganizationIntegrationConfigurationRepository : IRepository { diff --git a/src/Core/AdminConsole/Repositories/IOrganizationIntegrationRepository.cs b/src/Core/Dirt/Repositories/IOrganizationIntegrationRepository.cs similarity index 74% rename from src/Core/AdminConsole/Repositories/IOrganizationIntegrationRepository.cs rename to src/Core/Dirt/Repositories/IOrganizationIntegrationRepository.cs index 1d8b8be0ec..03775e8d20 100644 --- a/src/Core/AdminConsole/Repositories/IOrganizationIntegrationRepository.cs +++ b/src/Core/Dirt/Repositories/IOrganizationIntegrationRepository.cs @@ -1,6 +1,7 @@ -using Bit.Core.AdminConsole.Entities; +using Bit.Core.Dirt.Entities; +using Bit.Core.Repositories; -namespace Bit.Core.Repositories; +namespace Bit.Core.Dirt.Repositories; public interface IOrganizationIntegrationRepository : IRepository { diff --git a/src/Core/AdminConsole/Services/IAzureServiceBusService.cs b/src/Core/Dirt/Services/IAzureServiceBusService.cs similarity index 77% rename from src/Core/AdminConsole/Services/IAzureServiceBusService.cs rename to src/Core/Dirt/Services/IAzureServiceBusService.cs index 75864255c2..6b425511ab 100644 --- a/src/Core/AdminConsole/Services/IAzureServiceBusService.cs +++ b/src/Core/Dirt/Services/IAzureServiceBusService.cs @@ -1,7 +1,7 @@ using Azure.Messaging.ServiceBus; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services; public interface IAzureServiceBusService : IEventIntegrationPublisher, IAsyncDisposable { diff --git a/src/Core/AdminConsole/Services/IEventIntegrationPublisher.cs b/src/Core/Dirt/Services/IEventIntegrationPublisher.cs similarity index 67% rename from src/Core/AdminConsole/Services/IEventIntegrationPublisher.cs rename to src/Core/Dirt/Services/IEventIntegrationPublisher.cs index 4d95707e90..583c2448fe 100644 --- a/src/Core/AdminConsole/Services/IEventIntegrationPublisher.cs +++ b/src/Core/Dirt/Services/IEventIntegrationPublisher.cs @@ -1,6 +1,6 @@ -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services; public interface IEventIntegrationPublisher : IAsyncDisposable { diff --git a/src/Core/AdminConsole/Services/IEventMessageHandler.cs b/src/Core/Dirt/Services/IEventMessageHandler.cs similarity index 85% rename from src/Core/AdminConsole/Services/IEventMessageHandler.cs rename to src/Core/Dirt/Services/IEventMessageHandler.cs index 83c5e33ecb..9b1385129b 100644 --- a/src/Core/AdminConsole/Services/IEventMessageHandler.cs +++ b/src/Core/Dirt/Services/IEventMessageHandler.cs @@ -1,6 +1,6 @@ using Bit.Core.Models.Data; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services; public interface IEventMessageHandler { diff --git a/src/Core/AdminConsole/Services/IIntegrationFilterService.cs b/src/Core/Dirt/Services/IIntegrationFilterService.cs similarity index 67% rename from src/Core/AdminConsole/Services/IIntegrationFilterService.cs rename to src/Core/Dirt/Services/IIntegrationFilterService.cs index 5bc035d468..f46ab83f54 100644 --- a/src/Core/AdminConsole/Services/IIntegrationFilterService.cs +++ b/src/Core/Dirt/Services/IIntegrationFilterService.cs @@ -1,9 +1,9 @@ #nullable enable -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Bit.Core.Models.Data; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services; public interface IIntegrationFilterService { diff --git a/src/Core/AdminConsole/Services/IIntegrationHandler.cs b/src/Core/Dirt/Services/IIntegrationHandler.cs similarity index 98% rename from src/Core/AdminConsole/Services/IIntegrationHandler.cs rename to src/Core/Dirt/Services/IIntegrationHandler.cs index c36081cb52..81103b453d 100644 --- a/src/Core/AdminConsole/Services/IIntegrationHandler.cs +++ b/src/Core/Dirt/Services/IIntegrationHandler.cs @@ -1,8 +1,8 @@ using System.Globalization; using System.Net; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services; public interface IIntegrationHandler { diff --git a/src/Core/AdminConsole/Services/IOrganizationIntegrationConfigurationValidator.cs b/src/Core/Dirt/Services/IOrganizationIntegrationConfigurationValidator.cs similarity index 86% rename from src/Core/AdminConsole/Services/IOrganizationIntegrationConfigurationValidator.cs rename to src/Core/Dirt/Services/IOrganizationIntegrationConfigurationValidator.cs index 48346cbae7..4a3a089f26 100644 --- a/src/Core/AdminConsole/Services/IOrganizationIntegrationConfigurationValidator.cs +++ b/src/Core/Dirt/Services/IOrganizationIntegrationConfigurationValidator.cs @@ -1,7 +1,7 @@ -using Bit.Core.AdminConsole.Entities; -using Bit.Core.Enums; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.Enums; -namespace Bit.Core.AdminConsole.Services; +namespace Bit.Core.Dirt.Services; public interface IOrganizationIntegrationConfigurationValidator { diff --git a/src/Core/AdminConsole/Services/IRabbitMqService.cs b/src/Core/Dirt/Services/IRabbitMqService.cs similarity index 89% rename from src/Core/AdminConsole/Services/IRabbitMqService.cs rename to src/Core/Dirt/Services/IRabbitMqService.cs index 12c40c3b98..b9f824506f 100644 --- a/src/Core/AdminConsole/Services/IRabbitMqService.cs +++ b/src/Core/Dirt/Services/IRabbitMqService.cs @@ -1,8 +1,8 @@ -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using RabbitMQ.Client; using RabbitMQ.Client.Events; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services; public interface IRabbitMqService : IEventIntegrationPublisher { diff --git a/src/Core/AdminConsole/Services/ISlackService.cs b/src/Core/Dirt/Services/ISlackService.cs similarity index 97% rename from src/Core/AdminConsole/Services/ISlackService.cs rename to src/Core/Dirt/Services/ISlackService.cs index 60d3da8af4..111fcb5440 100644 --- a/src/Core/AdminConsole/Services/ISlackService.cs +++ b/src/Core/Dirt/Services/ISlackService.cs @@ -1,6 +1,7 @@ -using Bit.Core.Models.Slack; +using Bit.Core.Dirt.Models.Data.Slack; +using Bit.Core.Dirt.Services.Implementations; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services; /// Defines operations for interacting with Slack, including OAuth authentication, channel discovery, /// and sending messages. diff --git a/src/Core/AdminConsole/Services/ITeamsService.cs b/src/Core/Dirt/Services/ITeamsService.cs similarity index 95% rename from src/Core/AdminConsole/Services/ITeamsService.cs rename to src/Core/Dirt/Services/ITeamsService.cs index e3757987c3..30a324f9a4 100644 --- a/src/Core/AdminConsole/Services/ITeamsService.cs +++ b/src/Core/Dirt/Services/ITeamsService.cs @@ -1,6 +1,7 @@ -using Bit.Core.Models.Teams; +using Bit.Core.Dirt.Models.Data.Teams; +using Bit.Core.Dirt.Services.Implementations; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services; /// /// Service that provides functionality relating to the Microsoft Teams integration including OAuth, diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusEventListenerService.cs b/src/Core/Dirt/Services/Implementations/AzureServiceBusEventListenerService.cs similarity index 89% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusEventListenerService.cs rename to src/Core/Dirt/Services/Implementations/AzureServiceBusEventListenerService.cs index a589211687..6175374e2f 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusEventListenerService.cs +++ b/src/Core/Dirt/Services/Implementations/AzureServiceBusEventListenerService.cs @@ -1,9 +1,9 @@ using System.Text; using Azure.Messaging.ServiceBus; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Microsoft.Extensions.Logging; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class AzureServiceBusEventListenerService : EventLoggingListenerService where TConfiguration : IEventListenerConfiguration @@ -42,7 +42,7 @@ public class AzureServiceBusEventListenerService : EventLoggingL private static ILogger CreateLogger(ILoggerFactory loggerFactory, TConfiguration configuration) { return loggerFactory.CreateLogger( - categoryName: $"Bit.Core.Services.AzureServiceBusEventListenerService.{configuration.EventSubscriptionName}"); + categoryName: $"Bit.Core.Dirt.Services.Implementations.AzureServiceBusEventListenerService.{configuration.EventSubscriptionName}"); } internal Task ProcessErrorAsync(ProcessErrorEventArgs args) diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusIntegrationListenerService.cs b/src/Core/Dirt/Services/Implementations/AzureServiceBusIntegrationListenerService.cs similarity index 94% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusIntegrationListenerService.cs rename to src/Core/Dirt/Services/Implementations/AzureServiceBusIntegrationListenerService.cs index c97c5f7efe..32132ddb37 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusIntegrationListenerService.cs +++ b/src/Core/Dirt/Services/Implementations/AzureServiceBusIntegrationListenerService.cs @@ -1,9 +1,9 @@ using Azure.Messaging.ServiceBus; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class AzureServiceBusIntegrationListenerService : BackgroundService where TConfiguration : IIntegrationListenerConfiguration @@ -23,7 +23,7 @@ public class AzureServiceBusIntegrationListenerService : Backgro { _handler = handler; _logger = loggerFactory.CreateLogger( - categoryName: $"Bit.Core.Services.AzureServiceBusIntegrationListenerService.{configuration.IntegrationSubscriptionName}"); + categoryName: $"Bit.Core.Dirt.Services.Implementations.AzureServiceBusIntegrationListenerService.{configuration.IntegrationSubscriptionName}"); _maxRetries = configuration.MaxRetries; _serviceBusService = serviceBusService; diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusService.cs b/src/Core/Dirt/Services/Implementations/AzureServiceBusService.cs similarity index 94% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusService.cs rename to src/Core/Dirt/Services/Implementations/AzureServiceBusService.cs index 953a9bb56e..7b87850fe3 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/AzureServiceBusService.cs +++ b/src/Core/Dirt/Services/Implementations/AzureServiceBusService.cs @@ -1,9 +1,9 @@ using Azure.Messaging.ServiceBus; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Bit.Core.Settings; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class AzureServiceBusService : IAzureServiceBusService { diff --git a/src/Core/AdminConsole/Services/Implementations/AzureTableStorageEventHandler.cs b/src/Core/Dirt/Services/Implementations/AzureTableStorageEventHandler.cs similarity index 84% rename from src/Core/AdminConsole/Services/Implementations/AzureTableStorageEventHandler.cs rename to src/Core/Dirt/Services/Implementations/AzureTableStorageEventHandler.cs index 578dde9485..73d22b21a7 100644 --- a/src/Core/AdminConsole/Services/Implementations/AzureTableStorageEventHandler.cs +++ b/src/Core/Dirt/Services/Implementations/AzureTableStorageEventHandler.cs @@ -1,9 +1,8 @@ -#nullable enable - -using Bit.Core.Models.Data; +using Bit.Core.Models.Data; +using Bit.Core.Services; using Microsoft.Extensions.DependencyInjection; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class AzureTableStorageEventHandler( [FromKeyedServices("persistent")] IEventWriteService eventWriteService) diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/DatadogIntegrationHandler.cs b/src/Core/Dirt/Services/Implementations/DatadogIntegrationHandler.cs similarity index 90% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/DatadogIntegrationHandler.cs rename to src/Core/Dirt/Services/Implementations/DatadogIntegrationHandler.cs index 45bb5b6d7d..e5c684ceec 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/DatadogIntegrationHandler.cs +++ b/src/Core/Dirt/Services/Implementations/DatadogIntegrationHandler.cs @@ -1,7 +1,7 @@ using System.Text; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class DatadogIntegrationHandler( IHttpClientFactory httpClientFactory, diff --git a/src/Core/Dirt/Services/Implementations/EventIntegrationEventWriteService.cs b/src/Core/Dirt/Services/Implementations/EventIntegrationEventWriteService.cs index 4ac97df763..44e0513ee0 100644 --- a/src/Core/Dirt/Services/Implementations/EventIntegrationEventWriteService.cs +++ b/src/Core/Dirt/Services/Implementations/EventIntegrationEventWriteService.cs @@ -1,7 +1,8 @@ using System.Text.Json; using Bit.Core.Models.Data; +using Bit.Core.Services; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class EventIntegrationEventWriteService : IEventWriteService, IAsyncDisposable { private readonly IEventIntegrationPublisher _eventIntegrationPublisher; diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/EventIntegrationHandler.cs b/src/Core/Dirt/Services/Implementations/EventIntegrationHandler.cs similarity index 97% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/EventIntegrationHandler.cs rename to src/Core/Dirt/Services/Implementations/EventIntegrationHandler.cs index b4246884f7..bcd1f1dd8c 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/EventIntegrationHandler.cs +++ b/src/Core/Dirt/Services/Implementations/EventIntegrationHandler.cs @@ -1,18 +1,18 @@ using System.Text.Json; using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; using Bit.Core.AdminConsole.Repositories; using Bit.Core.AdminConsole.Utilities; -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Repositories; using Bit.Core.Models.Data; -using Bit.Core.Models.Data.Organizations; using Bit.Core.Models.Data.Organizations.OrganizationUsers; using Bit.Core.Repositories; using Bit.Core.Utilities; using Microsoft.Extensions.Logging; using ZiggyCreatures.Caching.Fusion; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class EventIntegrationHandler( IntegrationType integrationType, diff --git a/src/Core/AdminConsole/Services/EventLoggingListenerService.cs b/src/Core/Dirt/Services/Implementations/EventLoggingListenerService.cs similarity index 97% rename from src/Core/AdminConsole/Services/EventLoggingListenerService.cs rename to src/Core/Dirt/Services/Implementations/EventLoggingListenerService.cs index 84a862ce94..29e3f8dec3 100644 --- a/src/Core/AdminConsole/Services/EventLoggingListenerService.cs +++ b/src/Core/Dirt/Services/Implementations/EventLoggingListenerService.cs @@ -1,11 +1,9 @@ -#nullable enable - -using System.Text.Json; +using System.Text.Json; using Bit.Core.Models.Data; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public abstract class EventLoggingListenerService : BackgroundService { diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/EventRepositoryHandler.cs b/src/Core/Dirt/Services/Implementations/EventRepositoryHandler.cs similarity index 87% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/EventRepositoryHandler.cs rename to src/Core/Dirt/Services/Implementations/EventRepositoryHandler.cs index ee3a2d5db2..32173b8da0 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/EventRepositoryHandler.cs +++ b/src/Core/Dirt/Services/Implementations/EventRepositoryHandler.cs @@ -1,7 +1,8 @@ using Bit.Core.Models.Data; +using Bit.Core.Services; using Microsoft.Extensions.DependencyInjection; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class EventRepositoryHandler( [FromKeyedServices("persistent")] IEventWriteService eventWriteService) diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/IntegrationFilterFactory.cs b/src/Core/Dirt/Services/Implementations/IntegrationFilterFactory.cs similarity index 97% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/IntegrationFilterFactory.cs rename to src/Core/Dirt/Services/Implementations/IntegrationFilterFactory.cs index d28ac910b7..8c25c80208 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/IntegrationFilterFactory.cs +++ b/src/Core/Dirt/Services/Implementations/IntegrationFilterFactory.cs @@ -1,7 +1,7 @@ using System.Linq.Expressions; using Bit.Core.Models.Data; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public delegate bool IntegrationFilter(EventMessage message, object? value); diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/IntegrationFilterService.cs b/src/Core/Dirt/Services/Implementations/IntegrationFilterService.cs similarity index 97% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/IntegrationFilterService.cs rename to src/Core/Dirt/Services/Implementations/IntegrationFilterService.cs index 1c8fae4000..7d56b7c7ce 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/IntegrationFilterService.cs +++ b/src/Core/Dirt/Services/Implementations/IntegrationFilterService.cs @@ -1,8 +1,8 @@ using System.Text.Json; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Bit.Core.Models.Data; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class IntegrationFilterService : IIntegrationFilterService { diff --git a/src/Core/AdminConsole/Services/OrganizationIntegrationConfigurationValidator.cs b/src/Core/Dirt/Services/Implementations/OrganizationIntegrationConfigurationValidator.cs similarity index 92% rename from src/Core/AdminConsole/Services/OrganizationIntegrationConfigurationValidator.cs rename to src/Core/Dirt/Services/Implementations/OrganizationIntegrationConfigurationValidator.cs index 2769565675..7b6ab320b8 100644 --- a/src/Core/AdminConsole/Services/OrganizationIntegrationConfigurationValidator.cs +++ b/src/Core/Dirt/Services/Implementations/OrganizationIntegrationConfigurationValidator.cs @@ -1,9 +1,9 @@ using System.Text.Json; -using Bit.Core.AdminConsole.Entities; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; -using Bit.Core.Enums; +using Bit.Core.Dirt.Entities; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; -namespace Bit.Core.AdminConsole.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class OrganizationIntegrationConfigurationValidator : IOrganizationIntegrationConfigurationValidator { diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqEventListenerService.cs b/src/Core/Dirt/Services/Implementations/RabbitMqEventListenerService.cs similarity index 91% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqEventListenerService.cs rename to src/Core/Dirt/Services/Implementations/RabbitMqEventListenerService.cs index 430540a2f7..ca7cd5ef16 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqEventListenerService.cs +++ b/src/Core/Dirt/Services/Implementations/RabbitMqEventListenerService.cs @@ -1,10 +1,10 @@ using System.Text; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class RabbitMqEventListenerService : EventLoggingListenerService where TConfiguration : IEventListenerConfiguration @@ -69,6 +69,6 @@ public class RabbitMqEventListenerService : EventLoggingListener private static ILogger CreateLogger(ILoggerFactory loggerFactory, TConfiguration configuration) { return loggerFactory.CreateLogger( - categoryName: $"Bit.Core.Services.RabbitMqEventListenerService.{configuration.EventQueueName}"); + categoryName: $"Bit.Core.Dirt.Services.Implementations.RabbitMqEventListenerService.{configuration.EventQueueName}"); } } diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqIntegrationListenerService.cs b/src/Core/Dirt/Services/Implementations/RabbitMqIntegrationListenerService.cs similarity index 96% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqIntegrationListenerService.cs rename to src/Core/Dirt/Services/Implementations/RabbitMqIntegrationListenerService.cs index 0762edc040..eced9131bb 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqIntegrationListenerService.cs +++ b/src/Core/Dirt/Services/Implementations/RabbitMqIntegrationListenerService.cs @@ -1,12 +1,12 @@ using System.Text; using System.Text.Json; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class RabbitMqIntegrationListenerService : BackgroundService where TConfiguration : IIntegrationListenerConfiguration @@ -37,7 +37,7 @@ public class RabbitMqIntegrationListenerService : BackgroundServ _timeProvider = timeProvider; _lazyChannel = new Lazy>(() => _rabbitMqService.CreateChannelAsync()); _logger = loggerFactory.CreateLogger( - categoryName: $"Bit.Core.Services.RabbitMqIntegrationListenerService.{configuration.IntegrationQueueName}"); ; + categoryName: $"Bit.Core.Dirt.Services.Implementations.RabbitMqIntegrationListenerService.{configuration.IntegrationQueueName}"); ; } public override async Task StartAsync(CancellationToken cancellationToken) diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqService.cs b/src/Core/Dirt/Services/Implementations/RabbitMqService.cs similarity index 98% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqService.cs rename to src/Core/Dirt/Services/Implementations/RabbitMqService.cs index 8976530cf4..c27fb37d08 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/RabbitMqService.cs +++ b/src/Core/Dirt/Services/Implementations/RabbitMqService.cs @@ -1,11 +1,11 @@ using System.Text; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; -using Bit.Core.Enums; +using Bit.Core.Dirt.Enums; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Bit.Core.Settings; using RabbitMQ.Client; using RabbitMQ.Client.Events; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class RabbitMqService : IRabbitMqService { diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/SlackIntegrationHandler.cs b/src/Core/Dirt/Services/Implementations/SlackIntegrationHandler.cs similarity index 96% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/SlackIntegrationHandler.cs rename to src/Core/Dirt/Services/Implementations/SlackIntegrationHandler.cs index e681140afe..6c6a4dd356 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/SlackIntegrationHandler.cs +++ b/src/Core/Dirt/Services/Implementations/SlackIntegrationHandler.cs @@ -1,6 +1,6 @@ -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class SlackIntegrationHandler( ISlackService slackService) diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/SlackService.cs b/src/Core/Dirt/Services/Implementations/SlackService.cs similarity index 98% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/SlackService.cs rename to src/Core/Dirt/Services/Implementations/SlackService.cs index 7eec2ec374..7683f718b5 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/SlackService.cs +++ b/src/Core/Dirt/Services/Implementations/SlackService.cs @@ -2,11 +2,11 @@ using System.Net.Http.Json; using System.Text.Json; using System.Web; -using Bit.Core.Models.Slack; +using Bit.Core.Dirt.Models.Data.Slack; using Bit.Core.Settings; using Microsoft.Extensions.Logging; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class SlackService( IHttpClientFactory httpClientFactory, diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/TeamsIntegrationHandler.cs b/src/Core/Dirt/Services/Implementations/TeamsIntegrationHandler.cs similarity index 94% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/TeamsIntegrationHandler.cs rename to src/Core/Dirt/Services/Implementations/TeamsIntegrationHandler.cs index 9e3645a99f..7aaed6c647 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/TeamsIntegrationHandler.cs +++ b/src/Core/Dirt/Services/Implementations/TeamsIntegrationHandler.cs @@ -1,8 +1,8 @@ using System.Text.Json; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; using Microsoft.Rest; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class TeamsIntegrationHandler( ITeamsService teamsService) diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/TeamsService.cs b/src/Core/Dirt/Services/Implementations/TeamsService.cs similarity index 96% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/TeamsService.cs rename to src/Core/Dirt/Services/Implementations/TeamsService.cs index f9911760bb..edb43bf85e 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/TeamsService.cs +++ b/src/Core/Dirt/Services/Implementations/TeamsService.cs @@ -2,9 +2,9 @@ using System.Net.Http.Json; using System.Text.Json; using System.Web; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; -using Bit.Core.Models.Teams; -using Bit.Core.Repositories; +using Bit.Core.Dirt.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.Teams; +using Bit.Core.Dirt.Repositories; using Bit.Core.Settings; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Teams; @@ -12,9 +12,9 @@ using Microsoft.Bot.Connector; using Microsoft.Bot.Connector.Authentication; using Microsoft.Bot.Schema; using Microsoft.Extensions.Logging; -using TeamInfo = Bit.Core.Models.Teams.TeamInfo; +using TeamInfo = Bit.Core.Dirt.Models.Data.Teams.TeamInfo; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class TeamsService( IHttpClientFactory httpClientFactory, diff --git a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/WebhookIntegrationHandler.cs b/src/Core/Dirt/Services/Implementations/WebhookIntegrationHandler.cs similarity index 92% rename from src/Core/AdminConsole/Services/Implementations/EventIntegrations/WebhookIntegrationHandler.cs rename to src/Core/Dirt/Services/Implementations/WebhookIntegrationHandler.cs index 0599f6e9d4..6caa1b9a6e 100644 --- a/src/Core/AdminConsole/Services/Implementations/EventIntegrations/WebhookIntegrationHandler.cs +++ b/src/Core/Dirt/Services/Implementations/WebhookIntegrationHandler.cs @@ -1,8 +1,8 @@ using System.Net.Http.Headers; using System.Text; -using Bit.Core.AdminConsole.Models.Data.EventIntegrations; +using Bit.Core.Dirt.Models.Data.EventIntegrations; -namespace Bit.Core.Services; +namespace Bit.Core.Dirt.Services.Implementations; public class WebhookIntegrationHandler( IHttpClientFactory httpClientFactory, diff --git a/src/Core/AdminConsole/Services/NoopImplementations/NoopSlackService.cs b/src/Core/Dirt/Services/NoopImplementations/NoopSlackService.cs similarity index 88% rename from src/Core/AdminConsole/Services/NoopImplementations/NoopSlackService.cs rename to src/Core/Dirt/Services/NoopImplementations/NoopSlackService.cs index a54df94814..30b68186bc 100644 --- a/src/Core/AdminConsole/Services/NoopImplementations/NoopSlackService.cs +++ b/src/Core/Dirt/Services/NoopImplementations/NoopSlackService.cs @@ -1,7 +1,6 @@ -using Bit.Core.Models.Slack; -using Bit.Core.Services; +using Bit.Core.Dirt.Models.Data.Slack; -namespace Bit.Core.AdminConsole.Services.NoopImplementations; +namespace Bit.Core.Dirt.Services.NoopImplementations; public class NoopSlackService : ISlackService { diff --git a/src/Core/AdminConsole/Services/NoopImplementations/NoopTeamsService.cs b/src/Core/Dirt/Services/NoopImplementations/NoopTeamsService.cs similarity index 83% rename from src/Core/AdminConsole/Services/NoopImplementations/NoopTeamsService.cs rename to src/Core/Dirt/Services/NoopImplementations/NoopTeamsService.cs index fafb23f570..3ebd58d996 100644 --- a/src/Core/AdminConsole/Services/NoopImplementations/NoopTeamsService.cs +++ b/src/Core/Dirt/Services/NoopImplementations/NoopTeamsService.cs @@ -1,7 +1,6 @@ -using Bit.Core.Models.Teams; -using Bit.Core.Services; +using Bit.Core.Dirt.Models.Data.Teams; -namespace Bit.Core.AdminConsole.Services.NoopImplementations; +namespace Bit.Core.Dirt.Services.NoopImplementations; public class NoopTeamsService : ITeamsService { diff --git a/src/Core/Entities/PlayItem.cs b/src/Core/Entities/PlayItem.cs new file mode 100644 index 0000000000..cf2f5c946b --- /dev/null +++ b/src/Core/Entities/PlayItem.cs @@ -0,0 +1,60 @@ +using System.ComponentModel.DataAnnotations; +using Bit.Core.AdminConsole.Entities; +using Bit.Core.Utilities; + +namespace Bit.Core.Entities; + +/// +/// PlayItem is a join table tracking entities created during automated testing. +/// A `PlayId` is supplied by the clients in the `x-play-id` header to inform the server +/// that any data created should be associated with the play, and therefore cleaned up with it. +/// +public class PlayItem : ITableObject +{ + public Guid Id { get; set; } + [MaxLength(256)] + public required string PlayId { get; init; } + public Guid? UserId { get; init; } + public Guid? OrganizationId { get; init; } + public DateTime CreationDate { get; init; } + + /// + /// Generates and sets a new COMB GUID for the Id property. + /// + public void SetNewId() + { + Id = CoreHelpers.GenerateComb(); + } + + /// + /// Creates a new PlayItem record associated with a User. + /// + /// The user entity created during the play. + /// The play identifier from the x-play-id header. + /// A new PlayItem instance tracking the user. + public static PlayItem Create(User user, string playId) + { + return new PlayItem + { + PlayId = playId, + UserId = user.Id, + CreationDate = DateTime.UtcNow + }; + } + + /// + /// Creates a new PlayItem record associated with an Organization. + /// + /// The organization entity created during the play. + /// The play identifier from the x-play-id header. + /// A new PlayItem instance tracking the organization. + public static PlayItem Create(Organization organization, string playId) + { + return new PlayItem + { + PlayId = playId, + OrganizationId = organization.Id, + CreationDate = DateTime.UtcNow + }; + } +} diff --git a/src/Core/MailTemplates/Handlebars/Auth/SendAccessEmailOtpEmailv2.html.hbs b/src/Core/MailTemplates/Handlebars/Auth/SendAccessEmailOtpEmailv2.html.hbs index f9cc04f73e..7d30fdcbe4 100644 --- a/src/Core/MailTemplates/Handlebars/Auth/SendAccessEmailOtpEmailv2.html.hbs +++ b/src/Core/MailTemplates/Handlebars/Auth/SendAccessEmailOtpEmailv2.html.hbs @@ -378,12 +378,12 @@ - + -
+
- +
@@ -471,8 +471,8 @@ - -
- + +
@@ -488,13 +488,13 @@
- +
+ - @@ -511,13 +511,13 @@ -
+ - +
- +
+ - @@ -534,13 +534,13 @@ -
+ - +
- +
+ - @@ -557,13 +557,13 @@ -
+ - +
- +
+ - @@ -580,13 +580,13 @@ -
+ - +
- +
+ - @@ -603,13 +603,13 @@ -
+ - +
- +
+ - @@ -626,13 +626,13 @@ -
+ - +
- +
+ - @@ -653,15 +653,15 @@ diff --git a/src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-enterprise-teams.html.hbs b/src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-enterprise-teams.html.hbs deleted file mode 100644 index 65e37e87dd..0000000000 --- a/src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-enterprise-teams.html.hbs +++ /dev/null @@ -1,815 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - -
- -
+ - +
-

+

© 2025 Bitwarden Inc. 1 N. Calle Cesar Chavez, Suite 102, Santa Barbara, CA, USA

Always confirm you are on a trusted Bitwarden domain before logging in:
- bitwarden.com | - Learn why we include this + bitwarden.com | + Learn why we include this

- - - - - -
- - - - - - - - -
- - - - - -
- - - - - - - -
- - -
- - - - - - - - - - - - - - - - - -
- - - - - - - -
- - - -
- -
- -

- You can now share passwords with members of {{OrganizationName}}! -

- -
- - - - - - - -
- - Log in - -
- -
- -
- - - -
- - - - - - - - - -
- - - - - - - -
- - - -
- -
- -
- - -
- -
- - - - - -
- - -
- - - - - - - - - - - -
- - - - - - - -
- - - -
- - - - - - - -
- - -
- - - - - - - - - -
- -
As a member of {{OrganizationName}}:
- -
- -
- - -
- -
- - - - - -
- - - - - - - -
- - -
- - -
- - - - - - - - - -
- - - - - - - -
- - Organization Icon - -
- -
- -
- - - -
- - - - - - - - - -
- -
Your account is owned by {{OrganizationName}} and is subject to their security and management policies.
- -
- -
- - -
- - -
- -
- - - - - -
- - - - - - - -
- - -
- - -
- - - - - - - - - -
- - - - - - - -
- - Group Users Icon - -
- -
- -
- - - -
- - - - - - - - - - - - - -
- -
You can easily access and share passwords with your team.
- -
- - - -
- -
- - -
- - -
- -
- - - - - -
- - - - - - - -
- -
- -
- - - -
- -
- - - - - - - - - -
- - - - - - - -
- - - -
- - - - - - - -
- - -
- - - - - - - - - -
- -

- Learn more about Bitwarden -

- Find user guides, product documentation, and videos on the - Bitwarden Help Center.
- -
- -
- - - -
- - - - - - - - - -
- -
- - -
- -
- - - -
- -
- - - - - - - - - -
- - - - - - - -
- - -
- - - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - -
- -

- © 2025 Bitwarden Inc. 1 N. Calle Cesar Chavez, Suite 102, Santa - Barbara, CA, USA -

-

- Always confirm you are on a trusted Bitwarden domain before logging - in:
- bitwarden.com | - Learn why we include this -

- -
- -
- - -
- -
- - - - - - - - - - \ No newline at end of file diff --git a/src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-family-free.html.hbs b/src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-family-free.html.hbs deleted file mode 100644 index c22bc80a51..0000000000 --- a/src/Core/MailTemplates/Handlebars/MJML/AdminConsole/OrganizationConfirmation/organization-confirmation-family-free.html.hbs +++ /dev/null @@ -1,983 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - -
- - - - - - - -
- - - - - - - - -
- - - - - -
- - - - - - - -
- - -
- - - - - - - - - - - - - - - - - -
- - - - - - - -
- - - -
- -
- -

- You can now share passwords with members of {{OrganizationName}}! -

- -
- - - - - - - -
- - Log in - -
- -
- -
- - - -
- - - - - - - - - -
- - - - - - - -
- - - -
- -
- -
- - -
- -
- - - - - -
- - -
- -
- - - - - - - - - -
- - - - - - - -
- - - -
- - - - - - - -
- - -
- - - - - - - - - -
- -
As a member of {{OrganizationName}}:
- -
- -
- - -
- -
- - - - - -
- - - - - - - -
- - -
- - -
- - - - - - - - - -
- - - - - - - -
- - Collections Icon - -
- -
- -
- - - -
- - - - - - - - - -
- -
You can access passwords {{OrganizationName}} has shared with you.
- -
- -
- - -
- - -
- -
- - - - - -
- - - - - - - -
- - -
- - -
- - - - - - - - - -
- - - - - - - -
- - Group Users Icon - -
- -
- -
- - - -
- - - - - - - - - - - - - -
- -
You can easily share passwords with friends, family, or coworkers.
- -
- - - -
- -
- - -
- - -
- -
- - - - - -
- - - - - - - -
- -
- -
- - - -
- -
- - - - - - - - - -
- - - - - - - -
- - - -
- - - - - - - -
- - -
- - - - - - - - - - - - - -
- -
Download Bitwarden on all devices
- -
- -
Already using the browser extension? - Download the Bitwarden mobile app from the - App Store - or Google Play - to quickly save logins and autofill forms on the go.
- -
- -
- - -
- -
- - - - - -
- - - - - - - -
- - -
- - -
- - - - - - - - - -
- - - - - - - -
- - - - Download on the App Store - - - -
- -
- -
- - - -
- - - - - - - - - -
- - - - - - - -
- - - - Get it on Google Play - - - -
- -
- -
- - -
- - -
- -
- - - -
- -
- - - - - - - - - -
- - - - - - - -
- - - -
- - - - - - - -
- - -
- - - - - - - - - -
- -

- Learn more about Bitwarden -

- Find user guides, product documentation, and videos on the - Bitwarden Help Center.
- -
- -
- - - -
- - - - - - - - - -
- -
- - -
- -
- - - -
- -
- - - - - - - - - -
- - - - - - - -
- - -
- - - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - - - - - - - - -
- - - - - - -
- - - -
-
- - - -
- -

- © 2025 Bitwarden Inc. 1 N. Calle Cesar Chavez, Suite 102, Santa - Barbara, CA, USA -

-

- Always confirm you are on a trusted Bitwarden domain before logging - in:
- bitwarden.com | - Learn why we include this -

- -
- -
- - -
- -
- - - - - -
- - - - \ No newline at end of file diff --git a/src/Core/MailTemplates/Handlebars/MJML/Auth/Onboarding/welcome-family-user.html.hbs b/src/Core/MailTemplates/Handlebars/MJML/Auth/Onboarding/welcome-family-user.html.hbs index 9c4b2406d4..b2b957f849 100644 --- a/src/Core/MailTemplates/Handlebars/MJML/Auth/Onboarding/welcome-family-user.html.hbs +++ b/src/Core/MailTemplates/Handlebars/MJML/Auth/Onboarding/welcome-family-user.html.hbs @@ -30,6 +30,14 @@ + + + + + + + + + + + + + + + + + +