Files
2026-02-23 08:00:41 -05:00

21 KiB

Dynamic Error Pages - Project Plan

1. Project Summary

Build a centralized dynamic error page system that application teams can redirect users to when systems are unavailable, degraded, or under maintenance. The platform will support:

  • ADFS passthrough authentication
  • Role-based views (All Authenticated vs Admin)
  • Admin-managed page templates and content flags
  • API handlers for admin pages and app-to-page redirects with runtime details
  • Time-gated content visibility rules
  • Kubernetes hosting behind Traefik ingress

2. Goals

  1. Provide a consistent user-facing experience for outage and maintenance scenarios.
  2. Let admins update messages without redeploying apps.
  3. Allow source apps to redirect with contextual data that populates templates.
  4. Enforce security and role-based access for editing/administration.
  5. Support conditional/time-based display rules (for example support contacts).

3. Scope

In Scope

  • ADFS authentication passthrough
  • Authenticated user portal pages
  • Admin portal pages for content/state management
  • Catch-all templates for outage and maintenance states
  • API endpoints for:
    • Admin CRUD/configuration
    • Source application runtime redirects/data payloads
  • Feature flags and scheduling logic for content visibility
  • Group-based role and permission management
  • Deployment to Kubernetes behind Traefik

Out of Scope (Initial Phase)

  • Per-app fully custom page builder UI
  • Multi-IdP auth support beyond ADFS
  • Public unauthenticated access

4. Users and Access Model

Authentication

  • All platform routes require authentication.
  • If authentication fails, upstream service blocks access and displays its own error page.
  • This application does not provide an unauthenticated fallback page.

Roles

  • All Authenticated Users:
    • Can view rendered error/maintenance pages.
    • Cannot modify content.
  • Admin Users:
    • Can access admin UI and APIs.
    • Can edit templates, flags, maintenance windows, app mappings, groups, and permissions.

Authorization Strategy

  • Use group membership claims from ADFS token to assign roles.
  • Maintain configurable allowed admin group list (add/remove without code changes).
  • Support granular authorization per page component/action.
  • Apply role/permission checks at both UI route level and API handler level.

5. Functional Requirements

  1. Support two generic catch-all templates:
    • Maintenance page
    • Application down/unavailable page
  2. Admins can edit displayed content for both templates.
  3. Source apps can redirect users to the system with details to populate template fields.
  4. Admin API handlers provide data and routing/config for admin pages.
  5. Admins can define flags controlling whether specific content blocks are shown.
  6. Admins can define maintenance windows that influence content visibility.
  7. Time-gated behavior example:
    • Hide support contact details during active maintenance window.
    • Show support contact details outside the maintenance window.

6. Non-Functional Requirements

  • Backend database platform is Microsoft SQL Server (MSSQL).
  • Delivery platform is Azure DevOps (repos/pipelines/releases).
  • Secure by default with authenticated access and role checks.
  • Database access uses a dedicated service account with least-privilege permissions.
  • Highly available deployment in Kubernetes.
  • Clear auditability for admin changes (who/what/when).
  • Fast render path for redirect-based user flows.
  • Configurable and maintainable API contract for calling apps.

7. Proposed Architecture

Components

  • Web UI Service:
    • Renders generic templates.
    • Hosts authenticated and admin views.
  • Admin API Service:
    • Template/content management.
    • Flags and schedule management.
    • App mapping and permissions management.
  • Runtime Render API:
    • Accepts app-provided context and resolves template variables.
  • Data Store (MSSQL):
    • Primary application database (read/write) stores templates, flags, schedules, app mappings, permissions, and audit records.
    • Separate group lookup database is accessed read-only for resolving group names.

Request Flow (High Level)

  1. App encounters outage/maintenance state.
  2. App redirects user to error page endpoint with app/context details.
  3. Platform authenticates user via ADFS passthrough.
  4. Render service resolves template + flags + current schedule state.
  5. User sees appropriate dynamic page.

8. API Design (Draft)

