-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
169 lines (145 loc) · 6.27 KB
/
Program.cs
File metadata and controls
169 lines (145 loc) · 6.27 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
// Copyright (c) 2025 Duplicati Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using ConsoleCommon;
using DuplicatiIngress;
using MassTransit;
using MassTransit.SqlTransport.PostgreSql;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using RobotsTxt;
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Support the untracked local environment variables file for development
ConfigureDevSetup.ConfigureForDevelopment(builder);
var envConfig = builder.Configuration.GetRequiredSection("Environment").Get<EnvironmentConfig>()!;
builder.Services.AddSingleton(envConfig);
var serilogConfig = builder.Configuration.GetSection("Serilog").Get<SerilogConfig>();
var extras = new LoggingExtras() { IsProd = envConfig.IsProd, Hostname = envConfig.Hostname, MachineName = envConfig.MachineName };
builder.AddCommonLogging(serilogConfig, extras);
var securityconfig = builder.Configuration.GetSection("Security").Get<SimpleSecurityOptions>();
builder.AddSimpleSecurityFilter(securityconfig, msg => Log.Warning(msg));
// Load encryption keys
var encryptionKeys = builder.Configuration.GetSection("EncryptionKey")
.GetChildren()
.Select(c => new { KeyId = c.Key, KeyValue = c.Value })
.Where(c => !string.IsNullOrWhiteSpace(c.KeyId) && !string.IsNullOrWhiteSpace(c.KeyValue))
.ToDictionary(c => c.KeyId, c => c.KeyValue!, StringComparer.OrdinalIgnoreCase);
if (encryptionKeys.Count == 0)
throw new InvalidOperationException("No encryption keys configured");
builder.Services.AddSingleton(new EncryptionKeyConfig(encryptionKeys));
var jwt = builder.Configuration.GetRequiredSection("Ingress:JWT").Get<JWTConfig>()!;
builder.Services.AddSingleton(jwt);
if (!envConfig.IsProd)
{
if (envConfig.Storage.StartsWith("file://"))
{
var path = envConfig.Storage.Substring("file://".Length).Split('?')[0];
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
}
builder.Services.AddSingleton(KVPSButter.KVPSLoader.CreateIKVPS(envConfig.Storage));
var preconfiguredTokenConfig = await PreconfiguredTokens.LoadFromStorage(builder.Configuration.GetSection("PreconfiguredTokens").Get<TokenRuleOverrideConfig>());
builder.Services
.AddTransient<IngressHandler>()
.AddSingleton(preconfiguredTokenConfig)
.AddSingleton<IPreconfiguredTokens, PreconfiguredTokens>()
.AddTransient<IJWTValidator, JWTValidator>()
.AddSingleton<IEncryptionKeyProvider, EncryptionKeyProvider>()
.AddTransient<IPublishIngressMessage, PublishIngressMessage>()
.AddStaticRobotsTxt(services => services.DenyAll());
builder.Services.AddMassTransit(x =>
{
x.AddConsumer<FailedUploadConsumer>(configure: context => { context.UseMessageRetry(r => r.Interval(10, 1000)); });
var messagingConfig = builder.Configuration.GetSection("Messaging").Get<MessagingConfig>();
if (builder.Environment.IsDevelopment() && string.IsNullOrWhiteSpace(messagingConfig?.ConnectionString))
{
x.UsingInMemory((context, cfg) => cfg.ConfigureEndpoints(context));
}
else
{
if (string.IsNullOrWhiteSpace(messagingConfig?.ConnectionString))
throw new InvalidOperationException("Messaging configuration is missing");
x.UsingPostgres((context, cfg) =>
{
cfg.Host(new PostgresSqlHostSettings(messagingConfig.ConnectionString));
cfg.ConfigureEndpoints(context);
});
}
});
var app = builder.Build();
app.UseCommonLogging();
app.UseSimpleSecurityFilter(securityconfig);
app.MapPost("/backupreports/{token}",
async ([FromServices] IngressHandler handler, [FromRoute] string token, CancellationToken ct) =>
{
await handler.MapPost(token, ct);
});
app.MapGet("/health", () => "OK");
app.MapGet("/", ctx =>
{
if (string.IsNullOrWhiteSpace(envConfig.RedirectUrl))
ctx.Response.StatusCode = 404;
else
ctx.Response.Redirect(envConfig.RedirectUrl);
return Task.CompletedTask;
});
app.UseHttpsRedirection();
app.UseRobotsTxt();
app.UseExceptionHandler(new ExceptionHandlerOptions
{
ExceptionHandler = context =>
{
var ex = context.Features.Get<IExceptionHandlerFeature>()?.Error;
if (ex is UserReportedException ure)
{
context.Response.StatusCode = ure.StatusCode;
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync(ure.Message);
}
else if (ex is SecurityTokenValidationException)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync("Invalid token");
}
else
{
context.Response.StatusCode = 500;
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync("An error occurred while processing your request.");
}
}
});
try
{
Log.Information("Starting application...");
app.Run();
}
catch (Exception ex)
{
Log.Error(ex, "Crashed while running application");
}
finally
{
Log.Information("Terminating application...");
Log.CloseAndFlush();
}