Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Lockout Alerting #723

Merged
merged 3 commits into from
Dec 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion BLAZAM/BLAZAM.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<ServerGarbageCollection>false</ServerGarbageCollection>
<AssemblyVersion>1.2.4</AssemblyVersion>
<Version>2024.12.27.1637</Version>
<Version>2024.12.29.1826</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<RootNamespace>BLAZAM</RootNamespace>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
Expand Down
281 changes: 183 additions & 98 deletions BLAZAM/ProgramHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
using System.Reflection;
using System.Text;
using Polly.Contrib.WaitAndRetry;
using BLAZAM.Services.Attributes;

namespace BLAZAM.Server
{
Expand Down Expand Up @@ -176,12 +177,12 @@ public static WebApplicationBuilder InjectServices(this WebApplicationBuilder bu
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true, // Important: Validate the signing key
IssuerSigningKey = new SymmetricSecurityKey (Encryption.Instance.Key),
IssuerSigningKey = new SymmetricSecurityKey(Encryption.Instance.Key),
ValidateIssuer = false,
ValidateAudience = false,
ValidateActor = false,
ValidateLifetime = true,

};
options.Events = new JwtAuthenticationEventsHandler(
builder.Services.BuildServiceProvider().GetRequiredService<IHttpContextAccessor>(),
Expand Down Expand Up @@ -243,7 +244,7 @@ public static WebApplicationBuilder InjectServices(this WebApplicationBuilder bu
ServerCertificateCustomValidationCallback = (m, c, ch, e) => true
});


//Provide a way to get the current HTTP userPrincipal as a service
builder.Services.AddHttpContextAccessor();

Expand All @@ -267,9 +268,6 @@ public static WebApplicationBuilder InjectServices(this WebApplicationBuilder bu
//Provide a PermissionHandler as a service
builder.Services.AddSingleton<PermissionApplicator>();

builder.Services.AddSingleton<UserSeederService>();

builder.Services.AddSingleton<IApplicationNewsService, ApplicationNewsService>();

//Provide a AuditLogger as a service
builder.Services.AddScoped<AuditLogger>();
Expand Down Expand Up @@ -316,7 +314,7 @@ public static WebApplicationBuilder InjectServices(this WebApplicationBuilder bu
//Provide notification publishing as a service
builder.Services.AddSingleton<INotificationPublisher, NotificationPublisher>();


builder.InjectBackgroundServices();

builder.Services.AddSessionServices();

Expand Down Expand Up @@ -352,134 +350,221 @@ public static WebApplicationBuilder InjectServices(this WebApplicationBuilder bu

builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Blazam API",
Version = "v1",
Description = "The official Blazam API documentation." +
"<br/>Authorization is required for API access." +
"<br/>The \"Authorization\" header value must be \"Bearer {token}\"",
License = new OpenApiLicense() { Name = "MIT License", Url = new Uri("https://github.com/Blazam-App/BLAZAM/blob/v1-Dev/LICENSE") },
Contact = new()
c.SwaggerDoc("v1", new OpenApiInfo
{
Email = "[email protected]",
Name = "Blazam Support",
Url = new("https://blazam.org/support")
},
TermsOfService = new Uri("https://blazam.org/tos")
});
Title = "Blazam API",
Version = "v1",
Description = "The official Blazam API documentation." +
"<br/>Authorization is required for API access." +
"<br/>The \"Authorization\" header value must be \"Bearer {token}\"",
License = new OpenApiLicense() { Name = "MIT License", Url = new Uri("https://github.com/Blazam-App/BLAZAM/blob/v1-Dev/LICENSE") },
Contact = new()
{
Email = "[email protected]",
Name = "Blazam Support",
Url = new("https://blazam.org/support")
},
TermsOfService = new Uri("https://blazam.org/tos")
});

// Add descriptions using XML comments
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
// Add descriptions using XML comments
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));

// Configure Swagger to use JWT Bearer authorization
var jwtSecurityScheme = new OpenApiSecurityScheme
{
Description = "Enter only the token supplied by Blazam",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = JwtBearerDefaults.AuthenticationScheme,
BearerFormat = "JWT",
Reference = new OpenApiReference
// Configure Swagger to use JWT Bearer authorization
var jwtSecurityScheme = new OpenApiSecurityScheme
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};
Description = "Enter only the token supplied by Blazam",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = JwtBearerDefaults.AuthenticationScheme,
BearerFormat = "JWT",
Reference = new OpenApiReference
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};

c.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
{ jwtSecurityScheme,Array.Empty<string>() }
});
});
});

builder.Host.UseWindowsService();