Admin APIs (Admin Role Required)

  • GET /api/admin/templates
  • PUT /api/admin/templates/{templateId}
  • GET /api/admin/apps
  • PUT /api/admin/apps/{appId}
  • GET /api/admin/flags
  • PUT /api/admin/flags/{flagKey}
  • GET /api/admin/windows
  • POST /api/admin/windows
  • PUT /api/admin/windows/{windowId}
  • GET /api/admin/authorization/groups
  • PUT /api/admin/authorization/groups
  • GET /api/admin/authorization/permissions
  • PUT /api/admin/authorization/permissions/{permissionKey}

Runtime APIs

  • POST /api/render
    • Input: app identifier + event type (maintenance/down) + optional details
    • Output: resolved page model

Runtime Payload Map (Initial JSON Draft)

{
  "requestId": "uuid",
  "source": {
    "appId": "billing-api",
    "environment": "prod",
    "instance": "billing-api-7c8d4f",
    "signature": "optional-signed-token"
  },
  "event": {
    "type": "maintenance",
    "statusCode": "MAINT_001",
    "occurredAtUtc": "2026-02-12T15:27:00Z"
  },
  "display": {
    "title": "optional override",
    "message": "optional override",
    "details": [
      { "label": "Change Ticket", "value": "CHG12345" }
    ]
  },
  "support": {
    "contactName": "Service Desk",
    "contactEmail": "support@company.com",
    "contactPhone": "800-000-0000"
  },
  "user": {
    "timezone": "America/Chicago",
    "locale": "en-US"
  }
}

