| | | 1 | | using Anichron.API.Security; |
| | | 2 | | using Anichron.API.Services; |
| | | 3 | | using Anichron.API.Settings; |
| | | 4 | | using Anichron.Core.Data; |
| | | 5 | | using Anichron.Core.Data.Repository; |
| | | 6 | | using Anichron.Core.Work; |
| | | 7 | | using Anichron.Infrastructure.Configuration; |
| | | 8 | | using Anichron.Infrastructure.Storage; |
| | | 9 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | | 10 | | using Microsoft.AspNetCore.Authorization; |
| | | 11 | | using Microsoft.AspNetCore.HttpOverrides; |
| | | 12 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 13 | | using Microsoft.Extensions.Options; |
| | | 14 | | using Microsoft.IdentityModel.Tokens; |
| | | 15 | | using Npgsql; |
| | | 16 | | using System.Net; |
| | | 17 | | using System.Text; |
| | | 18 | | |
| | | 19 | | namespace Anichron.API.Infrastructure; |
| | | 20 | | |
| | | 21 | | public static class ServiceCollectionExtensions |
| | | 22 | | { |
| | | 23 | | extension(IServiceCollection services) |
| | | 24 | | { |
| | | 25 | | public IServiceCollection AddApiProblems() |
| | 147 | 26 | | => services.AddProblemDetails().AddExceptionHandler<DatabaseUnavailableHandler>(); |
| | | 27 | | |
| | | 28 | | public IServiceCollection AddDatabase(IConfiguration configuration) |
| | 10 | 29 | | { |
| | 10 | 30 | | return services.AddDatabaseSettings(configuration).AddDbContext<AnichronDbContext>((provider, options) => |
| | 10 | 31 | | options.UseAnichronNpgsql( |
| | 10 | 32 | | new NpgsqlConnectionStringBuilder(provider.GetRequiredService<IOptions<DatabaseConnectionSettings>>( |
| | 10 | 33 | | { |
| | 10 | 34 | | Timeout = AppDefaults.Database.ConnectTimeoutSeconds, |
| | 10 | 35 | | }.ToString())); |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | public IServiceCollection AddForwardedHeadersSupport(IConfiguration configuration) |
| | 13 | 39 | | { |
| | 13 | 40 | | var knownProxies = ConfigurationList.Parse(configuration["ForwardedHeaders:KnownProxies"], IPAddress.Parse); |
| | 13 | 41 | | var knownNetworks = ConfigurationList.Parse(configuration["ForwardedHeaders:KnownNetworks"], System.Net.IPNe |
| | | 42 | | |
| | 12 | 43 | | return services.Configure<ForwardedHeadersOptions>(options => |
| | 12 | 44 | | { |
| | 12 | 45 | | options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; |
| | 12 | 46 | | options.ForwardLimit = 1; |
| | 12 | 47 | | foreach (var proxy in knownProxies) |
| | 12 | 48 | | options.KnownProxies.Add(proxy); |
| | 12 | 49 | | foreach (var network in knownNetworks) |
| | 12 | 50 | | options.KnownIPNetworks.Add(network); |
| | 12 | 51 | | }); |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | public IServiceCollection AddRateLimiting(IConfiguration configuration) |
| | 14 | 55 | | { |
| | 14 | 56 | | services.AddOptions<RateLimitSettings>() |
| | 14 | 57 | | .Bind(configuration.GetSection("RateLimit")) |
| | 14 | 58 | | .ValidateDataAnnotations() |
| | 14 | 59 | | .ValidateOnStart(); |
| | 14 | 60 | | services.AddOptions<RateLimiterOptions>().Configure<IOptions<RateLimitSettings>>((options, settings) => |
| | 14 | 61 | | { |
| | 14 | 62 | | options.AddPolicy(AuthRateLimitPolicies.Sensitive, new SlidingWindowPolicy( |
| | 14 | 63 | | settings.Value.SensitivePermitLimit, |
| | 14 | 64 | | TimeSpan.FromSeconds(AppDefaults.RateLimit.Sensitive.WindowSeconds), |
| | 14 | 65 | | AppDefaults.RateLimit.Sensitive.Segments)); |
| | 14 | 66 | | |
| | 14 | 67 | | options.AddPolicy(AuthRateLimitPolicies.Refresh, new SlidingWindowPolicy( |
| | 14 | 68 | | settings.Value.RefreshPermitLimit, |
| | 14 | 69 | | TimeSpan.FromMinutes(AppDefaults.RateLimit.Refresh.WindowMinutes), |
| | 14 | 70 | | AppDefaults.RateLimit.Refresh.Segments)); |
| | 14 | 71 | | }); |
| | | 72 | | |
| | 14 | 73 | | return services.AddRateLimiter(_ => { }); |
| | | 74 | | } |
| | | 75 | | |
| | | 76 | | public IServiceCollection AddWorkItemServices() |
| | 11 | 77 | | { |
| | 11 | 78 | | services.AddOptions<WorkItemEventsSettings>() |
| | 11 | 79 | | .BindConfiguration("WorkItemEvents") |
| | 11 | 80 | | .ValidateDataAnnotations() |
| | 11 | 81 | | .ValidateOnStart(); |
| | 11 | 82 | | services.AddScoped<IWorkItemReader, EfWorkItemReader>(); |
| | 11 | 83 | | services.AddScoped<IWorkItemCanceller, EfWorkItemCanceller>(); |
| | 11 | 84 | | services.AddScoped<IWorkQueue, EfWorkQueue>(); |
| | 11 | 85 | | services.AddScoped<IProxyOrphanReader, EfProxyOrphanReader>(); |
| | 11 | 86 | | return services; |
| | | 87 | | } |
| | | 88 | | |
| | | 89 | | public IServiceCollection AddCorsPolicy(IConfiguration configuration) |
| | 4 | 90 | | { |
| | 4 | 91 | | var allowedOrigins = CorsOrigins.Read(configuration); |
| | | 92 | | |
| | | 93 | | // Always register CORS services so UseCors() is valid in the middleware pipeline. |
| | 4 | 94 | | services.AddCors(options => CorsOrigins.ConfigureDefaultPolicy(options, allowedOrigins)); |
| | | 95 | | |
| | 4 | 96 | | return services; |
| | | 97 | | } |
| | | 98 | | |
| | | 99 | | public IServiceCollection AddAuthServices(IConfiguration configuration) |
| | 75 | 100 | | { |
| | 75 | 101 | | services.AddOptions<JwtSettings>() |
| | 75 | 102 | | .Bind(configuration.GetSection("Jwt")) |
| | 75 | 103 | | .ValidateOnStart(); |
| | 75 | 104 | | services.AddSingleton<IValidateOptions<JwtSettings>, JwtSettingsValidator>(); |
| | 75 | 105 | | services.AddUserWrites(configuration); |
| | 75 | 106 | | services.AddSingleton<IClock>(SystemClock.Instance); |
| | 75 | 107 | | services.AddSingleton(DateTimeZoneProviders.Tzdb.GetSystemDefault()); |
| | 75 | 108 | | services.AddSingleton<IJwtFactory, JwtFactory>(); |
| | 75 | 109 | | services.AddScoped<IRefreshTokenRepository, EfRefreshTokenRepository>(); |
| | 75 | 110 | | services.AddScoped<IInviteRepository, EfInviteRepository>(); |
| | 75 | 111 | | services.AddScoped<IUserStorageConfigRepository, EfUserStorageConfigRepository>(); |
| | 75 | 112 | | services.AddScoped<IMediaAssetReadRepository, EfMediaAssetReadRepository>(); |
| | 75 | 113 | | services.AddScoped<IAssetViewReader, EfAssetViewReader>(); |
| | 75 | 114 | | services.AddScoped<IAssetInteractionWriter, EfAssetInteractionWriter>(); |
| | 75 | 115 | | services.AddSingleton<IProxyStore, ProxyStore>(); |
| | 75 | 116 | | services.AddSingleton<IOriginalStore, OriginalStore>(); |
| | 75 | 117 | | services.AddScoped<ILockoutService, LockoutService>(); |
| | | 118 | | // Stryker disable once Statement |
| | 75 | 119 | | services.AddSingleton(TimeProvider.System); |
| | 75 | 120 | | services.AddSingleton<ILoginResponseFloor>(sp => new LoginResponseFloor( |
| | 75 | 121 | | sp.GetRequiredService<TimeProvider>(), |
| | 75 | 122 | | TimeSpan.FromMilliseconds(configuration.GetValue( |
| | 75 | 123 | | "Login:FailureFloorMilliseconds", AppDefaults.Login.FailureFloorMilliseconds)))); |
| | 75 | 124 | | services.AddScoped<ITokenService, TokenService>(); |
| | 75 | 125 | | services.AddScoped<IAuthService, AuthService>(); |
| | 75 | 126 | | services.AddScoped<IAdminResetService, AdminResetService>(); |
| | 75 | 127 | | services.AddScoped<IAdminUserService, AdminUserService>(); |
| | 75 | 128 | | services.AddScoped<IAdminStorageConfigService, AdminStorageConfigService>(); |
| | | 129 | | |
| | 75 | 130 | | var sameSite = CorsOrigins.RefreshCookieSameSite(CorsOrigins.Read(configuration)); |
| | 75 | 131 | | services.AddSingleton(provider => |
| | 75 | 132 | | { |
| | 75 | 133 | | var jwt = provider.GetRequiredService<IOptions<JwtSettings>>().Value; |
| | 75 | 134 | | return new AuthCookieSettings |
| | 75 | 135 | | { |
| | 75 | 136 | | SameSite = sameSite, |
| | 75 | 137 | | AccessTokenMinutes = jwt.AccessTokenMinutes, |
| | 75 | 138 | | RefreshTokenDays = jwt.RefreshTokenDays, |
| | 75 | 139 | | }; |
| | 75 | 140 | | }); |
| | | 141 | | |
| | 75 | 142 | | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(); |
| | 75 | 143 | | services.AddJwtValidation(JwtBearerDefaults.AuthenticationScheme); |
| | | 144 | | |
| | 75 | 145 | | return services; |
| | | 146 | | } |
| | | 147 | | |
| | | 148 | | public IServiceCollection AddBootstrapAdmin(IConfiguration configuration) |
| | 1 | 149 | | { |
| | 1 | 150 | | services.AddUserWrites(configuration); |
| | 1 | 151 | | services.AddTransient<IBootstrapSeeder, BootstrapSeeder>(); |
| | 1 | 152 | | services.AddTransient<IBootstrapResetService, BootstrapResetService>(); |
| | 1 | 153 | | return services; |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | private void AddUserWrites(IConfiguration configuration) |
| | 76 | 157 | | { |
| | 76 | 158 | | services.Configure<PasswordPolicy>(configuration.GetSection("PasswordPolicy")); |
| | 76 | 159 | | services.Configure<UsernamePolicy>(configuration.GetSection("UsernamePolicy")); |
| | 76 | 160 | | services.AddSingleton<IGuidFactory, TimeOrderedGuidFactory>(); |
| | 76 | 161 | | services.AddSingleton<IPasswordHasher, Argon2PasswordHasher>(); |
| | 76 | 162 | | services.AddScoped<IUserRepository, EfUserRepository>(); |
| | 76 | 163 | | services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<AnichronDbContext>()); |
| | 76 | 164 | | services.AddScoped<IRegistrationValidator, RegistrationValidator>(); |
| | | 165 | | |
| | 76 | 166 | | services.AddHttpClient<IPwnedPasswordClient, PwnedPasswordClient>(client => |
| | 76 | 167 | | { |
| | 76 | 168 | | client.BaseAddress = new Uri(AppDefaults.Pwned.Url); |
| | 76 | 169 | | client.DefaultRequestHeaders.Add("Add-Padding", "true"); |
| | 76 | 170 | | }).AddStandardResilienceHandler(options => |
| | 76 | 171 | | { |
| | 76 | 172 | | var timeout = TimeSpan.FromSeconds(AppDefaults.Pwned.TimeoutInSeconds); |
| | 76 | 173 | | options.TotalRequestTimeout.Timeout = timeout; |
| | 76 | 174 | | options.AttemptTimeout.Timeout = timeout; |
| | 76 | 175 | | }); |
| | 76 | 176 | | } |
| | | 177 | | |
| | | 178 | | internal IServiceCollection AddJwtValidation(string scheme) |
| | 106 | 179 | | { |
| | 106 | 180 | | services.AddOptions<JwtBearerOptions>(scheme) |
| | 106 | 181 | | .Configure<IOptions<JwtSettings>>((options, jwt) => |
| | 106 | 182 | | options.TokenValidationParameters = new TokenValidationParameters |
| | 106 | 183 | | { |
| | 106 | 184 | | ValidateIssuerSigningKey = true, |
| | 106 | 185 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Value.Secret)), |
| | 106 | 186 | | ValidateIssuer = true, |
| | 106 | 187 | | ValidIssuer = jwt.Value.Issuer, |
| | 106 | 188 | | ValidateAudience = true, |
| | 106 | 189 | | ValidAudience = jwt.Value.Audience, |
| | 106 | 190 | | ValidateLifetime = true, |
| | 106 | 191 | | ClockSkew = TimeSpan.Zero, |
| | 106 | 192 | | }); |
| | 106 | 193 | | return services; |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | public IServiceCollection AddAuthorizationPolicies() |
| | 150 | 197 | | { |
| | 150 | 198 | | var mustChangePassword = new MustChangePasswordRequirement(); |
| | 150 | 199 | | services.AddSingleton<IAuthorizationMiddlewareResultHandler, MustChangePasswordResultHandler>(); |
| | 150 | 200 | | return services.AddAuthorization(options => |
| | 150 | 201 | | { |
| | 150 | 202 | | options.DefaultPolicy = new AuthorizationPolicyBuilder() |
| | 150 | 203 | | .RequireAuthenticatedUser() |
| | 150 | 204 | | .AddRequirements(mustChangePassword) |
| | 150 | 205 | | .Build(); |
| | 150 | 206 | | options.AddPolicy(AuthPolicies.Admin, |
| | 150 | 207 | | policy => policy.RequireClaim(AppClaimTypes.IsAdmin, "true").AddRequirements(mustChangePassword)); |
| | 150 | 208 | | }); |
| | | 209 | | } |
| | | 210 | | |
| | | 211 | | public IServiceCollection AddApiHealthChecks() |
| | 5 | 212 | | { |
| | 5 | 213 | | services.AddHealthChecks() |
| | 5 | 214 | | .AddDbContextCheck<AnichronDbContext>("database") |
| | 5 | 215 | | .AddCheck<ProxyStorageHealthCheck>("proxyStorage") |
| | 5 | 216 | | .AddCheck<OriginalsStorageHealthCheck>("originalsStorage"); |
| | 5 | 217 | | return services; |
| | | 218 | | } |
| | | 219 | | } |
| | | 220 | | } |