Changes
This commit is contained in:
@@ -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/
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace maintenance.Authentication.Configuration;
|
||||
|
||||
public static class AdminGroupSources
|
||||
{
|
||||
public const string Max = "MAX";
|
||||
public const string Ad = "AD";
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
@@ -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<string> 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)
|
||||
|
||||
@@ -13,6 +13,7 @@ public sealed class AppDbContext : DbContext
|
||||
public DbSet<AppMappingEntity> AppMappings => Set<AppMappingEntity>();
|
||||
public DbSet<FeatureFlagEntity> FeatureFlags => Set<FeatureFlagEntity>();
|
||||
public DbSet<MaintenanceWindowEntity> MaintenanceWindows => Set<MaintenanceWindowEntity>();
|
||||
public DbSet<AdminGroupEntity> AdminGroups => Set<AdminGroupEntity>();
|
||||
public DbSet<AuthorizationGroupEntity> AuthorizationGroups => Set<AuthorizationGroupEntity>();
|
||||
public DbSet<PermissionRuleEntity> PermissionRules => Set<PermissionRuleEntity>();
|
||||
public DbSet<AuditRecordEntity> AuditRecords => Set<AuditRecordEntity>();
|
||||
@@ -57,6 +58,15 @@ public sealed class AppDbContext : DbContext
|
||||
e.HasIndex(x => new { x.AppId, x.StartTimeEastern, x.EndTimeEastern });
|
||||
});
|
||||
|
||||
modelBuilder.Entity<AdminGroupEntity>(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<AuthorizationGroupEntity>(e =>
|
||||
{
|
||||
e.ToTable("AuthorizationGroup");
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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"]
|
||||
@@ -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",
|
||||
|
||||
@@ -5,12 +5,28 @@
|
||||
}
|
||||
|
||||
<h1>Admin Groups</h1>
|
||||
<p>Manage group claim values that grant admin access.</p>
|
||||
<p>
|
||||
@if (Model.IsAdSource)
|
||||
{
|
||||
<text>Source: AD lookup + AuthorizationGroup records.</text>
|
||||
}
|
||||
else
|
||||
{
|
||||
<text>Source: MAX app database records.</text>
|
||||
}
|
||||
</p>
|
||||
|
||||
<form method="get" class="mb-4">
|
||||
<div class="row g-2">
|
||||
<div class="col-md-8">
|
||||
<input asp-for="GroupSearch" class="form-control" placeholder="Search available groups by name" />
|
||||
@if (Model.IsAdSource)
|
||||
{
|
||||
<input asp-for="GroupSearch" class="form-control" placeholder="Search AD lookup groups by name" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<input asp-for="GroupSearch" class="form-control" placeholder="Search added groups (case-insensitive)" />
|
||||
}
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<button type="submit" class="btn btn-outline-primary">Search</button>
|
||||
@@ -18,7 +34,7 @@
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@if (Model.LookupResults.Count > 0)
|
||||
@if (Model.IsAdSource && Model.LookupResults.Count > 0)
|
||||
{
|
||||
<div class="mb-4">
|
||||
<h5>Lookup Results</h5>
|
||||
@@ -63,29 +79,53 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Group Claim Value</th>
|
||||
<th>Role</th>
|
||||
<th>Active</th>
|
||||
@if (Model.IsAdSource)
|
||||
{
|
||||
<th>Role</th>
|
||||
<th>Active</th>
|
||||
}
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var g in Model.Groups)
|
||||
@if (Model.IsAdSource)
|
||||
{
|
||||
<tr>
|
||||
<td>@g.GroupClaimValue</td>
|
||||
<td>@g.Role</td>
|
||||
<td>@g.Active</td>
|
||||
<td>
|
||||
<form method="post" asp-page-handler="Toggle" style="display:inline">
|
||||
<input type="hidden" name="id" value="@g.Id" />
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary">Toggle</button>
|
||||
</form>
|
||||
<form method="post" asp-page-handler="Delete" style="display:inline">
|
||||
<input type="hidden" name="id" value="@g.Id" />
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger">Remove</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
@foreach (var g in Model.AdGroups)
|
||||
{
|
||||
<tr>
|
||||
<td>@g.GroupClaimValue</td>
|
||||
<td>@g.Role</td>
|
||||
<td>@g.Active</td>
|
||||
<td>
|
||||
<form method="post" asp-page-handler="Toggle" style="display:inline">
|
||||
<input type="hidden" name="id" value="@g.Id" />
|
||||
<input type="hidden" asp-for="GroupSearch" />
|
||||
<button type="submit" class="btn btn-sm btn-outline-secondary">Toggle</button>
|
||||
</form>
|
||||
<form method="post" asp-page-handler="Delete" style="display:inline">
|
||||
<input type="hidden" name="id" value="@g.Id" />
|
||||
<input type="hidden" asp-for="GroupSearch" />
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger">Remove</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@foreach (var g in Model.Groups)
|
||||
{
|
||||
<tr>
|
||||
<td>@g.GroupClaimValue</td>
|
||||
<td>
|
||||
<form method="post" asp-page-handler="Delete" style="display:inline">
|
||||
<input type="hidden" name="id" value="@g.Id" />
|
||||
<input type="hidden" asp-for="GroupSearch" />
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger">Remove</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -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<AuthorizationGroupEntity> Groups { get; private set; } = [];
|
||||
public bool IsAdSource { get; private set; }
|
||||
public IReadOnlyList<AdminGroupEntity> Groups { get; private set; } = [];
|
||||
public IReadOnlyList<AuthorizationGroupEntity> AdGroups { get; private set; } = [];
|
||||
public IReadOnlyList<string> LookupResults { get; private set; } = [];
|
||||
|
||||
public async Task OnGetAsync()
|
||||
{
|
||||
IsAdSource = ResolveIsAdSource();
|
||||
await LoadAsync();
|
||||
await SearchAsync();
|
||||
if (IsAdSource)
|
||||
{
|
||||
await SearchAdLookupAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<GroupLookupDbContext>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +58,14 @@
|
||||
<div class="col-md-6 mb-3">
|
||||
<label asp-for="Input.StartUtc" class="form-label"></label>
|
||||
<input asp-for="Input.StartUtc" class="form-control" type="datetime-local" />
|
||||
<span asp-validation-for="Input.StartUtc" class="text-danger"></span>
|
||||
<div id="startUtcDisplay" class="form-text"></div>
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label asp-for="Input.EndUtc" class="form-label"></label>
|
||||
<input asp-for="Input.EndUtc" class="form-control" type="datetime-local" />
|
||||
<span asp-validation-for="Input.EndUtc" class="text-danger"></span>
|
||||
<div id="endUtcDisplay" class="form-text"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -122,3 +126,109 @@
|
||||
</form>
|
||||
|
||||
<partial name="_ValidationScriptsPartial" />
|
||||
<script>
|
||||
(function () {
|
||||
const startInput = document.getElementById("Input_StartUtc");
|
||||
const endInput = document.getElementById("Input_EndUtc");
|
||||
const startUtcDisplay = document.getElementById("startUtcDisplay");
|
||||
const endUtcDisplay = document.getElementById("endUtcDisplay");
|
||||
|
||||
function getOffsetMinutes(timeZone, instant) {
|
||||
const offsetPart = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: timeZone,
|
||||
timeZoneName: "shortOffset"
|
||||
})
|
||||
.formatToParts(instant)
|
||||
.find(function (part) { return part.type === "timeZoneName"; });
|
||||
|
||||
if (!offsetPart) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = offsetPart.value.match(/GMT([+-]\d{1,2})(?::(\d{2}))?/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hours = parseInt(match[1], 10);
|
||||
const minutes = match[2] ? parseInt(match[2], 10) : 0;
|
||||
const sign = hours < 0 ? -1 : 1;
|
||||
return (Math.abs(hours) * 60 + minutes) * sign;
|
||||
}
|
||||
|
||||
function easternLocalToUtcInstant(localValue) {
|
||||
const match = localValue.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const year = Number(match[1]);
|
||||
const monthIndex = Number(match[2]) - 1;
|
||||
const day = Number(match[3]);
|
||||
const hour = Number(match[4]);
|
||||
const minute = Number(match[5]);
|
||||
|
||||
const naiveUtcMillis = Date.UTC(year, monthIndex, day, hour, minute, 0, 0);
|
||||
let guess = new Date(naiveUtcMillis);
|
||||
const offsetOne = getOffsetMinutes("America/New_York", guess);
|
||||
if (offsetOne === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let utcMillis = naiveUtcMillis - (offsetOne * 60 * 1000);
|
||||
guess = new Date(utcMillis);
|
||||
const offsetTwo = getOffsetMinutes("America/New_York", guess);
|
||||
if (offsetTwo !== null && offsetTwo !== offsetOne) {
|
||||
utcMillis = naiveUtcMillis - (offsetTwo * 60 * 1000);
|
||||
}
|
||||
|
||||
return new Date(utcMillis);
|
||||
}
|
||||
|
||||
function toUtcText(easternLocalValue) {
|
||||
if (!easternLocalValue) {
|
||||
return "UTC: not set";
|
||||
}
|
||||
|
||||
const utcInstant = easternLocalToUtcInstant(easternLocalValue);
|
||||
if (!utcInstant || Number.isNaN(utcInstant.getTime())) {
|
||||
return "UTC: invalid ET value";
|
||||
}
|
||||
|
||||
const formatted = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "UTC",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
timeZoneName: "short"
|
||||
}).format(utcInstant);
|
||||
|
||||
return "UTC: " + formatted;
|
||||
}
|
||||
|
||||
function refreshDisplays() {
|
||||
if (startUtcDisplay && startInput) {
|
||||
startUtcDisplay.textContent = toUtcText(startInput.value);
|
||||
}
|
||||
|
||||
if (endUtcDisplay && endInput) {
|
||||
endUtcDisplay.textContent = toUtcText(endInput.value);
|
||||
}
|
||||
}
|
||||
|
||||
if (startInput) {
|
||||
startInput.addEventListener("input", refreshDisplays);
|
||||
startInput.addEventListener("change", refreshDisplays);
|
||||
}
|
||||
|
||||
if (endInput) {
|
||||
endInput.addEventListener("input", refreshDisplays);
|
||||
endInput.addEventListener("change", refreshDisplays);
|
||||
}
|
||||
|
||||
refreshDisplays();
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
<h1>Manage Pages</h1>
|
||||
<p>Create and schedule maintenance/error pages while keeping the visual template fixed.</p>
|
||||
<p><a asp-page="./Create" class="btn btn-primary">Create page from template</a></p>
|
||||
@if (!string.IsNullOrWhiteSpace(Model.StatusMessage))
|
||||
{
|
||||
<div class="alert alert-info" role="alert">@Model.StatusMessage</div>
|
||||
}
|
||||
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
@@ -33,6 +37,17 @@
|
||||
<td>
|
||||
<a asp-page="./Edit" asp-route-id="@item.Id">Edit</a> |
|
||||
<a href="@Model.GetPreviewUrl(item)" target="_blank" rel="noopener">Preview</a>
|
||||
@if (!item.IsDefaultFallback)
|
||||
{
|
||||
<text> | </text>
|
||||
<form method="post" asp-page-handler="Delete" asp-route-id="@item.Id" style="display:inline">
|
||||
<button type="submit"
|
||||
class="btn btn-link p-0 align-baseline"
|
||||
onclick="return confirm('Delete page @item.Key?');">
|
||||
Delete
|
||||
</button>
|
||||
</form>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
|
||||
@@ -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<ManagedPageEntity> 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<IActionResult> 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)}";
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
@page
|
||||
@page "/app-error"
|
||||
@model ErrorModel
|
||||
@{
|
||||
ViewData["Title"] = "Error";
|
||||
|
||||
@@ -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)}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
@page "/errors/{kind}"
|
||||
@page "/{kind:regex(^error$|^maintenance$)}"
|
||||
@model maintenance.Pages.Errors.RenderModel
|
||||
@await Html.PartialAsync("_LockedTemplate", Model.Resolved)
|
||||
|
||||
+19
-12
@@ -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<AppDbContext>(options =>
|
||||
{
|
||||
options.UseSqlServer(primaryDbConnection);
|
||||
});
|
||||
|
||||
builder.Services.AddDbContext<GroupLookupDbContext>(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<GroupLookupDbContext>(options =>
|
||||
{
|
||||
options.UseSqlServer(groupLookupDbConnection);
|
||||
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
|
||||
});
|
||||
}
|
||||
|
||||
builder.Services.AddScoped<ITemplateService, TemplateService>();
|
||||
builder.Services.AddScoped<IManagedPageService, ManagedPageService>();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
+5
-4
@@ -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
|
||||
|
||||
@@ -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"
|
||||
+14
-4
@@ -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
|
||||
|
||||
+1
-16
@@ -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"
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.WsFederation" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user