-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
286 lines (251 loc) · 10.2 KB
/
Program.cs
File metadata and controls
286 lines (251 loc) · 10.2 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
using System.Security.Claims;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using Serilog.Events;
using ShiftDrop.Common.Services;
using ShiftDrop.Features;
using ShiftDrop.Features.Webhooks.SmsStatus;
// Configure Serilog before anything else
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithEnvironmentName()
.Enrich.WithThreadId()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}")
.CreateBootstrapLogger();
try
{
Log.Information("Starting ShiftDrop API");
var builder = WebApplication.CreateBuilder(args);
// Use Serilog for all logging
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithEnvironmentName()
.Enrich.WithThreadId()
.Enrich.WithProperty("Application", "ShiftDrop")
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Problem Details for consistent error responses (RFC 7807)
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = context =>
{
context.ProblemDetails.Extensions["traceId"] = context.HttpContext.TraceIdentifier;
};
});
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddCors(options =>
{
options.AddPolicy("DevCors", policy =>
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod());
// Production CORS - allow Vercel frontend and configurable origins
var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
?? Array.Empty<string>();
options.AddPolicy("ProdCors", policy =>
policy.WithOrigins(allowedOrigins.Concat(new[] { "https://shift-drop.vercel.app", "https://frontend-five-lovat-27.vercel.app" }).ToArray())
.AllowAnyHeader()
.AllowAnyMethod());
});
// Rate limiting to prevent abuse
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
// Global policy: 100 requests per minute per IP
options.AddPolicy("fixed", httpContext =>
{
// Check if rate limiting is disabled (e.g., in tests) at request time
var config = httpContext.RequestServices.GetRequiredService<IConfiguration>();
var disabled = config.GetValue<bool>("RateLimiting:Disabled");
var limit = disabled ? int.MaxValue : 100;
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = limit,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0 // Reject immediately when limit reached
});
});
// Strict policy for anonymous endpoints: 20 requests per minute
options.AddPolicy("strict", httpContext =>
{
var config = httpContext.RequestServices.GetRequiredService<IConfiguration>();
var disabled = config.GetValue<bool>("RateLimiting:Disabled");
var limit = disabled ? int.MaxValue : 20;
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = limit,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0
});
});
// SMS-sending endpoints: 5 per minute per user (prevents spam/accidents)
// Keyed by authenticated user ID to prevent abuse regardless of IP
options.AddPolicy("sms-send", httpContext =>
{
var config = httpContext.RequestServices.GetRequiredService<IConfiguration>();
var disabled = config.GetValue<bool>("RateLimiting:Disabled");
var limit = disabled ? int.MaxValue : 5;
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "anonymous",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = limit,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0
});
});
});
// SMS service: Use Twilio if configured, otherwise Console (logs only)
var twilioConfigured = !string.IsNullOrEmpty(builder.Configuration["Twilio:AccountSid"]);
if (twilioConfigured)
{
builder.Services.AddScoped<ISmsService, TwilioSmsService>();
}
else
{
builder.Services.AddScoped<ISmsService, ConsoleSmsService>();
}
builder.Services.AddHostedService<OutboxProcessor>();
// Push notification service
builder.Services.Configure<WebPushOptions>(builder.Configuration.GetSection("WebPush"));
builder.Services.AddScoped<IPushNotificationService, WebPushNotificationService>();
builder
.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = builder.Configuration["Auth0:Authority"];
options.Audience = builder.Configuration["Auth0:Audience"];
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
};
});
builder.Services.AddAuthorization();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection"),
sqlOptions => sqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null))
);
builder.Services.Configure<DbKeepAliveOptions>(
builder.Configuration.GetSection("DbKeepAlive"));
builder.Services.AddHostedService<DbKeepAliveService>();
// Health checks with DB connectivity
builder.Services.AddHealthChecks()
.AddSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection") ?? "",
name: "sqlserver",
tags: ["db", "ready"]);
var app = builder.Build();
// Global exception handler - returns Problem Details (RFC 7807)
app.UseExceptionHandler(exceptionApp =>
{
exceptionApp.Run(async context =>
{
var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>();
var exception = exceptionFeature?.Error;
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogError(exception, "Unhandled exception occurred. TraceId: {TraceId}", context.TraceIdentifier);
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An unexpected error occurred",
Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1",
Instance = context.Request.Path,
Extensions = { ["traceId"] = context.TraceIdentifier }
};
// Don't expose exception details in production
if (app.Environment.IsDevelopment())
{
problemDetails.Detail = exception?.Message;
}
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/problem+json";
await context.Response.WriteAsJsonAsync(problemDetails);
});
});
// Structured request logging
app.UseSerilogRequestLogging(options =>
{
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("UserAgent", httpContext.Request.Headers.UserAgent.ToString());
};
});
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors("DevCors");
}
else
{
app.UseHttpsRedirection();
app.UseCors("ProdCors");
}
app.UseAuthentication();
app.UseAuthorization();
// Rate limiting (must run after authentication so sms-send policy can access User claims)
app.UseRateLimiter();
// Health endpoints
app.MapHealthChecks("/health/ready", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready"),
ResponseWriter = async (context, report) =>
{
context.Response.ContentType = "application/json";
var result = new
{
status = report.Status.ToString(),
checks = report.Entries.Select(e => new
{
name = e.Key,
status = e.Value.Status.ToString(),
duration = e.Value.Duration.TotalMilliseconds
})
};
await context.Response.WriteAsJsonAsync(result);
}
}).AllowAnonymous();
// Simple liveness check (no dependencies)
app.MapGet("/health", () => Results.Ok(new { status = "Healthy" })).AllowAnonymous();
app.MapSmsStatusWebhook();
app.MapFeatures();
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
throw; // Re-throw so tests can see startup failures
}
finally
{
Log.CloseAndFlush();
}
// Make Program accessible for WebApplicationFactory in tests
public partial class Program { }