-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
128 lines (108 loc) · 4.43 KB
/
Program.cs
File metadata and controls
128 lines (108 loc) · 4.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
using System.Threading.RateLimiting;
using Infostacker.Services;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Serilog;
using SharingService = Infostacker.Services.SharingService;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
const string AllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Configuration.AddJsonFile("version.json", optional: true);
string seqServer = builder.Configuration.GetValue<string>("SeqServer")?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(seqServer))
{
seqServer = "https://localhost:5341";
}
builder.Host.UseSerilog((_, _, loggerConfiguration) =>
{
loggerConfiguration
.Enrich.WithProperty("Application", "InfostackerService")
.WriteTo.Console()
.WriteTo.File("Logs/logs.txt", rollingInterval: RollingInterval.Day)
.WriteTo.Seq(seqServer)
.MinimumLevel.Information();
});
builder.Services.AddMemoryCache();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddTransient<ISharingService, SharingService>();
long maxRequestBodySize = builder.Configuration.GetValue<long?>("MaxRequestBodySizeInBytes") is > 0
? builder.Configuration.GetValue<long>("MaxRequestBodySizeInBytes")
: 104857600L;
builder.Services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = maxRequestBodySize;
});
builder.WebHost.ConfigureKestrel(options =>
{
options.Limits.MaxRequestBodySize = maxRequestBodySize;
});
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
int readRequestsPerMinute = builder.Configuration.GetValue<int?>("RateLimiting:ReadRequestsPerMinute") is > 0
? builder.Configuration.GetValue<int>("RateLimiting:ReadRequestsPerMinute")
: 120;
int writeRequestsPerMinute = builder.Configuration.GetValue<int?>("RateLimiting:WriteRequestsPerMinute") is > 0
? builder.Configuration.GetValue<int>("RateLimiting:WriteRequestsPerMinute")
: 30;
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) =>
{
Log.Warning(
"Rate limit exceeded for {IpAddress} on {RequestPath}.",
context.HttpContext.Connection.RemoteIpAddress?.ToString(),
context.HttpContext.Request.Path.Value);
context.HttpContext.Response.ContentType = "application/json";
await context.HttpContext.Response.WriteAsync("{\"message\":\"Rate limit exceeded. Try again later.\"}", cancellationToken)
.ConfigureAwait(false);
};
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
{
string ipAddress = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown-ip";
bool isWriteMethod = HttpMethods.IsPost(httpContext.Request.Method)
|| HttpMethods.IsPut(httpContext.Request.Method)
|| HttpMethods.IsDelete(httpContext.Request.Method);
int permitLimit = isWriteMethod ? writeRequestsPerMinute : readRequestsPerMinute;
string partitionKey = $"{ipAddress}:{(isWriteMethod ? "write" : "read")}";
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey,
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = permitLimit,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
AutoReplenishment = true
});
});
});
builder.Services.AddCors(options =>
{
options.AddPolicy(AllowSpecificOrigins, policy =>
{
policy.WithOrigins("app://obsidian.md")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
WebApplication app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseForwardedHeaders();
app.UseSerilogRequestLogging();
app.UseHttpsRedirection();
app.UseCors(AllowSpecificOrigins);
app.UseRateLimiter();
app.UseAuthorization();
app.MapControllers();
app.Run();