From dd287987e0377aa50fbd7ee9d1dc8c345548df1c Mon Sep 17 00:00:00 2001 From: Ccjcarkbla Date: Mon, 9 Mar 2026 12:53:15 -0400 Subject: [PATCH] Changes --- .dockerignore | 15 ++ .../Configuration/AdminGroupSources.cs | 7 + .../Configuration/AuthEnvironment.cs | 1 + .../Core/AdminRoleClaimsTransformation.cs | 23 ++- Data/AppDbContext.cs | 10 ++ Data/Entities/AdminGroupEntity.cs | 8 + Dockerfile | 9 ++ FutureSecrets.example.json | 1 + Pages/Admin/Groups/Index.cshtml | 82 +++++++--- Pages/Admin/Groups/Index.cshtml.cs | 140 +++++++++++++++--- Pages/Admin/Templates/Edit.cshtml | 110 ++++++++++++++ Pages/Admin/Templates/Edit.cshtml.cs | 84 ++++++++++- Pages/Admin/Templates/Index.cshtml | 15 ++ Pages/Admin/Templates/Index.cshtml.cs | 29 +++- Pages/Error.cshtml | 2 +- Pages/Errors/Index.cshtml.cs | 6 +- Pages/Errors/Render.cshtml | 2 +- Program.cs | 31 ++-- .../FutureSecrets.example.json | 1 + k8s/README.md | 9 +- k8s/configmap.yaml | 26 ++++ k8s/deployment.yaml | 18 ++- k8s/secret.example.yaml | 17 +-- maintenance.csproj | 1 + 24 files changed, 550 insertions(+), 97 deletions(-) create mode 100644 .dockerignore create mode 100644 Authentication/Configuration/AdminGroupSources.cs create mode 100644 Data/Entities/AdminGroupEntity.cs create mode 100644 Dockerfile create mode 100644 k8s/configmap.yaml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..1d52357 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,15 @@ +**/.git +**/.vs +**/.vscode +**/bin +**/obj +# Include CI publish output folder for runtime-only image packaging +!artifacts_tmp_build/ +!artifacts_tmp_build/** + +FutureSecrets.json +FutureSecrets.example.json +appsettings.Development.json + +Dockerfile* +k8s/ diff --git a/Authentication/Configuration/AdminGroupSources.cs b/Authentication/Configuration/AdminGroupSources.cs new file mode 100644 index 0000000..48f92b4 --- /dev/null +++ b/Authentication/Configuration/AdminGroupSources.cs @@ -0,0 +1,7 @@ +namespace maintenance.Authentication.Configuration; + +public static class AdminGroupSources +{ + public const string Max = "MAX"; + public const string Ad = "AD"; +} diff --git a/Authentication/Configuration/AuthEnvironment.cs b/Authentication/Configuration/AuthEnvironment.cs index a989e7f..f9d5c6e 100644 --- a/Authentication/Configuration/AuthEnvironment.cs +++ b/Authentication/Configuration/AuthEnvironment.cs @@ -4,6 +4,7 @@ public static class AuthEnvironment { public const string AuthMode = "AUTH_MODE"; public const string AdminGroups = "AUTH_ADMIN_GROUPS"; + public const string AdminGroupSource = "AUTH_GROUP_SOURCE"; public const string AdfsMetadataAddress = "ADFS_METADATA_ADDRESS"; public const string AdfsRealm = "ADFS_WTRELM"; diff --git a/Authentication/Core/AdminRoleClaimsTransformation.cs b/Authentication/Core/AdminRoleClaimsTransformation.cs index f45a422..46711b7 100644 --- a/Authentication/Core/AdminRoleClaimsTransformation.cs +++ b/Authentication/Core/AdminRoleClaimsTransformation.cs @@ -44,11 +44,24 @@ public sealed class AdminRoleClaimsTransformation : IClaimsTransformation var configuredGroups = (_configuration[AuthEnvironment.AdminGroups] ?? string.Empty) .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - var dbGroups = await _dbContext.AuthorizationGroups - .AsNoTracking() - .Where(g => g.Active && g.Role == "admin") - .Select(g => g.GroupClaimValue) - .ToListAsync(); + var groupSource = _configuration[AuthEnvironment.AdminGroupSource] ?? AdminGroupSources.Max; + List dbGroups; + + if (groupSource.Equals(AdminGroupSources.Ad, StringComparison.OrdinalIgnoreCase)) + { + dbGroups = await _dbContext.AuthorizationGroups + .AsNoTracking() + .Where(g => g.Active && g.Role == "admin") + .Select(g => g.GroupClaimValue) + .ToListAsync(); + } + else + { + dbGroups = await _dbContext.AdminGroups + .AsNoTracking() + .Select(g => g.GroupClaimValue) + .ToListAsync(); + } var effectiveGroups = configuredGroups .Concat(dbGroups) diff --git a/Data/AppDbContext.cs b/Data/AppDbContext.cs index 392e16c..45fe972 100644 --- a/Data/AppDbContext.cs +++ b/Data/AppDbContext.cs @@ -13,6 +13,7 @@ public sealed class AppDbContext : DbContext public DbSet AppMappings => Set(); public DbSet FeatureFlags => Set(); public DbSet MaintenanceWindows => Set(); + public DbSet AdminGroups => Set(); public DbSet AuthorizationGroups => Set(); public DbSet PermissionRules => Set(); public DbSet AuditRecords => Set(); @@ -57,6 +58,15 @@ public sealed class AppDbContext : DbContext e.HasIndex(x => new { x.AppId, x.StartTimeEastern, x.EndTimeEastern }); }); + modelBuilder.Entity(e => + { + e.ToTable("AdminGroup"); + e.HasKey(x => x.Id); + e.Property(x => x.GroupClaimValue).HasMaxLength(256).IsRequired(); + e.Property(x => x.NormalizedGroupClaimValue).HasMaxLength(256).IsRequired(); + e.HasIndex(x => x.NormalizedGroupClaimValue).IsUnique(); + }); + modelBuilder.Entity(e => { e.ToTable("AuthorizationGroup"); diff --git a/Data/Entities/AdminGroupEntity.cs b/Data/Entities/AdminGroupEntity.cs new file mode 100644 index 0000000..59ae14b --- /dev/null +++ b/Data/Entities/AdminGroupEntity.cs @@ -0,0 +1,8 @@ +namespace maintenance.Data.Entities; + +public sealed class AdminGroupEntity +{ + public Guid Id { get; set; } + public string GroupClaimValue { get; set; } = string.Empty; + public string NormalizedGroupClaimValue { get; set; } = string.Empty; +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..28b03d8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,9 @@ +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +WORKDIR /app + +COPY artifacts_tmp_build/ ./ + +ENV ASPNETCORE_URLS=http://+:8080 +EXPOSE 8080 + +ENTRYPOINT ["dotnet", "maintenance.dll"] diff --git a/FutureSecrets.example.json b/FutureSecrets.example.json index d6171ea..1754bf4 100644 --- a/FutureSecrets.example.json +++ b/FutureSecrets.example.json @@ -1,5 +1,6 @@ { "AUTH_MODE": "WSFED", + "AUTH_GROUP_SOURCE": "MAX", "AUTH_ADMIN_GROUPS": "maintenance-Admins;maintenance-SuperAdmins", "ADFS_METADATA_ADDRESS": "https://adfs.example.com/federationmetadata/2007-06/federationmetadata.xml", "ADFS_WTRELM": "URN:WSFEDAPP", diff --git a/Pages/Admin/Groups/Index.cshtml b/Pages/Admin/Groups/Index.cshtml index 64134a7..7ab0093 100644 --- a/Pages/Admin/Groups/Index.cshtml +++ b/Pages/Admin/Groups/Index.cshtml @@ -5,12 +5,28 @@ }

