1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-25 12:45:18 +01:00
bitwarden-server/test/IntegrationTestCommon/Factories/IdentityApplicationFactory.cs

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

159 lines
6.3 KiB
C#
Raw Normal View History

using System.Net.Http.Json;
using System.Text.Json;
[PM-1188] Server owner auth migration (#2825) * [PM-1188] add sso project to auth * [PM-1188] move sso api models to auth * [PM-1188] fix sso api model namespace & imports * [PM-1188] move core files to auth * [PM-1188] fix core sso namespace & models * [PM-1188] move sso repository files to auth * [PM-1188] fix sso repo files namespace & imports * [PM-1188] move sso sql files to auth folder * [PM-1188] move sso test files to auth folders * [PM-1188] fix sso tests namespace & imports * [PM-1188] move auth api files to auth folder * [PM-1188] fix auth api files namespace & imports * [PM-1188] move auth core files to auth folder * [PM-1188] fix auth core files namespace & imports * [PM-1188] move auth email templates to auth folder * [PM-1188] move auth email folder back into shared directory * [PM-1188] fix auth email names * [PM-1188] move auth core models to auth folder * [PM-1188] fix auth model namespace & imports * [PM-1188] add entire Identity project to auth codeowners * [PM-1188] fix auth orm files namespace & imports * [PM-1188] move auth orm files to auth folder * [PM-1188] move auth sql files to auth folder * [PM-1188] move auth tests to auth folder * [PM-1188] fix auth test files namespace & imports * [PM-1188] move emergency access api files to auth folder * [PM-1188] fix emergencyaccess api files namespace & imports * [PM-1188] move emergency access core files to auth folder * [PM-1188] fix emergency access core files namespace & imports * [PM-1188] move emergency access orm files to auth folder * [PM-1188] fix emergency access orm files namespace & imports * [PM-1188] move emergency access sql files to auth folder * [PM-1188] move emergencyaccess test files to auth folder * [PM-1188] fix emergency access test files namespace & imports * [PM-1188] move captcha files to auth folder * [PM-1188] fix captcha files namespace & imports * [PM-1188] move auth admin files into auth folder * [PM-1188] fix admin auth files namespace & imports - configure mvc to look in auth folders for views * [PM-1188] remove extra imports and formatting * [PM-1188] fix ef auth model imports * [PM-1188] fix DatabaseContextModelSnapshot paths * [PM-1188] fix grant import in ef * [PM-1188] update sqlproj * [PM-1188] move missed sqlproj files * [PM-1188] move auth ef models out of auth folder * [PM-1188] fix auth ef models namespace * [PM-1188] remove auth ef models unused imports * [PM-1188] fix imports for auth ef models * [PM-1188] fix more ef model imports * [PM-1188] fix file encodings
2023-04-14 19:25:56 +02:00
using Bit.Core.Auth.Models.Api.Request.Accounts;
using Bit.Core.Enums;
using Bit.Core.Utilities;
using Bit.Identity;
using Bit.Identity.Models.Request.Accounts;
using Bit.Test.Common.Helpers;
using HandlebarsDotNet;
using Microsoft.AspNetCore.Http;
namespace Bit.IntegrationTestCommon.Factories;
2022-08-29 22:06:55 +02:00
public class IdentityApplicationFactory : WebApplicationFactoryBase<Startup>
{
public const string DefaultDeviceIdentifier = "92b9d953-b9b6-4eaf-9d3e-11d57144dfeb";
public async Task<HttpContext> RegisterAsync(RegisterRequestModel model)
{
return await Server.PostAsync("/accounts/register", JsonContent.Create(model));
}
Auth/PM-5092 - Registration with Email verification - Send Email Verification Endpoint (#4173) * PM-5092 - Add new EnableEmailVerification global setting. * PM-5092 - WIP - AccountsController.cs - create stub for new PostRegisterSendEmailVerification * PM-5092 - RegisterSendEmailVerificationRequestModel * PM-5092 - Create EmailVerificationTokenable.cs and get started on tests (still WIP). * PM-5092 - EmailVerificationTokenable.cs finished + tests working. * PM-5092 - Add token data factory for new EmailVerificationTokenable factory. * PM-5092 - EmailVerificationTokenable.cs - set expiration to match existing verify email. * PM-5092 - Get SendVerificationEmailForRegistrationCommand command mostly written + register as scoped. * PM-5092 - Rename tokenable to be more clear and differentiate it from the existing email verification token. * PM-5092 - Add new registration verify email method on mail service. * PM-5092 - Refactor SendVerificationEmailForRegistrationCommand and add call to mail service to send email. * PM-5092 - NoopMailService.cs needs to implement all interface methods. * PM-5092 - AccountsController.cs - get PostRegisterSendEmailVerification logic in place. * PM-5092 - AccountsControllerTests.cs - Add some unit tests - WIP * PM-5092 - SendVerificationEmailForRegistrationCommandTests * PM-5092 - Add integration tests for new acct controller method * PM-5092 - Cleanup unit tests * PM-5092 - AccountsController.cs - PostRegisterSendEmailVerification - remove modelState invalid check as .NET literally executes this validation pre-method execution. * PM-5092 - Rename to read better - send verification email > send email verification * PM-5092 - Revert primary constructor approach so DI works. * PM-5092 - (1) Cleanup new but now not needed global setting (2) Add custom email for registration verify email. * PM-5092 - Fix email text * PM-5092 - (1) Modify ReferenceEvent.cs to allow nullable values for the 2 params which should have been nullable based on the constructor logic (2) Add new ReferenceEventType.cs for email verification register submit (3) Update AccountsController.cs to log new reference event (4) Update tests * PM-5092 - RegistrationEmailVerificationTokenable - update prefix, purpose, and token id to include registration to differentiate it from the existing email verification token. * PM-5092 - Per PR feedback, cleanup used dict. * PM-5092 - formatting pass (manual + dotnet format) * PM-5092 - Per PR feedback, log reference event after core business logic executes * PM-5092 - Per PR feedback, add validation + added nullable flag to name as it is optional. * PM-5092 - Per PR feedback, add constructor validation for required tokenable data * PM-5092 - RegisterVerifyEmail url now contains email as that is required in client side registration step to create a master key. * PM-5092 - Add fromEmail flag + some docs * PM-5092 - ReferenceEvent.cs - Per PR feedback, make SignupInitiationPath and PlanUpgradePath nullable * PM-5092 - ReferenceEvent.cs - remove nullability per PR feedback * PM-5092 - Per PR feedback, use default constructor and manually create reference event. * PM-5092 - Per PR feedback, add more docs!
2024-06-19 19:54:20 +02:00
public async Task<HttpContext> PostRegisterSendEmailVerificationAsync(RegisterSendVerificationEmailRequestModel model)
{
return await Server.PostAsync("/accounts/register/send-verification-email", JsonContent.Create(model));
}
Auth/PM-7322 - Registration with Email verification - Finish registration endpoint (#4182) * PM-7322 - AccountsController.cs - create empty method + empty req model to be able to create draft PR. * PM-7322 - Start on RegisterFinishRequestModel.cs * PM-7322 - WIP on Complete Registration endpoint * PM-7322 - UserService.cs - RegisterUserAsync - Tweak of token to be orgInviteToken as we are adding a new email verification token to the mix. * PM-7322 - UserService - Rename MP to MPHash * PM-7322 - More WIP progress on getting new finish registration process in place. * PM-7322 Create IRegisterUserCommand * PM-7322 - RegisterUserCommand.cs - first WIP draft * PM-7322 - Implement use of new command in Identity. * PM-7322 - Rename RegisterUserViaOrgInvite to just be RegisterUser as orgInvite is optional. * PM07322 - Test RegisterUserCommand.RegisterUser(...) happy paths and one bad request path. * PM-7322 - More WIP on RegisterUserCommand.cs and tests * PM-7322 - RegisterUserCommand.cs - refactor ValidateOrgInviteToken logic to always validate the token if we have one. * PM-7322 - RegisterUserCommand.cs - Refactor OrgInviteToken validation to be more clear + validate org invite token even in open registration scenarios + added tests. * PM-7322 - Add more test coverage to RegisterUserWithOptionalOrgInvite * PM-7322 - IRegisterUserCommand - DOCS * PM-7322 - Test RegisterUser * PM-7322 - IRegisterUserCommand - Add more docs. * PM-7322 - Finish updating all existing user service register calls to use the new command. * PM-7322 - RegistrationEmailVerificationTokenable.cs changes + tests * PM-7322 - RegistrationEmailVerificationTokenable.cs changed to only verify email as it's the only thing we need to verify + updated tests. * PM-7322 - Get RegisterUserViaEmailVerificationToken built and tested * PM-7322 - AccountsController.cs - get bones of PostRegisterFinish in place * PM-7322 - SendVerificationEmailForRegistrationCommand - Feature flag timing attack delays per architecture discussion with a default of keeping them around. * PM-7322 - RegisterFinishRequestModel.cs - EmailVerificationToken must be optional for org invite scenarios. * PM-7322 - HandlebarsMailService.cs - SendRegistrationVerificationEmailAsync - must URL encode email to avoid invalid email upon submission to server on complete registration step * PM-7322 - RegisterUserCommandTests.cs - add API key assertions * PM-7322 - Clean up RegisterUserCommand.cs * PM-7322 - Refactor AccountsController.cs existing org invite method and new process to consider new feature flag for delays. * PM-7322 - Add feature flag svc to AccountsControllerTests.cs + add TODO * PM-7322 - AccountsController.cs - Refactor shared IdentityResult logic into private helper. * PM-7322 - Work on getting PostRegisterFinish tests in place. * PM-7322 - AccountsControllerTests.cs - test new method. * PM-7322 - RegisterFinishRequestModel.cs - Update to use required keyword instead of required annotations as it is easier to catch mistakes. * PM-7322 - Fix misspelling * PM-7322 - Integration tests for RegistrationWithEmailVerification * PM-7322 - Fix leaky integration tests. * PM-7322 - Another leaky test fix. * PM-7322 - AccountsControllerTests.cs - fix RegistrationWithEmailVerification_WithOrgInviteToken_Succeeds * PM-7322 - AccountsControllerTests.cs - Finish out integration test suite!
2024-07-02 23:03:36 +02:00
public async Task<HttpContext> PostRegisterFinishAsync(RegisterFinishRequestModel model)
{
return await Server.PostAsync("/accounts/register/finish", JsonContent.Create(model));
}
public async Task<HttpContext> PostRegisterVerificationEmailClicked(RegisterVerificationEmailClickedRequestModel model)
{
return await Server.PostAsync("/accounts/register/verification-email-clicked", JsonContent.Create(model));
}
public async Task<(string Token, string RefreshToken)> TokenFromPasswordAsync(
string username,
string password,
string deviceIdentifier = DefaultDeviceIdentifier,
string clientId = "web",
DeviceType deviceType = DeviceType.FirefoxBrowser,
string deviceName = "firefox")
{
var context = await ContextFromPasswordAsync(
username, password, deviceIdentifier, clientId, deviceType, deviceName);
using var body = await AssertHelper.AssertResponseTypeIs<JsonDocument>(context);
var root = body.RootElement;
return (root.GetProperty("access_token").GetString(), root.GetProperty("refresh_token").GetString());
}
public async Task<HttpContext> ContextFromPasswordAsync(
string username,
string password,
string deviceIdentifier = DefaultDeviceIdentifier,
string clientId = "web",
DeviceType deviceType = DeviceType.FirefoxBrowser,
string deviceName = "firefox")
2022-08-29 22:06:55 +02:00
{
var context = await Server.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "scope", "api offline_access" },
{ "client_id", clientId },
{ "deviceType", ((int)deviceType).ToString() },
{ "deviceIdentifier", deviceIdentifier },
{ "deviceName", deviceName },
{ "grant_type", "password" },
{ "username", username },
{ "password", password },
}), context => context.Request.Headers.Append("Auth-Email", CoreHelpers.Base64UrlEncodeString(username)));
return context;
}
public async Task<HttpContext> ContextFromPasswordWithTwoFactorAsync(
string username,
string password,
string deviceIdentifier = DefaultDeviceIdentifier,
string clientId = "web",
DeviceType deviceType = DeviceType.FirefoxBrowser,
string deviceName = "firefox",
string twoFactorProviderType = "Email",
string twoFactorToken = "two-factor-token")
{
var context = await Server.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "scope", "api offline_access" },
{ "client_id", clientId },
{ "deviceType", ((int)deviceType).ToString() },
{ "deviceIdentifier", deviceIdentifier },
{ "deviceName", deviceName },
{ "grant_type", "password" },
{ "username", username },
{ "password", password },
{ "TwoFactorToken", twoFactorToken },
{ "TwoFactorProvider", twoFactorProviderType },
{ "TwoFactorRemember", "1" },
}), context => context.Request.Headers.Append("Auth-Email", CoreHelpers.Base64UrlEncodeString(username)));
return context;
}
public async Task<string> TokenFromAccessTokenAsync(Guid clientId, string clientSecret,
DeviceType deviceType = DeviceType.SDK)
{
var context = await ContextFromAccessTokenAsync(clientId, clientSecret, deviceType);
using var body = await AssertHelper.AssertResponseTypeIs<JsonDocument>(context);
var root = body.RootElement;
return root.GetProperty("access_token").GetString();
}
public async Task<HttpContext> ContextFromAccessTokenAsync(Guid clientId, string clientSecret,
DeviceType deviceType = DeviceType.SDK)
{
var context = await Server.PostAsync("/connect/token",
new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "scope", "api.secrets" },
{ "client_id", clientId.ToString() },
{ "client_secret", clientSecret },
{ "grant_type", "client_credentials" },
{ "deviceType", ((int)deviceType).ToString() }
}));
return context;
}
public async Task<string> TokenFromOrganizationApiKeyAsync(string clientId, string clientSecret,
DeviceType deviceType = DeviceType.FirefoxBrowser)
{
var context = await ContextFromOrganizationApiKeyAsync(clientId, clientSecret, deviceType);
using var body = await AssertHelper.AssertResponseTypeIs<JsonDocument>(context);
var root = body.RootElement;
return root.GetProperty("access_token").GetString();
}
public async Task<HttpContext> ContextFromOrganizationApiKeyAsync(string clientId, string clientSecret,
DeviceType deviceType = DeviceType.FirefoxBrowser)
{
var context = await Server.PostAsync("/connect/token",
new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "scope", "api.organization" },
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "grant_type", "client_credentials" },
{ "deviceType", ((int)deviceType).ToString() }
}));
return context;
}
}