Security

  • Enforce role policy on /api/admin/*.
  • Validate source app identity for runtime calls (shared secret, token, or mTLS).

9. Data Model (Draft)

Template

  • id
  • name (maintenance, down)
  • title
  • body
  • supportContactBlock
  • lastUpdatedBy
  • lastUpdatedAt

AppMapping

  • appId
  • displayName
  • defaultTemplate
  • allowedFields
  • active

FeatureFlag

  • key
  • enabled
  • scope (global/app/template)

MaintenanceWindow

  • id
  • appId (nullable for global)
  • startTimeEastern
  • endTimeEastern
  • hideSupportContactDuringWindow (bool)
  • displayTimezone (derived from user context for UI presentation)

AuthorizationGroup

  • id
  • groupClaimValue
  • role (admin, future roles)
  • active

PermissionRule

  • id
  • permissionKey (for example template.edit.body, template.edit.contact, window.manage)
  • groupId
  • effect (allow/deny)

AuditRecord

  • id
  • actor
  • action
  • target
  • timestampUtc
  • diff

10. UI Requirements

Authenticated View

  • Render user-facing page content only.
  • Clean, readable status and guidance.
  • Maintenance window source is Eastern time; render local-time equivalents for the user where appropriate.

Admin View

  • Edit maintenance/down templates.
  • Toggle content flags.
  • Create/manage maintenance windows (entered/stored as Eastern time).
  • Manage authorization groups (add/remove).
  • Manage granular permissions by page component/action.
  • Preview rendered output with current rules.

11. Kubernetes and Traefik Deployment

  • Deploy service(s) to Kubernetes namespace for shared platform tools.
  • Use Azure DevOps for source control workflows, CI/CD pipelines, and release orchestration.
  • Expose via Traefik ingress route(s) with TLS.
  • Configure session/auth headers for ADFS passthrough integration.
  • Store secrets (ADFS settings, API tokens, and DB service account credentials) in Kubernetes secrets.
  • Add readiness/liveness probes and autoscaling targets.

12. Logging, Monitoring, and Audit

  • Structured logs for render/admin actions.
  • Metrics for request count, render latency, and error rates.
  • Admin audit trail for all content/config, group, and permission changes.
  • Alerts for elevated 5xx rates and auth failures.

13. Design Structure

Layered Design

  1. Edge Layer
    • Traefik ingress, TLS termination, routing.
  2. Auth Layer
    • ADFS token passthrough, claim extraction, identity context creation.
  3. Application Layer
    • UI rendering, admin endpoints, runtime render endpoint.
  4. Domain Layer
    • Rules engine (flags, schedule checks, permission checks, template resolution).
  5. Data Layer
    • MSSQL repositories, transactional updates, audit persistence.

Domain Modules

  • IdentityModule: token claims, group resolution, role resolution.
  • AuthorizationModule: permission evaluation by action/component.
  • TemplateModule: template retrieval, placeholder validation, content overrides.
  • ScheduleModule: Eastern-time window evaluation + user-local projection.
  • RenderModule: resolves final page model with rule precedence.
  • AuditModule: immutable audit writes for admin changes.

Rule Evaluation Order

  1. Authentication required.
  2. Authorization checks (route + action).
  3. App mapping validation.
  4. Template selection.
  5. Feature-flag checks.
  6. Maintenance window checks.
  7. Time-gated content filtering.
  8. Final payload field allowlist enforcement.
  9. Response render.

14. Rules Catalog

Authentication Rules

  • AUTH-001: All routes require valid authenticated identity.
  • AUTH-002: Failed authentication is handled upstream; app does not render fallback unauthenticated pages.

Authorization Rules

  • AUTHZ-001: Admin access is granted only if token group claim matches configured active admin group.
  • AUTHZ-002: Group list is config-driven (add/remove groups without redeploy).
  • AUTHZ-003: Deny by default if no explicit allow rule exists.
  • AUTHZ-004: Component-level permissions override broad role where configured.

Rendering Rules

  • RND-001: Only two base templates in phase 1: maintenance, down.
  • RND-002: App-provided fields can only populate whitelisted template variables.
  • RND-003: If app-provided template type is invalid, fallback to app default template.
  • RND-004: If app mapping is missing/inactive, return controlled generic error response.

Schedule and Timezone Rules

  • SCH-001: Maintenance windows are authored and stored in Eastern time.
  • SCH-002: Window comparisons are performed against Eastern-time normalized current time.
  • SCH-003: User-facing timestamps are also displayed in the user timezone when available.
  • SCH-004: If user timezone is missing, default display timezone is Eastern.

Content Gating Rules

  • CNT-001: hideSupportContactDuringWindow=true removes support blocks while window is active.
  • CNT-002: Outside active windows, support blocks are shown unless independently disabled by flag.
  • CNT-003: Explicit safety flags can suppress any optional content block globally.

Payload Rules

  • PAY-001: Runtime payload format is JSON only.
  • PAY-002: Required fields: source.appId, event.type, event.occurredAtUtc.
  • PAY-003: Unknown fields are ignored and logged for review.
  • PAY-004: Payload size and field lengths are bounded to configured limits.

Data Access Rules

  • DB-001: Service account authenticates to MSSQL using credentials from Kubernetes secret.
  • DB-002: Read/write granted only to primary application database.
  • DB-003: Group lookup database access is read-only.
  • DB-004: Write operations are audited with actor, timestamp, and diff.

15. Milestones

  1. Foundation
    • Auth integration, base service skeleton, data model.
  2. Runtime Path
    • Catch-all templates, runtime render endpoint, app redirect contract.
  3. Admin Path
    • Admin UI + admin APIs for templates/flags/windows/groups/permissions.
  4. Deployment
    • Kubernetes manifests/helm, Traefik ingress, observability.
  5. Hardening
    • Security tests, load tests, audit verification, documentation.

16. Open Questions

  1. Exact claim name/format in ADFS token for group membership.
  2. Permission model depth for initial release (coarse admin-only vs selected component-level permissions).
  3. What SLA/SLO targets should this service meet?

17. Module Breakdown and Delivery Order

Project implementation will proceed module-by-module, validating each module before moving to the next.

Module 1: Database

  • Purpose: Provide durable storage and retrieval for templates, flags, windows, auth groups, permissions, app mappings, and audit records.
  • Scope:
    • MSSQL schema creation and migrations.
    • Connection via service account secret from Kubernetes.
    • Read/write permissions on primary app DB.
    • Read-only permissions on group lookup DB.
  • Validation Gate:
    • Migration runs cleanly in lower environment.
    • CRUD operations pass integration tests.
    • Read-only enforcement confirmed on lookup DB.

Module 2: Authentication

  • Purpose: Enforce authenticated-only access and resolve token claims into identity context.
  • Scope:
    • ADFS passthrough integration.
    • Claim extraction (user identity, group claims).
    • Group-to-role mapping (All Authenticated, Admin).
    • Deny-by-default behavior for non-authorized actions.
  • Validation Gate:
    • Authenticated users can access view routes.
    • Unauthenticated requests are blocked upstream.
    • Admin role assignment works from configured groups.

Module 3: API

  • Purpose: Expose runtime and admin endpoints with authorization, validation, and rules evaluation.
  • Scope:
    • Runtime render endpoint contract (JSON payload).
    • Admin CRUD endpoints for templates, flags, windows, groups, permissions.
    • Request validation, allowlist filtering, and audit logging hooks.
    • Schedule/time-gate rule application.
  • Validation Gate:
    • Endpoint auth/authz checks pass.
    • Runtime payload validation and rule resolution pass.
    • Admin writes produce expected audit records.

Module 4: Pages (Razor Pages)

  • Purpose: Deliver user-facing and admin-facing UI over the API/domain logic.
  • Scope:
    • Authenticated user error page render flows.
    • Admin screens for templates, flags, windows, groups, permissions.
    • Preview behavior for schedule and content-gate outcomes.
    • Clear separation of PageModel orchestration vs domain logic.
  • Validation Gate:
    • End-to-end render flow works from API payload to final page.
    • Admin edit flows persist and reflect in runtime renders.
    • UI route protections align with role/permission rules.

Module Sequence

  1. Database
  2. Authentication
  3. API
  4. Pages

Definition of Done Per Module

  • Code complete for scoped module requirements.
  • Automated tests added and passing for module responsibilities.
  • Integration test against dependent module(s) passing.
  • Deployment pipeline updated in Azure DevOps for module changes.

18. Authentication Service Draft (Razor Pages)

Initial implementation target is local development using environment variables and ADFS WS-Federation.

ADFS Settings (Current)

  • RPT Identifier (realm): URN:WSFEDAPP
  • Local app URL: https://localhost:44374
  • WS-Fed callback path: /signin-wsfed

Local Environment Variables (Phase 1)

  • AUTH_MODE=WSFED
  • ADFS_METADATA_ADDRESS=https://<adfs-host>/federationmetadata/2007-06/federationmetadata.xml
  • ADFS_WTRELM=URN:WSFEDAPP
  • ADFS_WREPLY=https://localhost:44374/signin-wsfed
  • ADFS_CALLBACK_PATH=/signin-wsfed
  • AUTH_ADMIN_GROUPS=<group1>;<group2>
  • ASPNETCORE_URLS=https://localhost:44374

Program Startup Draft

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.WsFederation;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
    })
    .AddCookie(options =>
    {
        options.Cookie.Name = "errorpages.auth";
        options.AccessDeniedPath = "/AccessDenied";
    })
    .AddWsFederation(options =>
    {
        options.MetadataAddress = Environment.GetEnvironmentVariable("ADFS_METADATA_ADDRESS");
        options.Wtrealm = Environment.GetEnvironmentVariable("ADFS_WTRELM");
        options.Wreply = Environment.GetEnvironmentVariable("ADFS_WREPLY");
        options.CallbackPath = Environment.GetEnvironmentVariable("ADFS_CALLBACK_PATH") ?? "/signin-wsfed";
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireAssertion(ctx =>
    {
        var configured = (Environment.GetEnvironmentVariable("AUTH_ADMIN_GROUPS") ?? string.Empty)
            .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

        return configured.Any(group =>
            ctx.User.Claims.Any(c =>
                (c.Type == "groups" || c.Type == "group" || c.Type.Contains("role")) &&
                string.Equals(c.Value, group, StringComparison.OrdinalIgnoreCase)));
    }));
});

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.Run();

Route Authorization Draft

  • User-facing pages: authenticated users only.
  • Admin pages (/Admin/*): authenticated + AdminOnly policy.
  • No unauthenticated page rendering in this service.

Validation Checklist for Module 2

  1. Unauthenticated request to / triggers WS-Fed challenge.
  2. Successful ADFS login issues app auth cookie.
  3. User in configured admin group can access /Admin.
  4. User not in admin group is denied from /Admin.
  5. Invalid/missing token claims result in deny-by-default behavior.

19. Modular Authentication Design (Swappable Providers)

Authentication must be provider-agnostic so ADFS can be replaced later with OAuth/OIDC or another enterprise IdP without rewriting page/API authorization logic.

Design Goals

  • Keep UI/API authorization logic independent from authentication protocol.
  • Swap provider through configuration (AUTH_MODE) and provider registration.
  • Normalize claims into one internal identity model.
  • Support multiple providers over time with minimal code churn.

Proposed Folder Structure

  • Authentication/Abstractions
    • IAuthProvider.cs
    • IClaimsTransformer.cs
    • IIdentityContextFactory.cs
  • Authentication/Core
    • IdentityContext.cs
    • IdentityContextFactory.cs
    • GroupRoleResolver.cs
  • Authentication/Providers/AdfsWsFed
    • AdfsWsFedAuthProvider.cs
    • AdfsWsFedOptions.cs
  • Authentication/Providers/Oidc (future)
    • OidcAuthProvider.cs
    • OidcOptions.cs
  • Authentication/Configuration
    • AuthOptions.cs
    • AuthMode.cs

Core Contracts

public interface IAuthProvider
{
    string Mode { get; }
    AuthenticationBuilder Configure(AuthenticationBuilder builder, IConfiguration config);
}

public interface IClaimsTransformer
{
    ClaimsPrincipal Transform(ClaimsPrincipal principal);
}

public sealed class IdentityContext
{
    public required string UserId { get; init; }
    public required string DisplayName { get; init; }
    public required IReadOnlyCollection<string> Groups { get; init; }
    public required IReadOnlyCollection<string> Roles { get; init; }
}

Provider Registration Pattern

var authMode = Environment.GetEnvironmentVariable("AUTH_MODE") ?? "WSFED";

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = authMode == "WSFED"
        ? WsFederationDefaults.AuthenticationScheme
        : "oidc";
})
.AddCookie();

IAuthProvider provider = authMode switch
{
    "WSFED" => new AdfsWsFedAuthProvider(),
    "OIDC" => new OidcAuthProvider(), // future
    _ => throw new InvalidOperationException($"Unsupported AUTH_MODE: {authMode}")
};

provider.Configure(builder.Services.AddAuthentication(), builder.Configuration);

Normalized Identity Rules

  • Map provider-specific claim names into canonical fields:
    • UserId
    • DisplayName
    • Groups
    • Roles
  • Authorization and page/API policies must consume only normalized values.
  • Never couple policy checks directly to raw provider claim types in page handlers.

Authorization Integration

  • AdminOnly policy evaluates normalized groups against configured admin groups.
  • Component-level permissions use normalized group IDs, not provider-specific claim keys.
  • Deny-by-default if group mapping cannot be resolved.

Configuration Model

  • Shared:
    • AUTH_MODE (WSFED, future OIDC)
    • AUTH_ADMIN_GROUPS
  • ADFS WS-Fed:
    • ADFS_METADATA_ADDRESS
    • ADFS_WTRELM
    • ADFS_WREPLY
    • ADFS_CALLBACK_PATH
  • OIDC (future):
    • OIDC_AUTHORITY
    • OIDC_CLIENT_ID
    • OIDC_CLIENT_SECRET
    • OIDC_CALLBACK_PATH

Swap Strategy (ADFS to OIDC Example)

  1. Implement OidcAuthProvider with same IAuthProvider contract.
  2. Ensure OIDC claims are mapped into the same normalized identity context.
  3. Set AUTH_MODE=OIDC.
  4. Validate auth flows and policy outcomes without changing PageModel/API authorization code.

Authentication Module Validation (Modular)

  1. Provider bootstraps from AUTH_MODE without code changes.
  2. Identity context generation is identical shape across providers.
  3. AdminOnly policy behavior remains unchanged when switching providers.
  4. Unauthorized users remain denied by default in all providers.