-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathProgram.cs
More file actions
228 lines (186 loc) · 7.72 KB
/
Copy pathProgram.cs
File metadata and controls
228 lines (186 loc) · 7.72 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
using Definitions.Database;
using Definitions.ObjectModels;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using ObjectService;
using ObjectService.Frontend;
using ObjectService.RouteHandlers;
using ObjectService.Services;
using Scalar.AspNetCore;
using System.Text;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
var connectionString = builder.Configuration.GetConnectionString("SQLiteConnection");
builder.Services.AddOpenApi(options =>
{
_ = options.AddDocumentTransformer((document, context, cancellationToken) =>
{
document.Info.Title = "OpenLoco Object Service";
document.Info.Version = "2.0";
document.Info.Contact = new OpenApiContact
{
Name = "Left of Zen",
Email = "leftofzen@openloco.io"
};
document.Servers?.Clear();
document.Servers?.Add(new OpenApiServer() { Url = "https://openloco.leftofzen.dev" });
return Task.CompletedTask;
});
});
// (options => _ = options.AddDocumentTransformer<BearerSecuritySchemeTransformer>());
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddHealthChecks()
.AddCheck<ObjectServiceHealthCheck>("object-service");
builder.Services.AddProblemDetails();
builder.Services.AddRazorPages();
builder.Services.AddHttpClient();
builder.Services.AddHttpContextAccessor();
builder.Services.AddDbContext<LocoDbContext>(options =>
{
_ = options.UseSqlite(connectionString);
if (builder.Environment.IsDevelopment())
{
// EnableSensitiveDataLogging exposes parameter values in logs, which can
// leak PII / secrets. Restrict to the Development environment.
_ = options.EnableDetailedErrors();
_ = options.EnableSensitiveDataLogging();
}
});
builder.Services.AddScoped<ObjectExplorerService>();
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
// this breaks the client side, even if the same converter is added...
//builder.Services.Configure<JsonOptions>(options => options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
var objRoot = builder.Configuration["ObjectService:RootFolder"];
var paletteMapFile = builder.Configuration["ObjectService:PaletteMapFile"];
ArgumentNullException.ThrowIfNull(objRoot);
ArgumentNullException.ThrowIfNull(paletteMapFile);
var serverFolderManager = new ServerFolderManager(objRoot);
var paletteMap = new PaletteMap(paletteMapFile);
builder.Services.AddSingleton(serverFolderManager);
builder.Services.AddSingleton(paletteMap);
//var server = new Server(new ServerSettings(objRoot, paletteMapFile));
//builder.Services.AddSingleton(server);
builder.Services.AddHttpLogging(logging =>
{
// these are marked [redacted] in the logs unless specified here
_ = logging.RequestHeaders.Add("Cdn-Loop");
_ = logging.RequestHeaders.Add("Cf-Connecting-Ip");
_ = logging.RequestHeaders.Add("Cf-Ipcountry");
_ = logging.RequestHeaders.Add("Cf-Ray");
_ = logging.RequestHeaders.Add("Cf-Visitor");
_ = logging.RequestHeaders.Add("Cf-Warp-Tag-Id");
_ = logging.RequestHeaders.Add("X-Forwarded-For");
_ = logging.RequestHeaders.Add("X-Forwarded-Proto");
logging.LoggingFields = HttpLoggingFields.All;
//logging.LoggingFields = HttpLoggingFields.ResponsePropertiesAndHeaders | HttpLoggingFields.Duration; // this is `All` excluding `ResponseBody`
logging.CombineLogs = true;
});
const string tokenPolicy = "token";
var rateLimiterSection = builder.Configuration.GetSection("ObjectService:RateLimiter");
ArgumentNullException.ThrowIfNull(rateLimiterSection);
var rateLimiter = new RateLimitOptions();
rateLimiterSection.Bind(rateLimiter);
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
builder.Services.AddRateLimiter(rlOptions => rlOptions
.AddTokenBucketLimiter(policyName: tokenPolicy, options =>
{
options.TokenLimit = rateLimiter.TokenLimit;
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = rateLimiter.QueueLimit;
options.ReplenishmentPeriod = TimeSpan.FromSeconds(rateLimiter.ReplenishmentPeriod);
options.TokensPerPeriod = rateLimiter.TokensReplenishedPerPeriod;
options.AutoReplenishment = rateLimiter.AutoReplenishment;
rlOptions.OnRejected = (context, cancellationToken) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter = retryAfter.TotalSeconds.ToString();
}
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
_ = context.HttpContext.Response.WriteAsync("Too many requests. Please try again later.", cancellationToken);
return new ValueTask();
};
}));
builder.Services
.AddIdentityApiEndpoints<TblUser>()
.AddEntityFrameworkStores<LocoDbContext>();
// Configure bearer token expiration from settings
builder.Services.Configure<BearerTokenOptions>(IdentityConstants.BearerScheme, options =>
{
var durationInMinutes = builder.Configuration.GetValue<int?>("JwtSettings:DurationInMinutes") ?? 60;
options.BearerTokenExpiration = TimeSpan.FromMinutes(durationInMinutes);
});
builder.Services.AddAuthentication()
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
ValidAudience = builder.Configuration["JwtSettings:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:Key"] ?? throw new InvalidOperationException("JWT Key not configured"))),
};
});
builder.Services.AddAuthorization(options =>
{
// Configure the default policy to accept both Identity Bearer tokens and JWT tokens
options.DefaultPolicy = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(IdentityConstants.BearerScheme, JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
// Used for the Identity stuff to send emails to users
// disabling this line effectively disables all email sending, as a default NoOpEmailSender is used in place
// builder.Services.AddTransient<IEmailSender, EmailSender>();
var app = builder.Build();
app.UseForwardedHeaders();
app.UseHttpLogging();
app.UseRateLimiter();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.MapIdentityApi<TblUser>();
// defining routes here, after MapIdentityApi, will overwrite them, allowing us to customise them
// app.MapPost("/register", () => Results.Ok());
_ = app
.MapHealthChecks("/health")
.RequireRateLimiting(tokenPolicy);
_ = app.MapRazorPages();
_ = app.MapV2Routes()
.RequireRateLimiting(tokenPolicy);
_ = app.MapV1Routes()
.RequireRateLimiting(tokenPolicy);
var showScalar = builder.Configuration.GetValue<bool?>("ObjectService:ShowScalar");
ArgumentNullException.ThrowIfNull(showScalar);
_ = app.MapOpenApi();
if (showScalar == true)
{
_ = app.MapScalarApiReference("/api", options =>
{
_ = options
.WithTitle("OpenLoco Object Service")
.WithTheme(ScalarTheme.Solarized)
.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient)
.AddPreferredSecuritySchemes("Bearer");
});
}
app.Run();
#pragma warning disable CA1050 // Declare types in namespaces
// this is to enable unit testing in a top-level statement program
public partial class Program;
#pragma warning restore CA1050 // Declare types in namespaces