return builder;
}
private static readonly object _lock = new object();
public static WebApplicationBuilder InjectBackgroundServices(this WebApplicationBuilder builder)
{

public static void PreRun(this WebApplication application)
{
//Setup Seq logging if allowed by admin
try
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
Parallel.ForEach(assemblies, assembly =>
{
var types = assembly.GetTypes()
.Where(t => t.IsClass && !t.IsAbstract
&& t.GetCustomAttribute<AutoStartBackgroundService>() != null);

foreach (var type in types)
{
var interfaceType = type.GetInterfaces()
.FirstOrDefault(i => i.GetCustomAttribute<AutoStartBackgroundService>() == null
&& i.Name != "IDisposable");

if (interfaceType != null)
{
lock (_lock)
{
builder.Services.AddSingleton(interfaceType, type);
}
}
else
{
lock (_lock)
{
builder.Services.AddSingleton(type);
}
}
}
});
return builder;
}

/// <summary>
/// Auto-starts <see cref="AutoStartBackgroundService"/> adorned classes and
/// sets the Seq logging opt-out, and other singleton services
/// </summary>
/// <param name="application"></param>
public static void PreRun(this WebApplication application)
{
using var context = Program.AppInstance.Services.GetRequiredService<IAppDatabaseFactory>().CreateDbContext();
if (context != null && context.AppSettings.FirstOrDefault()?.SendLogsToDeveloper != null)
try
{
Loggers.SendToSeqServer = context.AppSettings.FirstOrDefault().SendLogsToDeveloper;
var assemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (var assembly in assemblies)
{
var types = assembly.GetTypes()
.Where(t => t.IsClass && !t.IsAbstract
&& t.GetCustomAttribute<AutoStartBackgroundService>() != null);

foreach (var type in types)
{
try
{
var interfaceType = type.GetInterfaces()
.FirstOrDefault(i => i.GetCustomAttribute<AutoStartBackgroundService>() == null
&& i.Name != "IDisposable");
BackgroundServiceBase? service;

if (interfaceType != null)
{
service = application.Services.GetRequiredService(interfaceType) as BackgroundServiceBase;

}
else
{
service = application.Services.GetRequiredService(type) as BackgroundServiceBase;

}


var data = type.GetCustomAttribute<AutoStartBackgroundService>();
service?.Start(data?.Immediate==true);
}
catch (Exception ex)
{
Loggers.SystemLogger.Error("Critical error starting up background service! {Error}", ex);

}
}
}
}
catch (Exception ex)
{
Loggers.SystemLogger.Error("Critical error getting loaded assemblies! {Error}", ex);

}
catch (Exception ex)
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}
PreloadServices();
}
//Setup Seq logging if allowed by admin
try
{
using var context = Program.AppInstance.Services.GetRequiredService<IAppDatabaseFactory>().CreateDbContext();
if (context != null && context.AppSettings.FirstOrDefault()?.SendLogsToDeveloper != null)
{
Loggers.SendToSeqServer = context.AppSettings.FirstOrDefault().SendLogsToDeveloper;

}
static IAsyncPolicy<HttpResponseMessage> GetWebhookRetryPolicy()
{
var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(1), retryCount: 5);
}

return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.WaitAndRetryAsync(delay);
}
private static void PreloadServices()
{
try
{
var context = Program.AppInstance.Services.GetRequiredService<NotificationGenerationService>();
}
catch (Exception ex)
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}
try
{
if (ApplicationInfo.installationCompleted)
}
catch (Exception ex)
{
var context = Program.AppInstance.Services.GetRequiredService<UserSeederService>();
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}
PreloadServices();

}
catch (Exception ex)
static IAsyncPolicy<HttpResponseMessage> GetWebhookRetryPolicy()
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(1), retryCount: 5);

return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.WaitAndRetryAsync(delay);
}
try
private static void PreloadServices()
{
if (ApplicationInfo.installationCompleted)
try
{
var context = Program.AppInstance.Services.GetRequiredService<UpdateService>();
context.Initialize();
var context = Program.AppInstance.Services.GetRequiredService<NotificationGenerationService>();
}
catch (Exception ex)
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}
try
{
if (ApplicationInfo.installationCompleted)
{
var context = Program.AppInstance.Services.GetRequiredService<UserSeederService>();
}

}
catch (Exception ex)
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}
try
{
if (ApplicationInfo.installationCompleted)
}
catch (Exception ex)
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}
try
{
var context = Program.AppInstance.Services.GetRequiredService<WebHookPublisher>();
if (ApplicationInfo.installationCompleted)
{
var context = Program.AppInstance.Services.GetRequiredService<UpdateService>();
context.Initialize();
}

}
catch (Exception ex)
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}
try
{
if (ApplicationInfo.installationCompleted)
{
var context = Program.AppInstance.Services.GetRequiredService<WebHookPublisher>();

}
catch (Exception ex)
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}
}

}
catch (Exception ex)
{
Loggers.SystemLogger.Error(ex.Message + " {@Error}", ex);
}

}
}
}
}
3 changes: 3 additions & 0 deletions BLAZAMDatabase/Context/DatabaseContextBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ public DatabaseContextBase(DbContextOptions options) : base(options)

}

//Data tables
public virtual DbSet<GenericSidList> LockedOutUsers { get; set; }

//App Settings
public virtual DbSet<AppSettings> AppSettings { get; set; }
public virtual DbSet<ADSettings> ActiveDirectorySettings { get; set; }
Expand Down
1 change: 1 addition & 0 deletions BLAZAMDatabase/Context/IDatabaseContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ public interface IDatabaseContext : IEFCoreDbContext
DbSet<ApiToken> ApiTokens { get; set; }
DbSet<WebHookSubscription> WebHookSubscriptions { get; set; }
DbSet<WebHookAttempt> WebHookAttempts { get; set; }
DbSet<GenericSidList> LockedOutUsers { get; set; }

void Export(string directory);
}
Expand Down
Loading
Loading