-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
290 lines (245 loc) · 11.5 KB
/
Program.cs
File metadata and controls
290 lines (245 loc) · 11.5 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
287
288
289
290
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication;
using SatOps.Configuration;
using SatOps.Modules.Groundstation;
using SatOps.Modules.FlightPlan;
using SatOps.Modules.Satellite;
using SatOps.Modules.User;
using SatOps.Authorization;
using System.Text.Json;
using SatOps.Data;
using Minio;
using Npgsql;
using System.Text;
using Serilog;
using dotenv.net;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using SatOps.Modules.GroundStationLink;
DotEnv.Load();
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
try
{
Log.Information("Starting SatOps web host");
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext());
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseUpper));
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerConfiguration(builder.Configuration);
// Add HttpClientFactory for calling external APIs (Auth0 UserInfo)
builder.Services.AddHttpClient();
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddMemoryCache();
// Database
var dataSourceBuilder = new NpgsqlDataSourceBuilder(
builder.Configuration.GetConnectionString("DefaultConnection")!
);
// Enable dynamic JSON serialization support (for List<string>, etc.)
dataSourceBuilder.EnableDynamicJson();
var dataSource = dataSourceBuilder.Build();
builder.Services.AddDbContext<SatOpsDbContext>(options =>
{
options.UseNpgsql(dataSource, npgsqlOptions =>
{
npgsqlOptions.MigrationsAssembly("SatOps");
});
});
// Prevent .NET from renaming JWT claims (e.g. "sub" → "nameidentifier")
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
// Configure Authentication with multiple JWT schemes
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// Auth0 JWT Bearer Authentication for human users
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
var auth0Settings = builder.Configuration.GetSection("Auth0");
var domain = auth0Settings["Domain"] ?? throw new InvalidOperationException("Auth0 Domain not configured.");
var audience = auth0Settings["Audience"] ?? throw new InvalidOperationException("Auth0 Audience not configured.");
options.Authority = $"https://{domain}/";
options.Audience = audience;
options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();
// Save the token so we can use it to call Auth0 UserInfo endpoint
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero
};
// Enable BootstrapContext to access the raw token in ClaimsTransformer
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
if (context is { SecurityToken: JwtSecurityToken jwtToken, Principal.Identity: ClaimsIdentity identity })
{
identity.BootstrapContext = jwtToken.RawData;
}
return Task.CompletedTask;
}
};
})
// Ground Station JWT Bearer Authentication
.AddJwtBearer("GroundStation", options =>
{
var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = jwtSettings["Key"] ?? throw new InvalidOperationException("JWT Key not configured.");
var issuer = jwtSettings["Issuer"] ?? throw new InvalidOperationException("JWT Issuer not configured.");
var audience = jwtSettings["Audience"] ?? throw new InvalidOperationException("JWT Audience not configured.");
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
ValidateIssuer = true,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudience = audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5)
};
});
// Authorization with role-based policies
// Hierarchical roles: Admin (2) > Operator (1) > Viewer (0)
builder.Services.AddAuthorization(options =>
{
// Special policy for ground station machine authentication
// Uses the "GroundStation" authentication scheme
options.AddPolicy(Policies.RequireGroundStation, policy =>
{
policy.AuthenticationSchemes.Add("GroundStation");
policy.RequireAuthenticatedUser();
policy.RequireClaim("type", "GroundStation");
});
// Role-based policies for human users
// These use hierarchical role checking: higher roles include lower permissions
options.AddPolicy(Policies.RequireViewer, policy =>
policy.Requirements.Add(new MinimumRoleRequirement(UserRole.Viewer)));
options.AddPolicy(Policies.RequireOperator, policy =>
policy.Requirements.Add(new MinimumRoleRequirement(UserRole.Operator)));
options.AddPolicy(Policies.RequireAdmin, policy =>
policy.Requirements.Add(new MinimumRoleRequirement(UserRole.Admin)));
});
// DI
builder.Services.AddScoped<IGroundStationRepository, GroundStationRepository>();
builder.Services.AddScoped<IGroundStationService, GroundStationService>();
builder.Services.AddScoped<IFlightPlanRepository, FlightPlanRepository>();
builder.Services.AddScoped<IFlightPlanService, FlightPlanService>();
builder.Services.AddScoped<IImagingCalculation, ImagingCalculation>();
builder.Services.AddScoped<ISatelliteRepository, SatelliteRepository>();
builder.Services.AddScoped<ISatelliteService, SatelliteService>();
builder.Services.AddScoped<ICelestrackClient, CelestrackClient>();
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<SatOps.Modules.Overpass.IOverpassRepository, SatOps.Modules.Overpass.OverpassRepository>();
builder.Services.AddScoped<SatOps.Modules.Overpass.IOverpassService, SatOps.Modules.Overpass.OverpassService>();
builder.Services.AddScoped<ICurrentUserProvider, CurrentUserProvider>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<IAuth0Client, Auth0Client>();
builder.Services.AddSingleton<IWebSocketService, WebSocketService>();
// MinIO Configuration
builder.Services.AddSingleton(sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
var endpoint = configuration.GetValue<string>("MinIO:Endpoint") ?? "localhost:9000";
var accessKey = configuration.GetValue<string>("MinIO:AccessKey") ?? "minioadmin";
var secretKey = configuration.GetValue<string>("MinIO:SecretKey") ?? "minioadmin";
var secure = configuration.GetValue<bool>("MinIO:Secure");
return new MinioClient()
.WithEndpoint(endpoint)
.WithCredentials(accessKey, secretKey)
.WithSSL(secure)
.Build();
});
// Imaging Calculation Configuration
builder.Services.Configure<ImagingCalculationOptions>(
builder.Configuration.GetSection("ImagingCalculation"));
// Operation Services
builder.Services.AddScoped<IObjectStorageService, ObjectStorageService>();
builder.Services.AddScoped<IImageService, ImageService>();
// Authorization handlers
builder.Services.AddScoped<IAuthorizationHandler, MinimumRoleAuthorizationHandler>();
builder.Services.AddScoped<IClaimsTransformation, UserPermissionsClaimsTransformation>();
// Background services
builder.Services.AddHostedService<GroundStationHealthCheckWorker>();
builder.Services.AddHostedService<SchedulerService>();
builder.Services.AddHostedService<TleUpdateWorker>();
var app = builder.Build();
app.UseSerilogRequestLogging();
// Configure the HTTP request pipeline.
// Global exception handling: never leak internals to clients
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("GlobalExceptionHandler");
var exceptionHandler = context.Features.Get<IExceptionHandlerFeature>();
var exception = exceptionHandler?.Error;
// Always return sanitized ProblemDetails
var problem = new ProblemDetails
{
Title = "An unexpected error occurred.",
Status = StatusCodes.Status500InternalServerError,
Type = "about:blank",
Detail = null,
Instance = context.Request.Path
};
// Log full exception details for diagnostics
if (exception != null)
{
logger.LogError(exception, "Unhandled exception while processing {Method} {Path}", context.Request.Method, context.Request.Path);
}
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/problem+json";
var json = JsonSerializer.Serialize(problem);
await context.Response.WriteAsync(json);
});
});
app.UseSwaggerConfiguration(builder.Configuration);
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Apply pending migrations on startup
if (!AppDomain.CurrentDomain.FriendlyName.Equals("ef", StringComparison.OrdinalIgnoreCase))
{
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<SatOpsDbContext>();
db.Database.Migrate();
}
app.UseWebSockets();
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}