Files
server/src/SharedWeb/Utilities/ServiceCollectionExtensions.cs

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

593 lines
26 KiB
C#
Raw Normal View History

using System;
using System.IO;
using System.Reflection;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Identity;
using Bit.Core.IdentityServer;
using Bit.Core.Models.Business.Tokenables;
using Bit.Core.Repositories;
using Bit.Core.Resources;
using Bit.Core.Services;
using Bit.Core.Settings;
using Bit.Core.Tokens;
using Bit.Core.Utilities;
using Bit.Infrastructure.Dapper;
using Bit.Infrastructure.EntityFramework;
using IdentityModel;
using IdentityServer4.AccessTokenValidation;
using IdentityServer4.Configuration;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
2017-07-21 12:53:26 -04:00
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Serilog.Context;
2019-03-19 00:39:03 -04:00
using NoopRepos = Bit.Core.Repositories.Noop;
2017-12-08 16:03:20 -05:00
using TableStorageRepos = Bit.Core.Repositories.TableStorage;
namespace Bit.SharedWeb.Utilities
{
public static class ServiceCollectionExtensions
{
public static void AddSqlServerRepositories(this IServiceCollection services, GlobalSettings globalSettings)
{
Postgres & MySql Support For Self-Hosted Installations (#1386) * EF Database Support Init (#1221) * scaffolding for ef support * deleted old postgres repos * added tables to oncreate * updated all the things to .NET 5 * Addition to #1221: Migrated DockerFiles from dotnet/3.1 to 5.0 (#1223) * Migrated DockerFiles from dotnet/3.1 to 5.0 * Migrated SSO/Dockerfile from dotnet 3.1 to 5.0 Co-authored-by: Daniel James Smith <djsmith85@users.noreply.github.com> * EFDatabaseSupport: Updated links and description in README.md and SETUP.md (#1232) * Updated requirements in README.md * Updated link to documentation of app-secrets * upgraded dotnet version to 5.0 * Ef database support implementation examples (#1265) * mostly finished testing the user repo * finished testing user repo * finished org, user, ssoconfig, and ssouser ef implementations * removed unused prop * fixed a sql file * fixed a spacing issue * fixed a spacing issue * removed extra database creation * refactoring * MsSql => SqlServer * refactoring * code review fixes * build fix * code review * continued attempts to fix the the build * skipped another test * finished all create test * initial pass at several repos * continued building out repos * initial pass at several repos * initial pass at device repo * initial pass at collection repo * initial run of all Entity Framework implementations * signup, signin, create/edit ciphers works * sync working * all web vault pages seem to load with 100% 200s * bulkcopy, folders, and favorites * group and collection management * sso, groups, emergency access, send * get basic creates matching on all repos * got everything building again post merge * removed some IDE config files * cleanup * no more notimplemented methods in the cipher repo * no more not implementeds everywhere * cleaned up schema/navigation properties and fixed tests * removed a sql comment that was written in c# style * fixed build issues from merge * removed unsupported db providers * formatting * code review refactors * naming cleanup for queries * added provider methods * cipher repo cleanup * implemented several missing procedures from the EF implementation surround account revision dates, keys, and storage * fixed the build * added a null check * consolidated some cipher repo methods * formatting fix * cleaned up indentation of queries * removed .idea file * generated postgres migrations * added mysql migrations * formatting * Bug Fixes & Formatting * Formatting * fixed a bug with bulk import when using MySql * code review fixes * fixed the build * implemented new methods * formatting * fixed the build * cleaned up select statements in ef queries * formatting * formatting * formatting Co-authored-by: Daniel James Smith <djsmith85@users.noreply.github.com>
2021-07-08 12:35:48 -04:00
var selectedDatabaseProvider = globalSettings.DatabaseProvider;
var provider = SupportedDatabaseProviders.SqlServer;
var connectionString = string.Empty;
if (!string.IsNullOrWhiteSpace(selectedDatabaseProvider))
{
switch (selectedDatabaseProvider.ToLowerInvariant())
{
case "postgres":
case "postgresql":
provider = SupportedDatabaseProviders.Postgres;
connectionString = globalSettings.PostgreSql.ConnectionString;
break;
case "mysql":
case "mariadb":
provider = SupportedDatabaseProviders.MySql;
connectionString = globalSettings.MySql.ConnectionString;
break;
default:
break;
}
}
var useEf = (provider != SupportedDatabaseProviders.SqlServer);
2020-01-10 08:33:13 -05:00
if (useEf)
2019-01-15 22:07:13 -05:00
{
services.AddEFRepositories(globalSettings.SelfHosted, connectionString, provider);
2019-01-15 22:07:13 -05:00
}
else
{
services.AddDapperRepositories(globalSettings.SelfHosted);
2019-01-15 22:07:13 -05:00
}
if (globalSettings.SelfHosted)
{
2019-03-19 00:39:03 -04:00
services.AddSingleton<IInstallationDeviceRepository, NoopRepos.InstallationDeviceRepository>();
2019-09-18 09:47:25 -04:00
services.AddSingleton<IMetaDataRepository, NoopRepos.MetaDataRepository>();
}
else
{
services.AddSingleton<IEventRepository, TableStorageRepos.EventRepository>();
2019-03-19 00:39:03 -04:00
services.AddSingleton<IInstallationDeviceRepository, TableStorageRepos.InstallationDeviceRepository>();
2019-09-18 09:47:25 -04:00
services.AddSingleton<IMetaDataRepository, TableStorageRepos.MetaDataRepository>();
}
}
public static void AddBaseServices(this IServiceCollection services)
{
2017-12-01 14:06:16 -05:00
services.AddScoped<ICipherService, CipherService>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IOrganizationService, OrganizationService>();
Families for Enterprise (#1714) * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Fix build error * Update emails * Fix tests * Skip local test * Add newline * Fix stripe subscription update * Finish emails * Skip test * Fix unit tests * Remove unused variable * Fix unit tests * Switch to handlebars ifs * Remove ending email * Remove reconfirmation template * Switch naming convention * Switch naming convention * Fix migration * Update copy and links * Switch to using Guid in the method * Remove unneeded css styles * Add sql files to Sql.sqlproj * Removed old comments * Made name more verbose * Fix SQL error * Move unit tests to service * Fix sp * Revert "Move unit tests to service" This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6. * Do repository validation in service layer * Fix tests * Fix merge conflicts and remove TODO * Remove unneeded models * Fix spacing and formatting * Switch Org -> Organization * Remove single use variables * Switch method name * Fix Controller * Switch to obfuscating email * Fix unit tests Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 16:25:06 -06:00
services.AddScoped<IOrganizationSponsorshipService, OrganizationSponsorshipService>();
services.AddScoped<ICollectionService, CollectionService>();
services.AddScoped<IGroupService, GroupService>();
2020-01-15 15:00:54 -05:00
services.AddScoped<IPolicyService, PolicyService>();
services.AddScoped<IEventService, EventService>();
services.AddScoped<IEmergencyAccessService, EmergencyAccessService>();
2017-12-04 09:32:42 -05:00
services.AddSingleton<IDeviceService, DeviceService>();
2019-09-18 09:46:26 -04:00
services.AddSingleton<IAppleIapService, AppleIapService>();
services.AddScoped<ISsoConfigService, SsoConfigService>();
services.AddScoped<ISendService, SendService>();
}
public static void AddTokenizers(this IServiceCollection services)
{
services.AddSingleton<IDataProtectorTokenFactory<EmergencyAccessInviteTokenable>>(serviceProvider =>
new DataProtectorTokenFactory<EmergencyAccessInviteTokenable>(
EmergencyAccessInviteTokenable.ClearTextPrefix,
EmergencyAccessInviteTokenable.DataProtectorPurpose,
serviceProvider.GetDataProtectionProvider())
);
services.AddSingleton<IDataProtectorTokenFactory<HCaptchaTokenable>>(serviceProvider =>
new DataProtectorTokenFactory<HCaptchaTokenable>(
HCaptchaTokenable.ClearTextPrefix,
HCaptchaTokenable.DataProtectorPurpose,
serviceProvider.GetDataProtectionProvider())
);
}
2017-08-07 16:31:00 -04:00
public static void AddDefaultServices(this IServiceCollection services, GlobalSettings globalSettings)
{
// Required for UserService
services.AddWebAuthn(globalSettings);
services.AddSingleton<IStripeAdapter, StripeAdapter>();
services.AddSingleton<Braintree.IBraintreeGateway>((serviceProvider) =>
{
return new Braintree.BraintreeGateway
{
Environment = globalSettings.Braintree.Production ?
Braintree.Environment.PRODUCTION : Braintree.Environment.SANDBOX,
MerchantId = globalSettings.Braintree.MerchantId,
PublicKey = globalSettings.Braintree.PublicKey,
PrivateKey = globalSettings.Braintree.PrivateKey
};
});
2019-02-08 23:53:09 -05:00
services.AddSingleton<IPaymentService, StripePaymentService>();
2018-08-03 23:04:47 -04:00
services.AddSingleton<IMailService, HandlebarsMailService>();
2017-08-22 15:27:29 -04:00
services.AddSingleton<ILicensingService, LicensingService>();
services.AddTokenizers();
if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) &&
CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName))
{
services.AddSingleton<IApplicationCacheService, InMemoryServiceBusApplicationCacheService>();
}
else
{
services.AddSingleton<IApplicationCacheService, InMemoryApplicationCacheService>();
}
2017-08-07 16:31:00 -04:00
var awsConfigured = CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret);
if (awsConfigured && CoreHelpers.SettingHasValue(globalSettings.Mail?.SendGridApiKey))
{
services.AddSingleton<IMailDeliveryService, MultiServiceMailDeliveryService>();
}
else if (awsConfigured)
2019-03-13 16:19:00 -04:00
{
services.AddSingleton<IMailDeliveryService, AmazonSesMailDeliveryService>();
}
else if (CoreHelpers.SettingHasValue(globalSettings.Mail?.Smtp?.Host))
{
services.AddSingleton<IMailDeliveryService, MailKitSmtpMailDeliveryService>();
}
2017-08-07 16:31:00 -04:00
else
{
services.AddSingleton<IMailDeliveryService, NoopMailDeliveryService>();
}
2018-08-02 17:23:37 -04:00
services.AddSingleton<IPushNotificationService, MultiServicePushNotificationService>();
if (globalSettings.SelfHosted &&
CoreHelpers.SettingHasValue(globalSettings.PushRelayBaseUri) &&
globalSettings.Installation?.Id != null &&
CoreHelpers.SettingHasValue(globalSettings.Installation?.Key))
{
services.AddSingleton<IPushRegistrationService, RelayPushRegistrationService>();
}
else if (!globalSettings.SelfHosted)
{
services.AddSingleton<IPushRegistrationService, NotificationHubPushRegistrationService>();
}
else
{
services.AddSingleton<IPushRegistrationService, NoopPushRegistrationService>();
}
if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString))
2017-08-07 16:31:00 -04:00
{
services.AddSingleton<IBlockIpService, AzureQueueBlockIpService>();
}
else if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Amazon?.AccessKeySecret))
2019-03-18 16:23:37 -04:00
{
services.AddSingleton<IBlockIpService, AmazonSqsBlockIpService>();
}
2017-08-07 16:31:00 -04:00
else
{
services.AddSingleton<IBlockIpService, NoopBlockIpService>();
}
Support large organization sync (#1311) * Increase organization max seat size from 30k to 2b (#1274) * Increase organization max seat size from 30k to 2b * PR review. Do not modify unless state matches expected * Organization sync simultaneous event reporting (#1275) * Split up azure messages according to max size * Allow simultaneous login of organization user events * Early resolve small event lists * Clarify logic Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com> * Improve readability This comes at the cost of multiple serializations, but the improvement in wire-time should more than make up for this on message where serialization time matters Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com> * Queue emails (#1286) * Extract common Azure queue methods * Do not use internal entity framework namespace * Prefer IEnumerable to IList unless needed All of these implementations were just using `Count == 1`, which is easily replicated. This will be used when abstracting Azure queues * Add model for azure queue message * Abstract Azure queue for reuse * Creat service to enqueue mail messages for later processing Azure queue mail service uses Azure queues. Blocking just blocks until all the work is done -- This is how emailing works today * Provide mail queue service to DI * Queue organization invite emails for later processing All emails can later be added to this queue * Create Admin hosted service to process enqueued mail messages * Prefer constructors to static generators * Mass delete organization users (#1287) * Add delete many to Organization Users * Correct formatting * Remove erroneous migration * Clarify parameter name * Formatting fixes * Simplify bump account revision sproc * Formatting fixes * Match file names to objects * Indicate if large import is expected * Early pull all existing users we were planning on inviting (#1290) * Early pull all existing users we were planning on inviting * Improve sproc name * Batch upsert org users (#1289) * Add UpsertMany sprocs to OrganizationUser * Add method to create TVPs from any object. Uses DbOrder attribute to generate. Sproc will fail unless TVP column order matches that of the db type * Combine migrations * Correct formatting * Include sql objects in sql project * Keep consisten parameter names * Batch deletes for performance * Correct formatting * consolidate migrations * Use batch methods in OrganizationImport * Declare @BatchSize * Transaction names limited to 32 chars Drop sproc before creating it if it exists * Update import tests * Allow for more users in org upgrades * Fix formatting * Improve class hierarchy structure * Use name tuple types * Fix formatting * Front load all reflection * Format constructor * Simplify ToTvp as class-specific extension Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com>
2021-05-17 09:43:02 -05:00
if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Mail.ConnectionString))
{
services.AddSingleton<IMailEnqueuingService, AzureQueueMailService>();
}
else
{
services.AddSingleton<IMailEnqueuingService, BlockingMailEnqueuingService>();
}
if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Events.ConnectionString))
2017-12-08 16:03:20 -05:00
{
services.AddSingleton<IEventWriteService, AzureQueueEventWriteService>();
}
else if (globalSettings.SelfHosted)
2017-12-08 16:03:20 -05:00
{
services.AddSingleton<IEventWriteService, RepositoryEventWriteService>();
}
else
{
services.AddSingleton<IEventWriteService, NoopEventWriteService>();
}
2017-12-04 12:17:26 -05:00
if (CoreHelpers.SettingHasValue(globalSettings.Attachment.ConnectionString))
2017-08-07 16:31:00 -04:00
{
services.AddSingleton<IAttachmentStorageService, AzureAttachmentStorageService>();
}
else if (CoreHelpers.SettingHasValue(globalSettings.Attachment.BaseDirectory))
{
services.AddSingleton<IAttachmentStorageService, LocalAttachmentStorageService>();
}
2017-08-07 16:31:00 -04:00
else
{
services.AddSingleton<IAttachmentStorageService, NoopAttachmentStorageService>();
}
if (CoreHelpers.SettingHasValue(globalSettings.Send.ConnectionString))
{
services.AddSingleton<ISendFileStorageService, AzureSendFileStorageService>();
}
else if (CoreHelpers.SettingHasValue(globalSettings.Send.BaseDirectory))
{
services.AddSingleton<ISendFileStorageService, LocalSendStorageService>();
}
else
{
services.AddSingleton<ISendFileStorageService, NoopSendFileStorageService>();
}
if (globalSettings.SelfHosted)
{
services.AddSingleton<IReferenceEventService, NoopReferenceEventService>();
}
else
{
services.AddSingleton<IReferenceEventService, AzureQueueReferenceEventService>();
}
if (CoreHelpers.SettingHasValue(globalSettings.Captcha?.HCaptchaSecretKey) &&
CoreHelpers.SettingHasValue(globalSettings.Captcha?.HCaptchaSiteKey))
{
services.AddSingleton<ICaptchaValidationService, HCaptchaValidationService>();
}
else
{
services.AddSingleton<ICaptchaValidationService, NoopCaptchaValidationService>();
}
}
2021-06-30 09:35:26 +02:00
public static void AddOosServices(this IServiceCollection services)
{
services.AddScoped<IProviderService, NoopProviderService>();
}
public static void AddNoopServices(this IServiceCollection services)
{
services.AddSingleton<IMailService, NoopMailService>();
services.AddSingleton<IMailDeliveryService, NoopMailDeliveryService>();
2017-05-26 09:44:54 -04:00
services.AddSingleton<IPushNotificationService, NoopPushNotificationService>();
services.AddSingleton<IBlockIpService, NoopBlockIpService>();
services.AddSingleton<IPushRegistrationService, NoopPushRegistrationService>();
services.AddSingleton<IAttachmentStorageService, NoopAttachmentStorageService>();
2017-08-11 22:55:25 -04:00
services.AddSingleton<ILicensingService, NoopLicensingService>();
2017-12-04 12:17:26 -05:00
services.AddSingleton<IEventWriteService, NoopEventWriteService>();
}
public static IdentityBuilder AddCustomIdentityServices(
this IServiceCollection services, GlobalSettings globalSettings)
{
2018-04-03 14:31:33 -04:00
services.AddSingleton<IOrganizationDuoWebTokenProvider, OrganizationDuoWebTokenProvider>();
services.Configure<PasswordHasherOptions>(options => options.IterationCount = 100000);
2017-06-23 10:08:29 -04:00
services.Configure<TwoFactorRememberTokenProviderOptions>(options =>
{
options.TokenLifespan = TimeSpan.FromDays(30);
});
var identityBuilder = services.AddIdentityWithoutCookieAuth<User, Role>(options =>
{
options.User = new UserOptions
{
RequireUniqueEmail = true,
AllowedUserNameCharacters = null // all
};
options.Password = new PasswordOptions
{
RequireDigit = false,
RequireLowercase = false,
RequiredLength = 8,
RequireNonAlphanumeric = false,
RequireUppercase = false
};
options.ClaimsIdentity = new ClaimsIdentityOptions
{
SecurityStampClaimType = "sstamp",
UserNameClaimType = JwtClaimTypes.Email,
UserIdClaimType = JwtClaimTypes.Subject
};
options.Tokens.ChangeEmailTokenProvider = TokenOptions.DefaultEmailProvider;
});
identityBuilder
.AddUserStore<UserStore>()
.AddRoleStore<RoleStore>()
.AddTokenProvider<DataProtectorTokenProvider<User>>(TokenOptions.DefaultProvider)
2018-12-19 22:27:45 -05:00
.AddTokenProvider<AuthenticatorTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.Authenticator))
.AddTokenProvider<EmailTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.Email))
.AddTokenProvider<YubicoOtpTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.YubiKey))
.AddTokenProvider<DuoWebTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.Duo))
.AddTokenProvider<TwoFactorRememberTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.Remember))
2021-03-22 23:21:43 +01:00
.AddTokenProvider<EmailTokenProvider<User>>(TokenOptions.DefaultEmailProvider)
.AddTokenProvider<WebAuthnTokenProvider>(
CoreHelpers.CustomProviderName(TwoFactorProviderType.WebAuthn));
return identityBuilder;
}
public static Tuple<IdentityBuilder, IdentityBuilder> AddPasswordlessIdentityServices<TUserStore>(
this IServiceCollection services, GlobalSettings globalSettings) where TUserStore : class
2018-08-28 17:40:08 -04:00
{
services.TryAddTransient<ILookupNormalizer, LowerInvariantLookupNormalizer>();
2018-03-21 14:26:49 -04:00
services.Configure<DataProtectionTokenProviderOptions>(options =>
{
options.TokenLifespan = TimeSpan.FromMinutes(15);
});
var passwordlessIdentityBuilder = services.AddIdentity<IdentityUser, Role>()
2018-03-21 14:26:49 -04:00
.AddUserStore<TUserStore>()
.AddRoleStore<RoleStore>()
.AddDefaultTokenProviders();
var regularIdentityBuilder = services.AddIdentityCore<User>()
.AddUserStore<UserStore>();
2018-03-21 14:26:49 -04:00
services.TryAddScoped<PasswordlessSignInManager<IdentityUser>, PasswordlessSignInManager<IdentityUser>>();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/";
2018-03-28 10:38:01 -04:00
options.AccessDeniedPath = "/login?accessDenied=true";
2018-03-21 14:26:49 -04:00
options.Cookie.Name = $"Bitwarden_{globalSettings.ProjectName}";
options.Cookie.HttpOnly = true;
2020-01-13 12:03:10 -05:00
options.ExpireTimeSpan = TimeSpan.FromDays(2);
2018-03-21 14:26:49 -04:00
options.ReturnUrlParameter = "returnUrl";
options.SlidingExpiration = true;
});
return new Tuple<IdentityBuilder, IdentityBuilder>(passwordlessIdentityBuilder, regularIdentityBuilder);
2018-03-21 14:26:49 -04:00
}
public static void AddIdentityAuthenticationServices(
2020-01-10 08:33:13 -05:00
this IServiceCollection services, GlobalSettings globalSettings, IWebHostEnvironment environment,
2018-08-15 18:43:26 -04:00
Action<AuthorizationOptions> addAuthorization)
{
services
.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = globalSettings.BaseServiceUri.InternalIdentity;
options.RequireHttpsMetadata = !environment.IsDevelopment() &&
globalSettings.BaseServiceUri.InternalIdentity.StartsWith("https");
options.TokenRetriever = TokenRetrieval.FromAuthorizationHeaderOrQueryString();
options.NameClaimType = ClaimTypes.Email;
options.SupportedTokens = SupportedTokens.Jwt;
});
if (addAuthorization != null)
{
2018-08-15 18:43:26 -04:00
services.AddAuthorization(config =>
{
2018-08-15 18:43:26 -04:00
addAuthorization.Invoke(config);
});
}
2019-02-26 17:01:06 -05:00
if (environment.IsDevelopment())
2019-02-26 17:01:06 -05:00
{
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
}
}
public static void AddCustomDataProtectionServices(
2020-01-10 08:33:13 -05:00
this IServiceCollection services, IWebHostEnvironment env, GlobalSettings globalSettings)
{
var builder = services.AddDataProtection(options => options.ApplicationDiscriminator = "Bitwarden");
if (env.IsDevelopment())
{
return;
}
if (globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.DataProtection.Directory))
{
builder.PersistKeysToFileSystem(new DirectoryInfo(globalSettings.DataProtection.Directory));
}
if (!globalSettings.SelfHosted && CoreHelpers.SettingHasValue(globalSettings.Storage?.ConnectionString))
{
X509Certificate2 dataProtectionCert = null;
if (CoreHelpers.SettingHasValue(globalSettings.DataProtection.CertificateThumbprint))
{
dataProtectionCert = CoreHelpers.GetCertificate(
globalSettings.DataProtection.CertificateThumbprint);
}
else if (CoreHelpers.SettingHasValue(globalSettings.DataProtection.CertificatePassword))
{
dataProtectionCert = CoreHelpers.GetBlobCertificateAsync(globalSettings.Storage.ConnectionString, "certificates",
"dataprotection.pfx", globalSettings.DataProtection.CertificatePassword)
.GetAwaiter().GetResult();
}
//TODO djsmith85 Check if this is the correct container name
builder
.PersistKeysToAzureBlobStorage(globalSettings.Storage.ConnectionString, "aspnet-dataprotection", "keys.xml")
.ProtectKeysWithCertificate(dataProtectionCert);
}
}
public static IIdentityServerBuilder AddIdentityServerCertificate(
this IIdentityServerBuilder identityServerBuilder, IWebHostEnvironment env, GlobalSettings globalSettings)
{
var certificate = CoreHelpers.GetIdentityServerCertificate(globalSettings);
if (certificate != null)
{
identityServerBuilder.AddSigningCredential(certificate);
2019-07-10 20:05:07 -04:00
}
else if (env.IsDevelopment())
{
identityServerBuilder.AddDeveloperSigningCredential(false);
}
2017-08-07 16:31:00 -04:00
else
{
throw new Exception("No identity certificate to use.");
}
return identityServerBuilder;
}
public static GlobalSettings AddGlobalSettingsServices(this IServiceCollection services,
IConfiguration configuration)
{
var globalSettings = new GlobalSettings();
ConfigurationBinder.Bind(configuration.GetSection("GlobalSettings"), globalSettings);
services.AddSingleton(s => globalSettings);
services.AddSingleton<IGlobalSettings, GlobalSettings>(s => globalSettings);
return globalSettings;
}
2017-07-21 12:53:26 -04:00
2019-09-03 14:44:22 -04:00
public static void UseDefaultMiddleware(this IApplicationBuilder app,
2020-01-10 08:33:13 -05:00
IWebHostEnvironment env, GlobalSettings globalSettings)
2017-07-21 12:53:26 -04:00
{
2019-09-03 14:44:22 -04:00
string GetHeaderValue(HttpContext httpContext, string header)
{
if (httpContext.Request.Headers.ContainsKey(header))
2019-09-03 14:44:22 -04:00
{
return httpContext.Request.Headers[header];
}
return null;
}
2017-08-25 08:57:43 -04:00
// Add version information to response headers
app.Use(async (httpContext, next) =>
{
using (LogContext.PushProperty("IPAddress", httpContext.GetIpAddress(globalSettings)))
using (LogContext.PushProperty("UserAgent", GetHeaderValue(httpContext, "user-agent")))
using (LogContext.PushProperty("DeviceType", GetHeaderValue(httpContext, "device-type")))
using (LogContext.PushProperty("Origin", GetHeaderValue(httpContext, "origin")))
2017-08-25 08:57:43 -04:00
{
2019-09-03 14:44:22 -04:00
httpContext.Response.OnStarting((state) =>
{
httpContext.Response.Headers.Append("Server-Version", CoreHelpers.GetVersion());
return Task.FromResult(0);
}, null);
await next.Invoke();
}
2017-08-25 08:57:43 -04:00
});
2017-07-21 12:53:26 -04:00
}
2019-04-26 09:52:54 -04:00
public static void UseForwardedHeaders(this IApplicationBuilder app, GlobalSettings globalSettings)
{
var options = new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
if (!string.IsNullOrWhiteSpace(globalSettings.KnownProxies))
2019-04-26 09:52:54 -04:00
{
var proxies = globalSettings.KnownProxies.Split(',');
foreach (var proxy in proxies)
2019-04-26 09:52:54 -04:00
{
if (System.Net.IPAddress.TryParse(proxy.Trim(), out var ip))
2019-04-26 09:52:54 -04:00
{
options.KnownProxies.Add(ip);
}
}
}
if (options.KnownProxies.Count > 1)
2019-04-26 09:52:54 -04:00
{
options.ForwardLimit = null;
}
app.UseForwardedHeaders(options);
}
public static void AddCoreLocalizationServices(this IServiceCollection services)
{
services.AddTransient<II18nService, I18nService>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
}
public static IApplicationBuilder UseCoreLocalization(this IApplicationBuilder app)
{
var supportedCultures = new[] { "en" };
return app.UseRequestLocalization(options => options
.SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures));
}
public static IMvcBuilder AddViewAndDataAnnotationLocalization(this IMvcBuilder mvc)
{
mvc.Services.AddTransient<IViewLocalizer, I18nViewLocalizer>();
return mvc.AddViewLocalization(options => options.ResourcesPath = "Resources")
.AddDataAnnotationsLocalization(options =>
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
var assemblyName = new AssemblyName(typeof(SharedResources).GetTypeInfo().Assembly.FullName);
return factory.Create("SharedResources", assemblyName.Name);
});
}
public static IServiceCollection AddDistributedIdentityServices(this IServiceCollection services, GlobalSettings globalSettings)
{
if (string.IsNullOrWhiteSpace(globalSettings.IdentityServer?.RedisConnectionString))
{
services.AddDistributedMemoryCache();
}
else
{
services.AddDistributedRedisCache(options =>
options.Configuration = globalSettings.IdentityServer.RedisConnectionString);
}
services.AddOidcStateDataFormatterCache();
services.AddSession();
services.ConfigureApplicationCookie(configure => configure.CookieManager = new DistributedCacheCookieManager());
services.ConfigureExternalCookie(configure => configure.CookieManager = new DistributedCacheCookieManager());
services.AddSingleton<IPostConfigureOptions<CookieAuthenticationOptions>>(
svcs => new ConfigureOpenIdConnectDistributedOptions(
svcs.GetRequiredService<IHttpContextAccessor>(),
globalSettings,
svcs.GetRequiredService<IdentityServerOptions>())
);
return services;
}
public static void AddWebAuthn(this IServiceCollection services, GlobalSettings globalSettings)
{
services.AddFido2(options =>
{
options.ServerDomain = new Uri(globalSettings.BaseServiceUri.Vault).Host;
options.ServerName = "Bitwarden";
options.Origin = globalSettings.BaseServiceUri.Vault;
options.TimestampDriftTolerance = 300000;
});
}
}
}