| | 1 | | using LGDXRobotCloud.API.Authentication; |
| | 2 | | using LGDXRobotCloud.API.Authorisation; |
| | 3 | | using LGDXRobotCloud.API.Configurations; |
| | 4 | | using LGDXRobotCloud.API.Middleware; |
| | 5 | | using LGDXRobotCloud.API.Services; |
| | 6 | | using LGDXRobotCloud.API.Services.Administration; |
| | 7 | | using LGDXRobotCloud.API.Services.Automation; |
| | 8 | | using LGDXRobotCloud.API.Services.Common; |
| | 9 | | using LGDXRobotCloud.API.Services.Identity; |
| | 10 | | using LGDXRobotCloud.API.Services.Navigation; |
| | 11 | | using LGDXRobotCloud.Data.DbContexts; |
| | 12 | | using LGDXRobotCloud.Data.Entities; |
| | 13 | | using LGDXRobotCloud.Utilities.Constants; |
| | 14 | | using MassTransit; |
| | 15 | | using Microsoft.AspNetCore.Authentication; |
| | 16 | | using Microsoft.AspNetCore.Authentication.Certificate; |
| | 17 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | 18 | | using Microsoft.AspNetCore.Authorization; |
| | 19 | | using Microsoft.AspNetCore.Hosting.Server; |
| | 20 | | using Microsoft.AspNetCore.Hosting.Server.Features; |
| | 21 | | using Microsoft.AspNetCore.Identity; |
| | 22 | | using Microsoft.AspNetCore.OpenApi; |
| | 23 | | using Microsoft.AspNetCore.Server.Kestrel.Https; |
| | 24 | | using Microsoft.EntityFrameworkCore; |
| | 25 | | using Microsoft.IdentityModel.Tokens; |
| | 26 | | using Microsoft.OpenApi.Models; |
| | 27 | | using Scalar.AspNetCore; |
| | 28 | | using System.Security.Claims; |
| | 29 | | using System.Security.Cryptography.X509Certificates; |
| | 30 | | using System.Text; |
| | 31 | |
|
| | 32 | | var builder = WebApplication.CreateBuilder(args); |
| | 33 | | builder.WebHost.ConfigureKestrel(cfg => |
| | 34 | | { |
| | 35 | | cfg.ConfigureHttpsDefaults(ctx => ctx.ClientCertificateMode = ClientCertificateMode.AllowCertificate); |
| | 36 | | cfg.AddServerHeader = false; |
| | 37 | | }); |
| | 38 | |
|
| | 39 | | /* |
| | 40 | | * Configuration |
| | 41 | | */ |
| | 42 | | builder.Services.Configure<LgdxRobotCloudConfiguration>( |
| | 43 | | builder.Configuration.GetSection("LGDXRobotCloud") |
| | 44 | | ); |
| | 45 | | builder.Services.Configure<LgdxRobotCloudSecretConfiguration>( |
| | 46 | | builder.Configuration.GetSection("LGDXRobotCloudSecret") |
| | 47 | | ); |
| | 48 | |
|
| | 49 | | /* |
| | 50 | | * Infrastructure |
| | 51 | | */ |
| | 52 | | builder.Services.AddMassTransit(cfg => |
| | 53 | | { |
| | 54 | | cfg.UsingRabbitMq((context, cfg) => |
| | 55 | | { |
| | 56 | | cfg.Host(builder.Configuration["RabbitMq:Host"], builder.Configuration["RabbitMq:VirtualHost"], h => |
| | 57 | | { |
| | 58 | | h.Username(builder.Configuration["RabbitMq:Username"] ?? string.Empty); |
| | 59 | | h.Password(builder.Configuration["RabbitMq:Password"] ?? string.Empty); |
| | 60 | | }); |
| | 61 | | }); |
| | 62 | | }); |
| | 63 | | builder.Services.AddMemoryCache(); |
| | 64 | | builder.Services.AddControllers(); |
| | 65 | | builder.Services.AddOpenApi(options => |
| | 66 | | { |
| | 67 | | options.AddDocumentTransformer<BearerSecuritySchemeTransformer>(); |
| | 68 | | }); |
| | 69 | | builder.Services.AddGrpc(cfg => cfg.EnableDetailedErrors = true); |
| | 70 | | builder.Services.AddDbContextPool<LgdxContext>(cfg => |
| | 71 | | cfg.UseNpgsql(builder.Configuration["PGSQLConnectionString"]) |
| | 72 | | .LogTo(Console.WriteLine, LogLevel.Information) |
| | 73 | | .EnableSensitiveDataLogging() |
| | 74 | | .EnableDetailedErrors() |
| | 75 | | ); |
| | 76 | | builder.Services.AddHttpContextAccessor(); |
| | 77 | |
|
| | 78 | | /* |
| | 79 | | * Authentication |
| | 80 | | */ |
| | 81 | | builder.Services.AddIdentity<LgdxUser, LgdxRole>() |
| | 82 | | .AddEntityFrameworkStores<LgdxContext>() |
| | 83 | | .AddTokenProvider<AuthenticatorTokenProvider<LgdxUser>>(TokenOptions.DefaultAuthenticatorProvider) |
| | 84 | | .AddTokenProvider<DataProtectorTokenProvider<LgdxUser>>(TokenOptions.DefaultProvider); |
| | 85 | | builder.Services.AddAuthentication(LgdxRobotCloudAuthenticationSchemes.CertificationScheme) |
| | 86 | | .AddCertificate(LgdxRobotCloudAuthenticationSchemes.CertificationScheme, cfg => |
| | 87 | | { |
| | 88 | | cfg.AllowedCertificateTypes = CertificateTypes.All; |
| | 89 | | cfg.RevocationMode = X509RevocationMode.NoCheck; |
| | 90 | | cfg.Events = new CertificateAuthenticationEvents() |
| | 91 | | { |
| | 92 | | OnCertificateValidated = ctx => |
| | 93 | | { |
| | 94 | | if (ctx.ClientCertificate.Thumbprint != builder.Configuration["LGDXRobotCloud:InternalCertificateThumbprint"]) |
| | 95 | | { |
| | 96 | | ctx.Fail("Invalid certificate."); |
| | 97 | | return Task.CompletedTask; |
| | 98 | | } |
| | 99 | | ctx.Success(); |
| | 100 | | return Task.CompletedTask; |
| | 101 | | } |
| | 102 | | }; |
| | 103 | | } |
| | 104 | | ); |
| | 105 | | builder.Services.AddAuthentication(LgdxRobotCloudAuthenticationSchemes.ApiKeyScheme) |
| | 106 | | .AddScheme<ApiKeyAuthenticationSchemeOptions, ApiKeyAuthenticationSchemeHandler>( |
| | 107 | | LgdxRobotCloudAuthenticationSchemes.ApiKeyScheme, |
| | 108 | | options => {} |
| | 109 | | ); |
| | 110 | | builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| | 111 | | .AddJwtBearer(cfg => |
| | 112 | | { |
| | 113 | | cfg.TokenValidationParameters = new TokenValidationParameters |
| | 114 | | { |
| | 115 | | ValidateIssuer = true, |
| | 116 | | ValidateAudience = true, |
| | 117 | | ValidateLifetime = true, |
| | 118 | | ValidateIssuerSigningKey = true, |
| | 119 | | ValidIssuer = builder.Configuration["LGDXRobotCloudSecret:LgdxUserJwtIssuer"], |
| | 120 | | ValidAudience = builder.Configuration["LGDXRobotCloudSecret:LgdxUserJwtIssuer"], |
| | 121 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["LGDXRobotCloudSecret:Lgd |
| | 122 | | ClockSkew = TimeSpan.Zero |
| | 123 | | }; |
| | 124 | | }); |
| | 125 | | builder.Services.AddTransient<ValidateRobotClientsCertificate>(); |
| | 126 | | builder.Services.AddAuthentication(LgdxRobotCloudAuthenticationSchemes.RobotClientsCertificateScheme) |
| | 127 | | .AddCertificate(LgdxRobotCloudAuthenticationSchemes.RobotClientsCertificateScheme, cfg => |
| | 128 | | { |
| | 129 | | cfg.AllowedCertificateTypes = CertificateTypes.All; |
| | 130 | | cfg.RevocationMode = X509RevocationMode.NoCheck; |
| | 131 | | cfg.Events = new CertificateAuthenticationEvents() |
| | 132 | | { |
| | 133 | | OnCertificateValidated = async ctx => |
| | 134 | | { |
| | 135 | | string subject = ctx.ClientCertificate.Subject; |
| | 136 | | string guid = subject.Substring(subject.IndexOf("OID.0.9.2342.19200300.100.1.1=") + 30, 36); |
| | 137 | | if (guid == string.Empty) |
| | 138 | | { |
| | 139 | | ctx.Fail("Robot ID not found."); |
| | 140 | | return; |
| | 141 | | } |
| | 142 | | var validatior = ctx.HttpContext.RequestServices.GetService<ValidateRobotClientsCertificate>(); |
| | 143 | | if (!await validatior!.Validate(ctx.ClientCertificate, Guid.Parse(guid))) |
| | 144 | | { |
| | 145 | | ctx.Fail("Invalid certificate / Robot not found."); |
| | 146 | | return; |
| | 147 | | } |
| | 148 | | var claims = new[] { |
| | 149 | | new Claim(ClaimTypes.NameIdentifier, guid) |
| | 150 | | }; |
| | 151 | | ctx.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ctx.Scheme.Name)); |
| | 152 | | ctx.Success(); |
| | 153 | | } |
| | 154 | | }; |
| | 155 | | }); |
| | 156 | | builder.Services.AddAuthentication(LgdxRobotCloudAuthenticationSchemes.RobotClientsJwtScheme) |
| | 157 | | .AddJwtBearer(LgdxRobotCloudAuthenticationSchemes.RobotClientsJwtScheme, cfg => |
| | 158 | | { |
| | 159 | | cfg.TokenValidationParameters = new TokenValidationParameters |
| | 160 | | { |
| | 161 | | ValidateIssuer = true, |
| | 162 | | ValidateAudience = true, |
| | 163 | | ValidateLifetime = true, |
| | 164 | | ValidateIssuerSigningKey = true, |
| | 165 | | ValidIssuer = builder.Configuration["LGDXRobotCloudSecret:RobotClientsJwtIssuer"], |
| | 166 | | ValidAudience = builder.Configuration["LGDXRobotCloudSecret:RobotClientsJwtIssuer"], |
| | 167 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["LGDXRobotCloudSecret:Rob |
| | 168 | | ClockSkew = TimeSpan.Zero |
| | 169 | | }; |
| | 170 | | }); |
| | 171 | | builder.Services.AddScoped<IAuthorizationHandler, ValidateLgdxUserAccessHandler>(); |
| | 172 | | builder.Services.AddAuthorizationBuilder() |
| | 173 | | .AddPolicy("ValidateLgdxUserAccess", policyBuilder => |
| | 174 | | { |
| | 175 | | policyBuilder.RequireAuthenticatedUser(); |
| | 176 | | policyBuilder.AddRequirements(new ValidateLgdxUserAccessRequirement()); |
| | 177 | | }); |
| | 178 | | builder.Services.AddScoped<IAuthorizationHandler, RobotClientShouldOnlineHandler>(); |
| | 179 | | builder.Services.AddAuthorizationBuilder() |
| | 180 | | .AddPolicy("RobotClientShouldOnline", policyBuilder => |
| | 181 | | { |
| | 182 | | policyBuilder.RequireAuthenticatedUser(); |
| | 183 | | policyBuilder.AddRequirements(new RobotClientShouldOnlineRequirement()); |
| | 184 | | }); |
| | 185 | |
|
| | 186 | | /* |
| | 187 | | * LGDX Depency Injection |
| | 188 | | */ |
| | 189 | | // Administrator |
| | 190 | | builder.Services.AddScoped<IApiKeyService, ApiKeyService>(); |
| | 191 | | builder.Services.AddScoped<IRobotCertificateService, RobotCertificateService>(); |
| | 192 | | builder.Services.AddScoped<IRoleService, RoleService>(); |
| | 193 | | builder.Services.AddScoped<IUserService, UserService>(); |
| | 194 | |
|
| | 195 | | // Automation |
| | 196 | | builder.Services.AddScoped<IAutoTaskService, AutoTaskService>(); |
| | 197 | | builder.Services.AddScoped<IFlowService, FlowService>(); |
| | 198 | | builder.Services.AddScoped<IProgressService, ProgressService>(); |
| | 199 | |
|
| | 200 | | // Identity |
| | 201 | | builder.Services.AddScoped<IAuthService, AuthService>(); |
| | 202 | | builder.Services.AddScoped<ICurrentUserService, CurrentUserService>(); |
| | 203 | |
|
| | 204 | | // Automation |
| | 205 | | builder.Services.AddScoped<IRealmService, RealmService>(); |
| | 206 | | builder.Services.AddScoped<IWaypointService, WaypointService>(); |
| | 207 | | builder.Services.AddScoped<IRobotService, RobotService>(); |
| | 208 | |
|
| | 209 | | // Custom Services |
| | 210 | | builder.Services.AddScoped<ITriggerRetryService, TriggerRetryService>(); |
| | 211 | | builder.Services.AddScoped<ITriggerService, TriggerService>(); |
| | 212 | | builder.Services.AddScoped<IEmailService, EmailService>(); |
| | 213 | | builder.Services.AddSingleton<IEventService, EventService>(); |
| | 214 | | builder.Services.AddScoped<IAutoTaskSchedulerService, AutoTaskSchedulerService>(); |
| | 215 | | builder.Services.AddScoped<IOnlineRobotsService, OnlineRobotsService>(); |
| | 216 | | builder.Services.AddScoped<IAuthenticationService, AuthenticationService>(); |
| | 217 | |
|
| | 218 | | var app = builder.Build(); |
| | 219 | |
|
| | 220 | | // Configure the HTTP request pipeline. |
| | 221 | | if (app.Environment.IsDevelopment()) |
| | 222 | | { |
| | 223 | | app.MapOpenApi(); |
| | 224 | | app.MapScalarApiReference(); |
| | 225 | | } |
| | 226 | |
|
| | 227 | | app.UseHttpsRedirection(); |
| | 228 | |
|
| | 229 | | app.UseAuthentication(); |
| | 230 | | app.UseAuthorization(); |
| | 231 | |
|
| | 232 | | app.MapControllerRoute( |
| | 233 | | name: "Area", |
| | 234 | | pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); |
| | 235 | | app.MapGrpcService<RobotClientsService>(); |
| | 236 | | app.UseLgdxExpectionHandling(); |
| | 237 | |
|
| | 238 | | app.Run(); |
| | 239 | |
|
| 0 | 240 | | internal sealed class BearerSecuritySchemeTransformer( |
| 0 | 241 | | IAuthenticationSchemeProvider authenticationSchemeProvider, |
| 0 | 242 | | IServer server |
| 0 | 243 | | ) : IOpenApiDocumentTransformer |
| | 244 | | { |
| | 245 | | public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToke |
| 0 | 246 | | { |
| 0 | 247 | | var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync(); |
| 0 | 248 | | if (authenticationSchemes.Any(authScheme => authScheme.Name == JwtBearerDefaults.AuthenticationScheme)) |
| 0 | 249 | | { |
| 0 | 250 | | var requirements = new Dictionary<string, OpenApiSecurityScheme> |
| 0 | 251 | | { |
| 0 | 252 | | ["Bearer"] = new OpenApiSecurityScheme |
| 0 | 253 | | { |
| 0 | 254 | | Type = SecuritySchemeType.Http, |
| 0 | 255 | | Scheme = "bearer", // "bearer" refers to the header name here |
| 0 | 256 | | In = ParameterLocation.Header, |
| 0 | 257 | | BearerFormat = "Json Web Token" |
| 0 | 258 | | } |
| 0 | 259 | | }; |
| 0 | 260 | | document.Components ??= new OpenApiComponents(); |
| 0 | 261 | | document.Components.SecuritySchemes = requirements; |
| 0 | 262 | | } |
| 0 | 263 | | document.Info = new() |
| 0 | 264 | | { |
| 0 | 265 | | Title = "LGDXRobot Cloud API", |
| 0 | 266 | | Version = "v1", |
| 0 | 267 | | Description = "Core API for the LGDXRobot Cloud.", |
| 0 | 268 | | Contact = new OpenApiContact |
| 0 | 269 | | { |
| 0 | 270 | | Name = "LGDXRobot", |
| 0 | 271 | | Url = new Uri("https://lgdxrobot.bristolgram.uk"), |
| 0 | 272 | | }, |
| 0 | 273 | | License = new OpenApiLicense |
| 0 | 274 | | { |
| 0 | 275 | | Name = "The MIT License", |
| 0 | 276 | | Url = new Uri("https://opensource.org/license/MIT") |
| 0 | 277 | | } |
| 0 | 278 | | }; |
| 0 | 279 | | var address = server.Features.Get<IServerAddressesFeature>()!.Addresses.LastOrDefault(); // HTTPS port must higher |
| 0 | 280 | | address = address!.Replace("[::]", "localhost"); |
| 0 | 281 | | document.Servers = |
| 0 | 282 | | [ |
| 0 | 283 | | new() |
| 0 | 284 | | { |
| 0 | 285 | | Url = address, |
| 0 | 286 | | Description = "Default Server" |
| 0 | 287 | | } |
| 0 | 288 | | ]; |
| 0 | 289 | | } |
| | 290 | | } |