Admin Groups

-

Manage group claim values that grant admin access.

+

+ @if (Model.IsAdSource) + { + Source: AD lookup + AuthorizationGroup records. + } + else + { + Source: MAX app database records. + } +

- + @if (Model.IsAdSource) + { + + } + else + { + + }
@@ -18,7 +34,7 @@
-@if (Model.LookupResults.Count > 0) +@if (Model.IsAdSource && Model.LookupResults.Count > 0) {
Lookup Results
@@ -63,29 +79,53 @@ Group Claim Value - Role - Active + @if (Model.IsAdSource) + { + Role + Active + } - @foreach (var g in Model.Groups) + @if (Model.IsAdSource) { - - @g.GroupClaimValue - @g.Role - @g.Active - -
- - -
-
- - -
- - + @foreach (var g in Model.AdGroups) + { + + @g.GroupClaimValue + @g.Role + @g.Active + +
+ + + +
+
+ + + +
+ + + } + } + else + { + @foreach (var g in Model.Groups) + { + + @g.GroupClaimValue + +
+ + + +
+ + + } } diff --git a/Pages/Admin/Groups/Index.cshtml.cs b/Pages/Admin/Groups/Index.cshtml.cs index 44b9439..3b08929 100644 --- a/Pages/Admin/Groups/Index.cshtml.cs +++ b/Pages/Admin/Groups/Index.cshtml.cs @@ -1,5 +1,6 @@ using maintenance.Data; using maintenance.Data.Entities; +using maintenance.Authentication.Configuration; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; @@ -10,13 +11,16 @@ namespace maintenance.Pages.Admin.Groups; [Authorize(Policy = "AdminOnly")] public sealed class IndexModel : PageModel { + private const string AdminRole = "admin"; private readonly AppDbContext _dbContext; - private readonly GroupLookupDbContext _groupLookupDbContext; + private readonly IConfiguration _configuration; + private readonly IServiceProvider _serviceProvider; - public IndexModel(AppDbContext dbContext, GroupLookupDbContext groupLookupDbContext) + public IndexModel(AppDbContext dbContext, IConfiguration configuration, IServiceProvider serviceProvider) { _dbContext = dbContext; - _groupLookupDbContext = groupLookupDbContext; + _configuration = configuration; + _serviceProvider = serviceProvider; } [BindProperty] @@ -25,44 +29,78 @@ public sealed class IndexModel : PageModel [BindProperty(SupportsGet = true)] public string GroupSearch { get; set; } = string.Empty; - public IReadOnlyList Groups { get; private set; } = []; + public bool IsAdSource { get; private set; } + public IReadOnlyList Groups { get; private set; } = []; + public IReadOnlyList AdGroups { get; private set; } = []; public IReadOnlyList LookupResults { get; private set; } = []; public async Task OnGetAsync() { + IsAdSource = ResolveIsAdSource(); await LoadAsync(); - await SearchAsync(); + if (IsAdSource) + { + await SearchAdLookupAsync(); + } } public async Task OnPostAddAsync() { + IsAdSource = ResolveIsAdSource(); var claim = NewGroupClaimValue.Trim(); if (string.IsNullOrWhiteSpace(claim)) { await LoadAsync(); - await SearchAsync(); + if (IsAdSource) + { + await SearchAdLookupAsync(); + } return Page(); } - var exists = await _dbContext.AuthorizationGroups - .AnyAsync(x => x.GroupClaimValue == claim, HttpContext.RequestAborted); - if (!exists) + if (IsAdSource) { - _dbContext.AuthorizationGroups.Add(new AuthorizationGroupEntity + var existsAd = await _dbContext.AuthorizationGroups + .AnyAsync(x => x.GroupClaimValue == claim, HttpContext.RequestAborted); + if (!existsAd) + { + _dbContext.AuthorizationGroups.Add(new AuthorizationGroupEntity + { + Id = Guid.NewGuid(), + GroupClaimValue = claim, + Role = AdminRole, + Active = true + }); + await _dbContext.SaveChangesAsync(HttpContext.RequestAborted); + } + + return RedirectToPage(new { GroupSearch }); + } + + var normalizedClaim = NormalizeGroup(claim); + var existsMax = await _dbContext.AdminGroups + .AnyAsync(x => x.NormalizedGroupClaimValue == normalizedClaim, HttpContext.RequestAborted); + if (!existsMax) + { + _dbContext.AdminGroups.Add(new AdminGroupEntity { Id = Guid.NewGuid(), GroupClaimValue = claim, - Role = "admin", - Active = true + NormalizedGroupClaimValue = normalizedClaim }); await _dbContext.SaveChangesAsync(HttpContext.RequestAborted); } - return RedirectToPage(); + return RedirectToPage(new { GroupSearch }); } public async Task OnPostAddFromLookupAsync(string groupName) { + if (!ResolveIsAdSource()) + { + return RedirectToPage(new { GroupSearch }); + } + if (string.IsNullOrWhiteSpace(groupName)) { return RedirectToPage(new { GroupSearch }); @@ -77,7 +115,7 @@ public sealed class IndexModel : PageModel { Id = Guid.NewGuid(), GroupClaimValue = claim, - Role = "admin", + Role = AdminRole, Active = true }); await _dbContext.SaveChangesAsync(HttpContext.RequestAborted); @@ -88,36 +126,74 @@ public sealed class IndexModel : PageModel public async Task OnPostToggleAsync(Guid id) { + if (!ResolveIsAdSource()) + { + return RedirectToPage(new { GroupSearch }); + } + var entity = await _dbContext.AuthorizationGroups.FirstOrDefaultAsync(x => x.Id == id, HttpContext.RequestAborted); if (entity is not null) { entity.Active = !entity.Active; await _dbContext.SaveChangesAsync(HttpContext.RequestAborted); } - return RedirectToPage(); + + return RedirectToPage(new { GroupSearch }); } public async Task OnPostDeleteAsync(Guid id) { - var entity = await _dbContext.AuthorizationGroups.FirstOrDefaultAsync(x => x.Id == id, HttpContext.RequestAborted); + if (ResolveIsAdSource()) + { + var adEntity = await _dbContext.AuthorizationGroups.FirstOrDefaultAsync(x => x.Id == id, HttpContext.RequestAborted); + if (adEntity is not null) + { + _dbContext.AuthorizationGroups.Remove(adEntity); + await _dbContext.SaveChangesAsync(HttpContext.RequestAborted); + } + + return RedirectToPage(new { GroupSearch }); + } + + var entity = await _dbContext.AdminGroups.FirstOrDefaultAsync(x => x.Id == id, HttpContext.RequestAborted); if (entity is not null) { - _dbContext.AuthorizationGroups.Remove(entity); + _dbContext.AdminGroups.Remove(entity); await _dbContext.SaveChangesAsync(HttpContext.RequestAborted); } - return RedirectToPage(); + return RedirectToPage(new { GroupSearch }); } private async Task LoadAsync() { - Groups = await _dbContext.AuthorizationGroups + if (IsAdSource) + { + AdGroups = await _dbContext.AuthorizationGroups + .AsNoTracking() + .OrderByDescending(x => x.Active) + .ThenBy(x => x.GroupClaimValue) + .Take(200) + .ToListAsync(HttpContext.RequestAborted); + return; + } + + var query = _dbContext.AdminGroups .AsNoTracking() - .OrderByDescending(x => x.Active) - .ThenBy(x => x.GroupClaimValue) + .AsQueryable(); + + if (!string.IsNullOrWhiteSpace(GroupSearch)) + { + var term = NormalizeGroup(GroupSearch); + query = query.Where(g => g.NormalizedGroupClaimValue.Contains(term)); + } + + Groups = await query + .OrderBy(g => g.GroupClaimValue) + .Take(200) .ToListAsync(HttpContext.RequestAborted); } - private async Task SearchAsync() + private async Task SearchAdLookupAsync() { if (string.IsNullOrWhiteSpace(GroupSearch)) { @@ -125,8 +201,15 @@ public sealed class IndexModel : PageModel return; } + var groupLookupDbContext = _serviceProvider.GetService(); + if (groupLookupDbContext is null) + { + LookupResults = []; + return; + } + var term = GroupSearch.Trim(); - LookupResults = await _groupLookupDbContext.Groups + LookupResults = await groupLookupDbContext.Groups .AsNoTracking() .Where(g => g.Name.Contains(term)) .OrderBy(g => g.Name) @@ -135,4 +218,15 @@ public sealed class IndexModel : PageModel .Take(25) .ToListAsync(HttpContext.RequestAborted); } + + private bool ResolveIsAdSource() + { + var source = _configuration[AuthEnvironment.AdminGroupSource] ?? AdminGroupSources.Max; + return source.Equals(AdminGroupSources.Ad, StringComparison.OrdinalIgnoreCase); + } + + private static string NormalizeGroup(string value) + { + return value.Trim().ToUpperInvariant(); + } } diff --git a/Pages/Admin/Templates/Edit.cshtml b/Pages/Admin/Templates/Edit.cshtml index c32f960..ad90e09 100644 --- a/Pages/Admin/Templates/Edit.cshtml +++ b/Pages/Admin/Templates/Edit.cshtml @@ -58,10 +58,14 @@
+ +
+ +
@@ -122,3 +126,109 @@ + diff --git a/Pages/Admin/Templates/Edit.cshtml.cs b/Pages/Admin/Templates/Edit.cshtml.cs index 8f00643..4cdafe2 100644 --- a/Pages/Admin/Templates/Edit.cshtml.cs +++ b/Pages/Admin/Templates/Edit.cshtml.cs @@ -22,7 +22,7 @@ public sealed class EditModel : PageModel [BindProperty] public InputModel Input { get; set; } = new(); - public string PreviewUrl { get; private set; } = "/errors/maintenance"; + public string PreviewUrl { get; private set; } = "/maintenance"; public sealed class InputModel { @@ -42,7 +42,9 @@ public sealed class EditModel : PageModel public bool IsEnabled { get; set; } public bool OverrideWindow { get; set; } public int Priority { get; set; } + [Display(Name = "Start ET")] public DateTime? StartUtc { get; set; } + [Display(Name = "End ET")] public DateTime? EndUtc { get; set; } public string? RecurrenceRule { get; set; } @@ -89,8 +91,8 @@ public sealed class EditModel : PageModel IsEnabled = page.IsEnabled, OverrideWindow = page.OverrideWindow, Priority = page.Priority, - StartUtc = page.StartUtc, - EndUtc = page.EndUtc, + StartUtc = ConvertUtcToEasternLocal(page.StartUtc), + EndUtc = ConvertUtcToEasternLocal(page.EndUtc), RecurrenceRule = page.RecurrenceRule, ErrorName = content.ErrorName, ShortDescription = content.ShortDescription, @@ -131,8 +133,27 @@ public sealed class EditModel : PageModel page.IsEnabled = Input.IsEnabled; page.OverrideWindow = Input.OverrideWindow; page.Priority = Input.Priority; - page.StartUtc = Input.StartUtc; - page.EndUtc = Input.EndUtc; + var hasInvalidEasternTime = false; + if (!TryConvertEasternLocalToUtc(Input.StartUtc, out var startUtc)) + { + ModelState.AddModelError("Input.StartUtc", "The selected Start ET is invalid due to daylight saving time."); + hasInvalidEasternTime = true; + } + + if (!TryConvertEasternLocalToUtc(Input.EndUtc, out var endUtc)) + { + ModelState.AddModelError("Input.EndUtc", "The selected End ET is invalid due to daylight saving time."); + hasInvalidEasternTime = true; + } + + if (hasInvalidEasternTime) + { + PreviewUrl = BuildPreviewUrl(Input.PageKind, Input.Key); + return Page(); + } + + page.StartUtc = startUtc; + page.EndUtc = endUtc; page.RecurrenceRule = string.IsNullOrWhiteSpace(Input.RecurrenceRule) ? null : Input.RecurrenceRule.Trim(); page.ContentJson = JsonSerializer.Serialize(new PageContentModel { @@ -182,6 +203,57 @@ public sealed class EditModel : PageModel private static string BuildPreviewUrl(string kind, string key) { - return $"/errors/{kind}?page={Uri.EscapeDataString(key)}"; + return $"/{kind}?page={Uri.EscapeDataString(key)}"; + } + + private static bool TryConvertEasternLocalToUtc(DateTime? easternLocal, out DateTime? utc) + { + utc = null; + + if (!easternLocal.HasValue) + { + return true; + } + + var localValue = DateTime.SpecifyKind(easternLocal.Value, DateTimeKind.Unspecified); + var easternTimeZone = ResolveEasternTimeZone(); + + if (easternTimeZone.IsInvalidTime(localValue)) + { + return false; + } + + utc = TimeZoneInfo.ConvertTimeToUtc(localValue, easternTimeZone); + return true; + } + + private static DateTime? ConvertUtcToEasternLocal(DateTime? utc) + { + if (!utc.HasValue) + { + return null; + } + + var utcValue = utc.Value.Kind switch + { + DateTimeKind.Utc => utc.Value, + DateTimeKind.Local => utc.Value.ToUniversalTime(), + _ => DateTime.SpecifyKind(utc.Value, DateTimeKind.Utc) + }; + + var eastern = TimeZoneInfo.ConvertTimeFromUtc(utcValue, ResolveEasternTimeZone()); + return DateTime.SpecifyKind(eastern, DateTimeKind.Unspecified); + } + + private static TimeZoneInfo ResolveEasternTimeZone() + { + try + { + return TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + } + catch (TimeZoneNotFoundException) + { + return TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); + } } } diff --git a/Pages/Admin/Templates/Index.cshtml b/Pages/Admin/Templates/Index.cshtml index eb8b40b..6fa19c8 100644 --- a/Pages/Admin/Templates/Index.cshtml +++ b/Pages/Admin/Templates/Index.cshtml @@ -7,6 +7,10 @@

Manage Pages

Create and schedule maintenance/error pages while keeping the visual template fixed.

Create page from template

+@if (!string.IsNullOrWhiteSpace(Model.StatusMessage)) +{ + +} @@ -33,6 +37,17 @@ } diff --git a/Pages/Admin/Templates/Index.cshtml.cs b/Pages/Admin/Templates/Index.cshtml.cs index df12717..814008b 100644 --- a/Pages/Admin/Templates/Index.cshtml.cs +++ b/Pages/Admin/Templates/Index.cshtml.cs @@ -1,6 +1,7 @@ using maintenance.Data; using maintenance.Data.Entities; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; @@ -17,6 +18,8 @@ public sealed class IndexModel : PageModel } public IReadOnlyList Templates { get; private set; } = []; + [TempData] + public string? StatusMessage { get; set; } public async Task OnGetAsync() { @@ -28,8 +31,32 @@ public sealed class IndexModel : PageModel .ToListAsync(HttpContext.RequestAborted); } + public async Task OnPostDeleteAsync(Guid id) + { + var page = await _dbContext.ManagedPages + .FirstOrDefaultAsync(t => t.Id == id, HttpContext.RequestAborted); + + if (page is null) + { + StatusMessage = "Page was not found."; + return RedirectToPage(); + } + + if (page.IsDefaultFallback) + { + StatusMessage = "Default template pages cannot be deleted."; + return RedirectToPage(); + } + + _dbContext.ManagedPages.Remove(page); + await _dbContext.SaveChangesAsync(HttpContext.RequestAborted); + + StatusMessage = $"Deleted page '{page.Key}'."; + return RedirectToPage(); + } + public string GetPreviewUrl(ManagedPageEntity page) { - return $"/errors/{page.PageKind}?page={Uri.EscapeDataString(page.Key)}"; + return $"/{page.PageKind}?page={Uri.EscapeDataString(page.Key)}"; } } diff --git a/Pages/Error.cshtml b/Pages/Error.cshtml index 6f92b95..93f7dea 100644 --- a/Pages/Error.cshtml +++ b/Pages/Error.cshtml @@ -1,4 +1,4 @@ -@page +@page "/app-error" @model ErrorModel @{ ViewData["Title"] = "Error"; diff --git a/Pages/Errors/Index.cshtml.cs b/Pages/Errors/Index.cshtml.cs index 7eca2f4..894afe4 100644 --- a/Pages/Errors/Index.cshtml.cs +++ b/Pages/Errors/Index.cshtml.cs @@ -24,15 +24,15 @@ public sealed class IndexModel : PageModel if (effectiveTemplate.Equals("generic", StringComparison.OrdinalIgnoreCase) || effectiveTemplate.Equals("error", StringComparison.OrdinalIgnoreCase)) { - return Redirect("/errors/error"); + return Redirect("/error"); } if (effectiveTemplate.Equals("unavailable", StringComparison.OrdinalIgnoreCase) || effectiveTemplate.Equals("maintenance", StringComparison.OrdinalIgnoreCase)) { - return Redirect("/errors/maintenance"); + return Redirect("/maintenance"); } - return Redirect($"/errors/maintenance?page={Uri.EscapeDataString(effectiveTemplate)}"); + return Redirect($"/maintenance?page={Uri.EscapeDataString(effectiveTemplate)}"); } } diff --git a/Pages/Errors/Render.cshtml b/Pages/Errors/Render.cshtml index 9815046..7bfc6e1 100644 --- a/Pages/Errors/Render.cshtml +++ b/Pages/Errors/Render.cshtml @@ -1,3 +1,3 @@ -@page "/errors/{kind}" +@page "/{kind:regex(^error$|^maintenance$)}" @model maintenance.Pages.Errors.RenderModel @await Html.PartialAsync("_LockedTemplate", Model.Resolved) diff --git a/Program.cs b/Program.cs index 8a30e73..1575507 100644 --- a/Program.cs +++ b/Program.cs @@ -21,37 +21,42 @@ if (builder.Environment.IsDevelopment()) } // Support Kubernetes mounted secrets (key-per-file) and env var secrets. -// Add env vars again after custom providers so Secret-backed env values win precedence. +// Keep secrets in files to avoid exposing them via process environment variables. var secretsDirectory = builder.Configuration["K8S_SECRETS_PATH"] ?? "/var/run/secrets/maintenancepages"; if (Directory.Exists(secretsDirectory)) { builder.Configuration.AddKeyPerFile(secretsDirectory, optional: true, reloadOnChange: true); } -builder.Configuration.AddEnvironmentVariables(); var primaryDbConnection = builder.Configuration.GetConnectionString("PrimaryDb"); var groupLookupDbConnection = builder.Configuration.GetConnectionString("GroupLookupDb"); +var adminGroupSource = builder.Configuration[AuthEnvironment.AdminGroupSource] ?? AdminGroupSources.Max; if (string.IsNullOrWhiteSpace(primaryDbConnection)) { throw new InvalidOperationException("Missing connection string: ConnectionStrings:PrimaryDb"); } -if (string.IsNullOrWhiteSpace(groupLookupDbConnection)) -{ - throw new InvalidOperationException("Missing connection string: ConnectionStrings:GroupLookupDb"); -} - builder.Services.AddDbContext(options => { options.UseSqlServer(primaryDbConnection); }); -builder.Services.AddDbContext(options => +if (adminGroupSource.Equals(AdminGroupSources.Ad, StringComparison.OrdinalIgnoreCase)) { - options.UseSqlServer(groupLookupDbConnection); - options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); -}); + if (string.IsNullOrWhiteSpace(groupLookupDbConnection)) + { + throw new InvalidOperationException( + "Missing connection string: ConnectionStrings:GroupLookupDb when AUTH_GROUP_SOURCE=AD"); + } + + builder.Services.AddDbContext(options => + { + options.UseSqlServer(groupLookupDbConnection); + options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); + }); +} + builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -126,7 +131,7 @@ if (app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment()) { - app.UseExceptionHandler("/Error"); + app.UseExceptionHandler("/app-error"); app.UseHsts(); } @@ -137,6 +142,8 @@ app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); +app.MapGet("/healthz", () => Results.Ok("ok")).AllowAnonymous(); + app.MapGet("/api/whoami", (ClaimsPrincipal user, IIdentityContextFactory identityFactory) => { var identity = identityFactory.Create(user); diff --git a/artifacts_tmp_build/FutureSecrets.example.json b/artifacts_tmp_build/FutureSecrets.example.json index fa52df6..f3db0bc 100644 --- a/artifacts_tmp_build/FutureSecrets.example.json +++ b/artifacts_tmp_build/FutureSecrets.example.json @@ -1,5 +1,6 @@ { "AUTH_MODE": "WSFED", + "AUTH_GROUP_SOURCE": "MAX", "AUTH_ADMIN_GROUPS": "maintenance-Admins;maintenance-SuperAdmins", "ADFS_METADATA_ADDRESS": "https://adfs.example.com/federationmetadata/2007-06/federationmetadata.xml", "ADFS_WTRELM": "URN:WSFEDAPP", diff --git a/k8s/README.md b/k8s/README.md index fd7beec..7841024 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -1,9 +1,10 @@ Apply order: 1) kubectl apply -f k8s/namespace.yaml -2) kubectl apply -f k8s/secret.example.yaml -3) kubectl apply -f k8s/deployment.yaml -4) kubectl apply -f k8s/service.yaml -5) kubectl apply -f k8s/ingress.yaml +2) kubectl apply -f k8s/configmap.yaml +3) kubectl apply -f k8s/secret.example.yaml +4) kubectl apply -f k8s/deployment.yaml +5) kubectl apply -f k8s/service.yaml +6) kubectl apply -f k8s/ingress.yaml Then verify: - kubectl -n maintenance-dev get pods,svc,ingress diff --git a/k8s/configmap.yaml b/k8s/configmap.yaml new file mode 100644 index 0000000..fc0db47 --- /dev/null +++ b/k8s/configmap.yaml @@ -0,0 +1,26 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: maintenance-config + namespace: maintenance-dev +data: + AUTH_MODE: "OIDC" + AUTH_ADMIN_GROUPS: "maintenance-Admins;maintenance-SuperAdmins" + + # OIDC non-sensitive settings + OIDC_AUTHORITY: "https://adfs.example.com/adfs" + OIDC_CALLBACK_PATH: "/signin-oidc" + OIDC_SIGNOUT_CALLBACK_PATH: "/signout-callback-oidc" + OIDC_SCOPES: "openid;profile;email;role" + OIDC_ROLE_CLAIM_TYPE: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" + OIDC_NAME_CLAIM_TYPE: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" + OIDC_VALID_ISSUERS: "" + + # WSFED non-sensitive settings (used if AUTH_MODE=WSFED) + ADFS_METADATA_ADDRESS: "https://adfs.example.com/federationmetadata/2007-06/federationmetadata.xml" + ADFS_WTRELM: "URN:WSFEDAPP" + ADFS_VALID_ISSUERS: "https://adfs.example.com/adfs/services/trust;http://adfs.example.com/adfs/services/trust" + ADFS_WREPLY: "https://maintenance.stage.omb.gov/signin-wsfed" + ADFS_WHR: "" + ADFS_WAUTH: "" + ADFS_CALLBACK_PATH: "/signin-wsfed" diff --git a/k8s/deployment.yaml b/k8s/deployment.yaml index 4b4e327..4e93792 100644 --- a/k8s/deployment.yaml +++ b/k8s/deployment.yaml @@ -27,9 +27,15 @@ spec: value: http://+:8080 - name: ASPNETCORE_ENVIRONMENT value: Staging + - name: K8S_SECRETS_PATH + value: /var/run/secrets/maintenancepages envFrom: - - secretRef: - name: Maintenance-Secrets + - configMapRef: + name: maintenance-config + volumeMounts: + - name: app-secrets + mountPath: /var/run/secrets/maintenancepages + readOnly: true resources: requests: cpu: 100m @@ -39,13 +45,17 @@ spec: memory: 512Mi livenessProbe: httpGet: - path: / + path: /healthz port: http initialDelaySeconds: 30 periodSeconds: 15 readinessProbe: httpGet: - path: / + path: /healthz port: http initialDelaySeconds: 10 periodSeconds: 10 + volumes: + - name: app-secrets + secret: + secretName: Maintenance-Secrets diff --git a/k8s/secret.example.yaml b/k8s/secret.example.yaml index e6d9bd4..b9caa1f 100644 --- a/k8s/secret.example.yaml +++ b/k8s/secret.example.yaml @@ -5,23 +5,8 @@ metadata: namespace: maintenance-dev type: Opaque stringData: - AUTH_MODE: "WSFED" - AUTH_ADMIN_GROUPS: "maintenance-Admins;maintenance-SuperAdmins" - ADFS_METADATA_ADDRESS: "https://adfs.example.com/federationmetadata/2007-06/federationmetadata.xml" - ADFS_WTRELM: "URN:WSFEDAPP" - ADFS_VALID_ISSUERS: "https://adfs.example.com/adfs/services/trust;http://adfs.example.com/adfs/services/trust" - ADFS_WREPLY: "https://maintenance.stage.omb.gov/signin-wsfed" - ADFS_WHR: "" - ADFS_WAUTH: "" - ADFS_CALLBACK_PATH: "/signin-wsfed" - OIDC_AUTHORITY: "https://adfs.example.com/adfs" + AUTH_GROUP_SOURCE: "MAX" OIDC_CLIENT_ID: "CHANGE_ME" OIDC_CLIENT_SECRET: "CHANGE_ME" - OIDC_CALLBACK_PATH: "/signin-oidc" - OIDC_SIGNOUT_CALLBACK_PATH: "/signout-callback-oidc" - OIDC_SCOPES: "openid;profile;email;role" - OIDC_ROLE_CLAIM_TYPE: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" - OIDC_NAME_CLAIM_TYPE: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" - OIDC_VALID_ISSUERS: "" ConnectionStrings__PrimaryDb: "Server=CHANGE_ME;Database=maintenance;User Id=CHANGE_ME;Password=CHANGE_ME;TrustServerCertificate=True" ConnectionStrings__GroupLookupDb: "Server=CHANGE_ME;Database=GroupLookup;User Id=CHANGE_ME;Password=CHANGE_ME;TrustServerCertificate=True" diff --git a/maintenance.csproj b/maintenance.csproj index 9605096..10ce7a1 100644 --- a/maintenance.csproj +++ b/maintenance.csproj @@ -10,6 +10,7 @@ +
Edit | Preview + @if (!item.IsDefaultFallback) + { + | +
+ +
+ }