divan/RMuseum/Startup.cs
Anas Rashid 987f69704b Security pass (#11): no default JWT secret, CORS allow-list, Diwan system emails
- appsettings: drop upstream's public JWT secret; API refuses to start outside Development without one
- Cors:AllowedOrigins (compose: https://SITE_DOMAIN); unset = any origin for local dev
- default admin/system/bot emails @diwan.local instead of @ganjoor.net

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:26:01 +02:00

430 lines
18 KiB
C#

using Audit.WebApi;
using Betalgo.Ranul.OpenAI.Extensions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using Newtonsoft.Json;
using RMuseum.DbContext;
using RMuseum.Models.Auth.Memory;
using RMuseum.Services;
using RMuseum.Services.Implementation;
using RMuseum.Services.Implementationa;
using RMuseum.Utils.SemanticSearch;
using RSecurityBackend.Authorization;
using RSecurityBackend.DbContext;
using RSecurityBackend.Models.Auth.Db;
using RSecurityBackend.Models.Auth.Memory;
using RSecurityBackend.Models.Mail;
using RSecurityBackend.Services;
using RSecurityBackend.Services.Implementation;
using RSecurityBackend.Utilities;
using Swashbuckle.AspNetCore.Filters;
using System;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace RMuseum
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
private string[] AllowedOrigins => (Configuration["Cors:AllowedOrigins"] ?? "")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(o => o.TrimEnd('/')).ToArray();
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add service and create Policy with options
services.AddCors(options =>
{
options.AddPolicy("DiwanCorsPolicy",
// diwan: Cors:AllowedOrigins (comma separated, e.g. https://diwan.example) restricts browsers;
// unset = any origin (local development)
builder => builder.SetIsOriginAllowed(origin => AllowedOrigins.Length == 0 || AllowedOrigins.Contains(origin.TrimEnd('/'), StringComparer.OrdinalIgnoreCase))
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("paging-headers", "audio-upload-enabled", "items-count")
.AllowCredentials()
);
});
services.AddDbContextPool<RMuseumDbContext>(
options => options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
providerOptions => {
providerOptions.EnableRetryOnFailure();
providerOptions.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
}
).ConfigureWarnings(warnings =>
warnings.Ignore(RelationalEventId.PendingModelChangesWarning))
);
//Audit.Core.Configuration.JsonSettings.ContractResolver = AuditNetEnvironmentSkippingContractResolver.Instance;
Audit.Core.Configuration.DataProvider = new RAuditDataProvider(Configuration.GetConnectionString("DefaultConnection"));
Audit.Core.Configuration.AuditDisabled = bool.Parse(Configuration["AuditNetEnabled"]) == false;
services.AddIdentityCore<RAppUser>(
options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
}
).AddErrorDescriber<PersianIdentityErrorDescriber>();
new IdentityBuilder(typeof(RAppUser), typeof(RAppRole), services)
.AddRoleManager<RoleManager<RAppRole>>()
.AddSignInManager<SignInManager<RAppUser>>()
.AddEntityFrameworkStores<RMuseumDbContext>()
.AddErrorDescriber<PersianIdentityErrorDescriber>();
services.AddMvc(mvc =>
mvc.AddAuditFilter(config => config
.LogRequestIf(r => r.Method != "GET")
.WithEventType("{controller}/{action} ({verb})")
.IncludeHeaders(ctx => !ctx.ModelState.IsValid)
.IncludeRequestBody()
.IncludeModelState()
));
services.AddMemoryCache();
services.AddHttpClient();
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
});
services.AddAuthentication(options =>
{
options.DefaultScheme = "bearer";
}).AddJwtBearer("bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidAudience = "Everyone",
ValidateIssuer = true,
ValidIssuer = Configuration.GetSection("RSecurityBackend")["ApplicationName"] ?? "Diwan", // diwan: issuer follows ApplicationName (the token issuer)
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes($"{Configuration.GetSection("Security")["Secret"]}")),
ValidateLifetime = true, //validate the expiration and not before values in the token
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Append("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
services.AddAuthorization(options =>
{
//this is the default policy to make sure the use session has not yet been deleted by him/her from another client
//or by an admin (Authorize with no policy should fail on deleted sessions)
var defPolicy = new AuthorizationPolicyBuilder();
defPolicy.Requirements.Add(new UserGroupPermissionRequirement("null", "null"));
options.DefaultPolicy = defPolicy.Build();
foreach (SecurableItem Item in RMuseumSecurableItem.Items)
{
foreach (SecurableItemOperation Operation in Item.Operations)
{
options.AddPolicy($"{Item.ShortName}:{Operation.ShortName}", policy => policy.Requirements.Add(new UserGroupPermissionRequirement(Item.ShortName, Operation.ShortName)));
}
}
});
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "RMuseum API",
Version = "v1",
Description = "RMuseum API",
TermsOfService = new Uri("https://ganjoor.net/contact"),
Contact = new OpenApiContact
{
Name = "Diwan",
Email = "diwan@ganjoor.net",
Url = new Uri("https://ganjoor.net")
}
}
);
c.EnableAnnotations();
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "RSecurityBackend.xml"));
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
{
Description = "format: \"bearer {token}\"",
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.OperationFilter<SecurityRequirementsOperationFilter>();
c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); // Adds "(Auth)" to the summary so that you can see which endpoints have Authorization
// or use the generic method, e.g. c.OperationFilter<AppendAuthorizeToSummaryOperationFilter<MyCustomAttribute>>();
});
//IHttpContextAccessor
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//authorization handler
services.AddScoped<IAuthorizationHandler, UserGroupPermissionHandler>();
//security context maps to main db context
services.AddTransient<RSecurityDbContext<RAppUser, RAppRole, Guid>, RMuseumDbContext>();
//captcha service
services.AddTransient<ICaptchaService, CaptchaServiceEF>();
//generic image file service
services.AddTransient<IImageFileService, ImageFileServiceEF>();
//app user services
services.AddTransient<IAppUserService, DiwanAppUserService>();
//user groups services
services.AddTransient<IUserRoleService, RoleService>();
//audit service
services.AddTransient<IAuditLogService, AuditLogServiceEF>();
//user permission checker
services.AddTransient<IUserPermissionChecker, UserPermissionChecker>();
//secret generator
services.AddTransient<ISecretGenerator, SecretGenerator>();
// email service
services.AddTransient<IEmailSender, MailKitEmailSender>();
services.Configure<SmptConfig>(Configuration);
//picture file service
services.AddTransient<IPictureFileService, PictureFileService>();
//messaging service
services.AddTransient<IRNotificationService, RNotificationService>();
//artifact service
services.AddTransient<IArtifactService, ArtifactService>();
//audio service
services.AddTransient<IRecitationService, RecitationService>();
//diwan service
services.AddTransient<IDiwanService, DiwanService>();
//music catalogue service
//long running job service
services.AddTransient<ILongRunningJobProgressService, LongRunningJobProgressServiceEF>();
//generic options service
services.AddTransient<IRGenericOptionsService, RGenericOptionsServiceEF>();
//site banner service
services.AddTransient<ISiteBannersService, SiteBannersService>();
//donation service
services.AddTransient<IDonationService, DonationService>();
//translation service
services.AddTransient<IDiwanTranslationService, DiwanTranslationService>();
//numbering service
services.AddTransient<IDiwanNumberingService, DiwanNumberingService>();
//geo location service
services.AddTransient<IGeoLocationService, GeoLocationService>();
//related people (family tree / person tagging) service
services.AddTransient<IDiwanRelatedPersonService, DiwanRelatedPersonService>();
//tracking service
services.AddTransient<IUserVisitsTrackingService, UserVisitsTrackingService>();
//poet photo suggestion service
services.AddTransient<IPoetPhotoSuggestionService, PoetPhotoSuggestionService>();
//faq service
services.AddTransient<IFAQService, FAQService>();
//workspace service
services.AddTransient<IWorkspaceService, WorkspaceService>();
//workspace role service
services.AddTransient<IWorkspaceRolesService, WorkspaceRolesServiceBase>();
//Queued FTP Upload Service
services.AddTransient<IQueuedFTPUploadService, QueuedFTPUploadService>();
//Contributions stats service
services.AddTransient<IContributionStatsService, ContributionStatsService>();
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
services.AddOpenAIService();
// See LazySemanticSearchResources.cs: this is deliberately NOT
// services.AddSingleton<EmbeddingIndex>(sp => EmbeddingIndex.Load(...)) anymore. That
// eager, throwing factory is what caused a production 503 on the whole /api/diwan
// surface when the configured paths were wrong — DiwanController's constructor
// (via ISemanticSearchService) couldn't be built, so nothing under that route could
// run. LazySemanticSearchResources defers the actual load to first real use and
// never throws; a failure there disables semantic search only.
services.AddSingleton<LazySemanticSearchResources>();
// Separate lazy singleton from LazySemanticSearchResources - poet/category name
// detection ("در کدام شعر حافظ") is an independent concern with its own independent
// failure mode; a bug in one must not be able to disable the other.
services.AddSingleton<LazyQueryScopeIndex>();
services.AddSingleton<ISemanticSearchService, SemanticSearchService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// diwan: never run outside Development with a missing JWT signing secret (upstream shipped a public default)
if (!env.IsDevelopment() && string.IsNullOrWhiteSpace(Configuration["Security:Secret"]))
throw new InvalidOperationException("Security:Secret is not set (env Security__Secret). Refusing to start.");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// RMuseum is API-only (see UseEndpoints below - MapControllers only), so there is no
// Razor "/Error" page or MVC "Error" action for the old app.UseExceptionHandler("/Error")
// to redirect to - that redirect just 404s, and (especially when hosted behind IIS/ANCM,
// as in production here) a 404 with no body of its own can get replaced by IIS's own
// generic HTML error page instead. Either way, callers - including DiwanRazor's own
// server-side page handlers, which otherwise assume every error body is a JSON-encoded
// string - got back unreadable HTML instead of the real exception, visible only by
// digging through the Windows Event Log. Handling the exception directly here instead
// of redirecting anywhere guarantees a small JSON-string body with the real exception
// message, in the exact same shape a normal RServiceResult.ExceptionString error already
// comes back as (see e.g. DiwanController's "return BadRequest(res.ExceptionString)"),
// so every existing client-side error handler keeps working unchanged.
app.UseExceptionHandler(errApp =>
{
errApp.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json; charset=utf-8";
var exceptionFeature = context.Features.Get<IExceptionHandlerPathFeature>();
var message = exceptionFeature?.Error?.ToString() ?? "خطای غیرمنتظره‌ای در سرور رخ داد.";
await context.Response.WriteAsync(JsonConvert.SerializeObject(message));
});
});
}
app.UseStaticFiles();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "RMuseum API V1");
c.RoutePrefix = string.Empty;
});
app.UseAuthentication();
// global policy - assign here or on each controller
app.UseCors("DiwanCorsPolicy");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}