forked from dotnet/orleans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Startup.cs
410 lines (363 loc) · 19.3 KB
/
Startup.cs
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
using Hellang.Middleware.ProblemDetails;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using OneBoxDeployment.Api.Filters;
using OneBoxDeployment.Api.Logging;
using OneBoxDeployment.Common;
using OneBoxDeployment.GrainInterfaces;
using OneBoxDeployment.OrleansUtilities;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Statistics;
using Serilog;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Security.Principal;
using System.Threading.Tasks;
namespace OneBoxDeployment.Api
{
/// <summary>
/// An API startup class with modifications.
/// </summary>
public class Startup
{
/// <summary>
/// This is the root to Swagger documentation URL and to the
/// generated content.
/// </summary>
private string SwaggerRoot { get; } = "api-docs";
/// <summary>
/// The root for Swagger documentation URL.
/// </summary>
private string SwaggerDocumentationBasePath { get; } = "OneBoxDeployment";
/// <summary>
/// The environment specific configuration object.
/// </summary>
public IConfiguration Configuration { get; }
/// <summary>
/// The environment specific logger.
/// </summary>
public Microsoft.Extensions.Logging.ILogger Logger { get; }
/// <summary>
/// The hosting environment.
/// </summary>
public IWebHostEnvironment Environment { get; set; }
/// <summary>
/// A default constructor.
/// </summary>
/// <param name="logger">The environment specific logger.</param>
/// <param name="configuration">The environment specific configuration object.</param>
/// <param name="env">The environment information to use in checking per deployment type configuration value validity.</param>
public Startup(ILogger<Startup> logger, IConfiguration configuration, IWebHostEnvironment env)
{
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
Environment = env ?? throw new ArgumentNullException(nameof(env));
if(Environment.IsProduction())
{
foreach(var forbiddenKey in ConfigurationKeys.ConfigurationKeysForbiddenInProduction)
{
var forbiddenKeys = new List<string>();
if(configuration.GetValue<string>(forbiddenKey, null) != null)
{
forbiddenKeys.Add(forbiddenKey);
}
//Note: ConfigurationErrorsException could be thrown here, but it'd require taking
//a dependency to System.Configuration.
if(forbiddenKeys.Any())
{
throw new ArgumentException($"The following keys are forbidden in production " +
$"= {env.EnvironmentName}: {string.Join(',', forbiddenKeys)}", nameof(configuration));
}
}
}
}
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">The ASP.NET services collection.</param>
public void ConfigureServices(IServiceCollection services)
{
if(Environment.IsProduction())
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddCors(options =>
{
var allowedOrigins = Configuration.GetSection("AllowedOrigins").Get<string[]>();
options.AddPolicy("CorsPolicy",
builder => builder
.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader());
});
}
else
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
}
//See more about formatters at https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting.
services
.AddProblemDetails(ConfigureProblemDetails)
.AddMvcCore(options =>
{
if(!Environment.IsDevelopment())
{
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
}
options.Conventions.Add(new NotFoundResultFilterConvention());
//The Content-Security-Policy (CSP) is JSON, so it's added here to the known JSON serialized types.
const string MimeTypeCspReport = "application/csp-report";
var jsonOutputFormatter = options.OutputFormatters.OfType<SystemTextJsonOutputFormatter>().FirstOrDefault();
if(jsonOutputFormatter != null)
{
jsonOutputFormatter.SupportedMediaTypes.Add(MimeTypeCspReport);
}
var jsonInputFormatter = options.InputFormatters.OfType<SystemTextJsonInputFormatter>().FirstOrDefault();
if(jsonInputFormatter != null)
{
jsonInputFormatter.SupportedMediaTypes.Add(MimeTypeCspReport);
}
})
.AddApiExplorer()
//.AddAuthorization()
.AddDataAnnotations()
.AddFormatterMappings();
//For further Swagger registration information:
//https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger.
services.AddSwaggerGen(swagger =>
{
swagger.DescribeAllParametersInCamelCase();
//In the Swagger document this corresponds as follows:
//http://localhost:4003/{SwaggerRoot}/{SwaggerDocumentationBasePath}/swagger.json
swagger.SwaggerDoc(SwaggerDocumentationBasePath, new OpenApiInfo
{
Title = "OneBoxDeployment APIs",
//Note that this is information subject to change and with legal
//consequences. In the future there needs to be a formal way to handle
//these.
//Also, for choosing licenses:
//- https://go.developer.ebay.com/api-license-agreement
//- https://www.zendesk.com/company/customers-partners/application-developer-api-license-agreement/
Contact = new OpenApiContact
{
Email = "contact@contact.com",
Name = "OneBoxDeployment",
Url = new Uri("https://contactinformationtobedefined.com")
},
Description = "OneBoxDeployment application programming interface (API) descriptions.",
License = new OpenApiLicense
{
Name = "The license name to be defined.",
Url = new Uri("https://contactinformationtobedefined.com")
},
TermsOfService = new Uri("https://choosealicense.com/licenses/")
});
//The name of the comments file (see project properties). This is set automatically to the name
//of the project unless explicitly changed.
string commentsFilename = $"{Assembly.GetAssembly(typeof(Startup)).GetName().Name}.xml";
string fullCommentsFilePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath,
commentsFilename);
swagger.IncludeXmlComments(fullCommentsFilePath);
});
services.AddHttpContextAccessor();
services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>()?.HttpContext?.User);
//A trick since the cluster configuration value from the in-memory provider is bound differently
//to the JSON one. Here in-memory one takes presedence to the file one since in that case the values
//come from the tests. Should be a flag or better yet, override properly...
ClusterConfig clusterConfig = null;
var clusterConfigValue = Configuration.GetSection(nameof(ClusterConfig));
if(clusterConfigValue?.Value != null)
{
clusterConfig = JsonConvert.DeserializeObject<ClusterConfig>(clusterConfigValue.Value, new IPAddressConverter());
}
else
{
clusterConfig = Configuration.GetSection(nameof(ClusterConfig)).GetValid<ClusterConfig>();
}
services.AddSingleton(Environment);
services.AddSingleton(Configuration);
var clientBuilder = new ClientBuilder()
.ConfigureLogging(logging => logging.AddConsole())
.UsePerfCounterEnvironmentStatistics()
.Configure<ClusterOptions>(options =>
{
options.ClusterId = clusterConfig.ClusterOptions.ClusterId;
options.ServiceId = clusterConfig.ClusterOptions.ServiceId;
})
.UseAdoNetClustering(options =>
{
options.Invariant = clusterConfig.ConnectionConfig.AdoNetConstant;
options.ConnectionString = clusterConfig.ConnectionConfig.ConnectionString;
})
.Configure<ClientMessagingOptions>(options => options.ResponseTimeout = TimeSpan.FromSeconds(30))
.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ITestStateGrain).Assembly).WithReferences());
var client = clientBuilder.Build();
client.Connect(async ex =>
{
await Task.Delay(TimeSpan.FromMilliseconds(300)).ConfigureAwait(false);
return true;
}).GetAwaiter().GetResult();
services.AddSingleton(client);
/*services.AddStartupTask<ClusterClientStartupTask>();
services
.AddHealthChecks()
.AddCheck<StartupTasksHealthCheck>("Startup tasks");
*/
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">The application to configure.</param>
/// <param name="env">The environment information to use in configuration phase.</param>
/// <param name="applicationLifetime"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
{
if(!env.IsProduction())
{
app.UseDeveloperExceptionPage();
}
//app.UseHealthChecks("/healthz");
//app.UseMiddleware<StartupTasksMiddleware>();
applicationLifetime.ApplicationStopping.Register(() => { });
//This ensures (or improves chances) to flush log buffers before (a graceful) shutdown.
//It appears there isn't other way (e.g. in Program) than taking a reference to the global
//static Serilog instance.
applicationLifetime.ApplicationStopped.Register(Log.CloseAndFlush);
//Security headers will always be added and by default the disallow everything.
//The trimming is a robustness measure to make sure the URL has one trailing slash.
//The listening address is needed for security headers. This is the public
//API address.
var appsettingsSection = Configuration.GetSection("AppSettings");
var listeningAddress = appsettingsSection["OneBoxDeploymentApiUrl"];
listeningAddress = (listeningAddress ?? app.ServerFeatures.Get<IServerAddressesFeature>().Addresses.FirstOrDefault()).EnsureTrailing('/');
//Note: the constructor checks ConfigurationKeys forbidden in production are not found.
if(!env.IsProduction())
{
//Creates a route to specifically throw and unhandled exception. This route is most likely injected only in testing.
var alwaysFaultyRoute = Configuration.GetValue<string>(ConfigurationKeys.AlwaysFaultyRoute, null);
if(alwaysFaultyRoute != null)
{
app.Map(alwaysFaultyRoute, routeBuilder => routeBuilder.Run(context => throw new Exception($"Fault injected route for testing ({context.Request.PathBase}/{context.Request.PathBase}).")));
}
}
Logger.LogInformation(Events.SwaggerDocumentation.Id, Events.SwaggerDocumentation.FormatString, listeningAddress + SwaggerRoot + "/");
var defaultSecurityPolicies = new HeaderPolicyCollection()
.AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365)
.RemoveServerHeader()
.AddFrameOptionsDeny();
app.UseSecurityHeaders(defaultSecurityPolicies);
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/" + SwaggerRoot), swaggerBranch =>
{
//See configuration at https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders.
const string GoogleStyles = "https://fonts.googleapis.com";
const string GoogleFontsUrl = "https://fonts.gstatic.com";
var clientUrl = Path.Combine(listeningAddress, SwaggerRoot).EnsureTrailing('/');
//Additional information for the many Feature-Policy none definitions:
//https://github.com/w3c/webappsec-feature-policy/issues/189#issuecomment-452401661.
swaggerBranch.UseSecurityHeaders(new HeaderPolicyCollection().AddFeaturePolicy(builder =>
{
builder.AddAccelerometer().None();
builder.AddAmbientLightSensor().None();
builder.AddAutoplay().None();
builder.AddCamera().None();
builder.AddEncryptedMedia().None();
builder.AddFullscreen().None();
builder.AddGeolocation().None();
builder.AddGyroscope().None();
builder.AddMagnetometer().None();
builder.AddMicrophone().None();
builder.AddMidi().None();
builder.AddPayment().None();
builder.AddPictureInPicture().None();
builder.AddSpeaker().None();
builder.AddSyncXHR().None();
builder.AddUsb().None();
builder.AddVR().None();
})
.AddXssProtectionBlock()
.AddContentTypeOptionsNoSniff()
.AddReferrerPolicyStrictOriginWhenCrossOrigin()
.AddContentSecurityPolicy(builder =>
{
builder.AddReportUri().To("/cspreport");
builder.AddBlockAllMixedContent();
builder.AddConnectSrc().Self();
builder.AddStyleSrc().Self().UnsafeInline().Sources.Add(GoogleStyles);
builder.AddFontSrc().Self().Sources.Add(GoogleFontsUrl);
builder.AddImgSrc().Self().Sources.Add("data:");
builder.AddScriptSrc().Self().UnsafeInline();
builder.AddObjectSrc().None();
builder.AddFormAction().Self();
builder.AddFrameAncestors().None().Sources.Add(clientUrl);
}, asReportOnly: false));
});
//For further Swagger related information, see at
//https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger.
app.UseSwagger();
app.UseSwagger(swagger => swagger.RouteTemplate = $"{SwaggerRoot}/{{documentName}}/swagger.json");
if(Configuration["HideSwaggerUi"]?.Equals("true") != true)
{
app.UseSwaggerUI(swaggerSetup =>
{
swaggerSetup.SwaggerEndpoint($"/{SwaggerRoot}/{SwaggerDocumentationBasePath}/swagger.json", SwaggerDocumentationBasePath);
swaggerSetup.RoutePrefix = SwaggerRoot;
swaggerSetup.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream($"{Assembly.GetAssembly(typeof(Startup)).GetName().Name}.wwwroot.swagger.index.html");
});
}
app.UseCors("CorsPolicy");
app.UseProblemDetails();
app.UseStaticFiles();
app.UseRouting();
//app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
private void ConfigureProblemDetails(ProblemDetailsOptions options)
{
// This is the default behavior; only include exception details in a development environment.
options.IncludeExceptionDetails = ctx => Environment.IsDevelopment();
options.OnBeforeWriteDetails = (ctx, details) =>
{
var identifier = Guid.NewGuid().ToString();
ctx.TraceIdentifier = identifier;
details.Instance = $"urn:oneboxdeployment:error:{identifier}";
};
// This will map NotImplementedException to the 501 Not Implemented status code.
options.Map<NotImplementedException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status501NotImplemented));
// This will map HttpRequestException to the 503 Service Unavailable status code.
options.Map<HttpRequestException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status503ServiceUnavailable));
options.Map<ValidationException>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status400BadRequest)
{
Title = "Hep!"
});
// Because exceptions are handled polymorphically, this will act as a "catch all" mapping, which is why it's added last.
// If an exception other than NotImplementedException and HttpRequestException is thrown, this will handle it.
options.Map<Exception>(ex => new ExceptionProblemDetails(ex, StatusCodes.Status500InternalServerError));
}
}
}