mirror of
https://github.com/bitwarden/server
synced 2025-12-25 20:53:16 +00:00
* [AC-1174] Introduce BulkAuthorizationHandler.cs * [AC-1174] Introduce CollectionUserAuthorizationHandler * [AC-1174] Add CreateForNewCollection CollectionUser requirement * [AC-1174] Add some more details to CollectionCustomization * [AC-1174] Formatting * [AC-1174] Add CollectionGroupOperation.cs * [AC-1174] Introduce CollectionGroupAuthorizationHandler.cs * [AC-1174] Cleanup CollectionFixture customization Implement and use re-usable extension method to support seeded Guids * [AC-1174] Introduce WithValueFromList AutoFixtureExtensions Modify CollectionCustomization to use multiple organization Ids for auto generated test data * [AC-1174] Simplify CollectionUserAuthorizationHandler.cs Modify the authorization handler to only perform authorization logic. Validation logic will need to be handled by any calling commands/controllers instead. * [AC-1174] Introduce shared CollectionAccessAuthorizationHandlerBase A shared base authorization handler was created for both CollectionUser and CollectionGroup resources, as they share the same underlying management authorization logic. * [AC-1174] Update CollectionUserAuthorizationHandler and CollectionGroupAuthorizationHandler to use the new CollectionAccessAuthorizationHandlerBase class * [AC-1174] Formatting * [AC-1174] Cleanup typo and redundant ToList() call * [AC-1174] Add check for provider users * [AC-1174] Reduce nested loops * [AC-1174] Introduce ICollectionAccess.cs * [AC-1174] Remove individual CollectionGroup and CollectionUser auth handlers and use base class instead * [AC-1174] Tweak unit test to fail minimally * [AC-1174] Reorganize authorization handlers in Core project * [AC-1174] Introduce new AddCoreAuthorizationHandlers() extension method * [AC-1174] Move CollectionAccessAuthorizationHandler into Api project * [AC-1174] Move CollectionFixture to Vault folder * [AC-1174] Rename operation to CreateUpdateDelete * [AC-1174] Require single organization for collection access authorization handler - Add requirement that all target collections must belong to the same organization - Simplify logic related to multiple organizations - Update tests and helpers - Use ToHashSet to improve lookup time * [AC-1174] Fix null reference exception * [AC-1174] Throw bad request exception when collections belong to different organizations * [AC-1174] Switch to CollectionAuthorizationHandler instead of CollectionAccessAuthorizationHandler to reduce complexity
265 lines
9.0 KiB
C#
265 lines
9.0 KiB
C#
using Bit.Api.Utilities;
|
|
using Bit.Core;
|
|
using Bit.Core.Context;
|
|
using Bit.Core.Settings;
|
|
using AspNetCoreRateLimit;
|
|
using Stripe;
|
|
using Bit.Core.Utilities;
|
|
using IdentityModel;
|
|
using System.Globalization;
|
|
using Bit.Core.IdentityServer;
|
|
using Bit.SharedWeb.Health;
|
|
using Microsoft.IdentityModel.Logging;
|
|
using Microsoft.OpenApi.Models;
|
|
using Bit.SharedWeb.Utilities;
|
|
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using Bit.Core.Auth.Identity;
|
|
using Bit.Core.OrganizationFeatures.OrganizationSubscriptions;
|
|
|
|
#if !OSS
|
|
using Bit.Commercial.Core.SecretsManager;
|
|
using Bit.Commercial.Core.Utilities;
|
|
using Bit.Commercial.Infrastructure.EntityFramework.SecretsManager;
|
|
#endif
|
|
|
|
namespace Bit.Api;
|
|
|
|
public class Startup
|
|
{
|
|
public Startup(IWebHostEnvironment env, IConfiguration configuration)
|
|
{
|
|
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
|
|
Configuration = configuration;
|
|
Environment = env;
|
|
}
|
|
|
|
public IConfiguration Configuration { get; private set; }
|
|
public IWebHostEnvironment Environment { get; set; }
|
|
|
|
public void ConfigureServices(IServiceCollection services)
|
|
{
|
|
// Options
|
|
services.AddOptions();
|
|
|
|
// Settings
|
|
var globalSettings = services.AddGlobalSettingsServices(Configuration, Environment);
|
|
if (!globalSettings.SelfHosted)
|
|
{
|
|
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimitOptions"));
|
|
services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));
|
|
}
|
|
|
|
// Data Protection
|
|
services.AddCustomDataProtectionServices(Environment, globalSettings);
|
|
|
|
// Event Grid
|
|
if (!string.IsNullOrWhiteSpace(globalSettings.EventGridKey))
|
|
{
|
|
ApiHelpers.EventGridKey = globalSettings.EventGridKey;
|
|
}
|
|
|
|
// Stripe Billing
|
|
StripeConfiguration.ApiKey = globalSettings.Stripe.ApiKey;
|
|
StripeConfiguration.MaxNetworkRetries = globalSettings.Stripe.MaxNetworkRetries;
|
|
|
|
// Repositories
|
|
services.AddDatabaseRepositories(globalSettings);
|
|
|
|
// Context
|
|
services.AddScoped<ICurrentContext, CurrentContext>();
|
|
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
|
|
|
// Caching
|
|
services.AddMemoryCache();
|
|
services.AddDistributedCache(globalSettings);
|
|
|
|
// BitPay
|
|
services.AddSingleton<BitPayClient>();
|
|
|
|
if (!globalSettings.SelfHosted)
|
|
{
|
|
services.AddIpRateLimiting(globalSettings);
|
|
}
|
|
|
|
// Identity
|
|
services.AddCustomIdentityServices(globalSettings);
|
|
services.AddIdentityAuthenticationServices(globalSettings, Environment, config =>
|
|
{
|
|
config.AddPolicy("Application", policy =>
|
|
{
|
|
policy.RequireAuthenticatedUser();
|
|
policy.RequireClaim(JwtClaimTypes.AuthenticationMethod, "Application", "external");
|
|
policy.RequireClaim(JwtClaimTypes.Scope, ApiScopes.Api);
|
|
});
|
|
config.AddPolicy("Web", policy =>
|
|
{
|
|
policy.RequireAuthenticatedUser();
|
|
policy.RequireClaim(JwtClaimTypes.AuthenticationMethod, "Application", "external");
|
|
policy.RequireClaim(JwtClaimTypes.Scope, ApiScopes.Api);
|
|
policy.RequireClaim(JwtClaimTypes.ClientId, "web");
|
|
});
|
|
config.AddPolicy("Push", policy =>
|
|
{
|
|
policy.RequireAuthenticatedUser();
|
|
policy.RequireClaim(JwtClaimTypes.Scope, ApiScopes.ApiPush);
|
|
});
|
|
config.AddPolicy("Licensing", policy =>
|
|
{
|
|
policy.RequireAuthenticatedUser();
|
|
policy.RequireClaim(JwtClaimTypes.Scope, ApiScopes.ApiLicensing);
|
|
});
|
|
config.AddPolicy("Organization", policy =>
|
|
{
|
|
policy.RequireAuthenticatedUser();
|
|
policy.RequireClaim(JwtClaimTypes.Scope, ApiScopes.ApiOrganization);
|
|
});
|
|
config.AddPolicy("Installation", policy =>
|
|
{
|
|
policy.RequireAuthenticatedUser();
|
|
policy.RequireClaim(JwtClaimTypes.Scope, ApiScopes.ApiInstallation);
|
|
});
|
|
config.AddPolicy("Secrets", policy =>
|
|
{
|
|
policy.RequireAuthenticatedUser();
|
|
policy.RequireAssertion(ctx => ctx.User.HasClaim(c =>
|
|
c.Type == JwtClaimTypes.Scope &&
|
|
(c.Value.Contains(ApiScopes.Api) || c.Value.Contains(ApiScopes.ApiSecrets))
|
|
));
|
|
});
|
|
});
|
|
|
|
services.AddScoped<AuthenticatorTokenProvider>();
|
|
|
|
// Services
|
|
services.AddBaseServices(globalSettings);
|
|
services.AddDefaultServices(globalSettings);
|
|
services.AddOrganizationSubscriptionServices();
|
|
services.AddCoreLocalizationServices();
|
|
|
|
// Authorization Handlers
|
|
services.AddAuthorizationHandlers();
|
|
|
|
//health check
|
|
if (!globalSettings.SelfHosted)
|
|
{
|
|
services.AddHealthChecks(globalSettings);
|
|
}
|
|
|
|
#if OSS
|
|
services.AddOosServices();
|
|
#else
|
|
services.AddCommercialCoreServices();
|
|
services.AddCommercialSecretsManagerServices();
|
|
services.AddSecretsManagerEfRepositories();
|
|
Jobs.JobsHostedService.AddCommercialSecretsManagerJobServices(services);
|
|
#endif
|
|
|
|
// MVC
|
|
services.AddMvc(config =>
|
|
{
|
|
config.Conventions.Add(new ApiExplorerGroupConvention());
|
|
config.Conventions.Add(new PublicApiControllersModelConvention());
|
|
});
|
|
|
|
services.AddSwagger(globalSettings);
|
|
Jobs.JobsHostedService.AddJobsServices(services, globalSettings.SelfHosted);
|
|
services.AddHostedService<Jobs.JobsHostedService>();
|
|
|
|
if (CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ConnectionString) &&
|
|
CoreHelpers.SettingHasValue(globalSettings.ServiceBus.ApplicationCacheTopicName))
|
|
{
|
|
services.AddHostedService<Core.HostedServices.ApplicationCacheHostedService>();
|
|
}
|
|
}
|
|
|
|
public void Configure(
|
|
IApplicationBuilder app,
|
|
IWebHostEnvironment env,
|
|
IHostApplicationLifetime appLifetime,
|
|
GlobalSettings globalSettings,
|
|
ILogger<Startup> logger)
|
|
{
|
|
IdentityModelEventSource.ShowPII = true;
|
|
app.UseSerilog(env, appLifetime, globalSettings);
|
|
|
|
// Add general security headers
|
|
app.UseMiddleware<SecurityHeadersMiddleware>();
|
|
|
|
// Default Middleware
|
|
app.UseDefaultMiddleware(env, globalSettings);
|
|
|
|
if (!globalSettings.SelfHosted)
|
|
{
|
|
// Rate limiting
|
|
app.UseMiddleware<CustomIpRateLimitMiddleware>();
|
|
}
|
|
else
|
|
{
|
|
app.UseForwardedHeaders(globalSettings);
|
|
}
|
|
|
|
// Add localization
|
|
app.UseCoreLocalization();
|
|
|
|
// Add static files to the request pipeline.
|
|
app.UseStaticFiles();
|
|
|
|
// Add routing
|
|
app.UseRouting();
|
|
|
|
// Add Cors
|
|
app.UseCors(policy => policy.SetIsOriginAllowed(o => CoreHelpers.IsCorsOriginAllowed(o, globalSettings))
|
|
.AllowAnyMethod().AllowAnyHeader().AllowCredentials());
|
|
|
|
// Add authentication and authorization to the request pipeline.
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
|
|
// Add current context
|
|
app.UseMiddleware<CurrentContextMiddleware>();
|
|
|
|
// Add endpoints to the request pipeline.
|
|
app.UseEndpoints(endpoints =>
|
|
{
|
|
endpoints.MapDefaultControllerRoute();
|
|
|
|
if (!globalSettings.SelfHosted)
|
|
{
|
|
endpoints.MapHealthChecks("/healthz");
|
|
|
|
endpoints.MapHealthChecks("/healthz/extended", new HealthCheckOptions
|
|
{
|
|
ResponseWriter = HealthCheckServiceExtensions.WriteResponse
|
|
});
|
|
}
|
|
});
|
|
|
|
// Add Swagger
|
|
if (Environment.IsDevelopment() || globalSettings.SelfHosted)
|
|
{
|
|
app.UseSwagger(config =>
|
|
{
|
|
config.RouteTemplate = "specs/{documentName}/swagger.json";
|
|
config.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
|
|
swaggerDoc.Servers = new List<OpenApiServer>
|
|
{
|
|
new OpenApiServer { Url = globalSettings.BaseServiceUri.Api }
|
|
});
|
|
});
|
|
app.UseSwaggerUI(config =>
|
|
{
|
|
config.DocumentTitle = "Bitwarden API Documentation";
|
|
config.RoutePrefix = "docs";
|
|
config.SwaggerEndpoint($"{globalSettings.BaseServiceUri.Api}/specs/public/swagger.json",
|
|
"Bitwarden Public API");
|
|
config.OAuthClientId("accountType.id");
|
|
config.OAuthClientSecret("secretKey");
|
|
});
|
|
}
|
|
|
|
// Log startup
|
|
logger.LogInformation(Constants.BypassFiltersEventId, globalSettings.ProjectName + " started.");
|
|
}
|
|
}
|