Skip to content
This repository was archived by the owner on Feb 20, 2026. It is now read-only.

Latest commit

 

History

History
1405 lines (1153 loc) · 61 KB

File metadata and controls

1405 lines (1153 loc) · 61 KB

OAuth/OIDC AAA Server — Full Implementation Plan

Project working name: Gatekeeper Status: Draft Date: 2026-02-15 Author: John Nahlen Target: Enterprise-grade OAuth2/OIDC Authentication, Authorization, and Accounting server comparable to Keycloak, Authentik, Auth0, and FusionAuth.


Table of Contents

  1. Architecture Decisions Summary
  2. Technology Stack
  3. System Architecture
  4. Security Architecture & Threat Model
  5. Database Design
  6. Extensibility Architecture
  7. Feature Inventory (All Phases)
  8. Phased Implementation Plan
  9. Claude Code Task Breakdown
  10. Model Delegation Strategy
  11. Testing Strategy
  12. Deployment & Operations
  13. RFC & Standards Reference
  14. Open Questions & Future Considerations

1. Architecture Decisions Summary

ADR-001: Tech Stack — C# / ASP.NET Core

Decision: C# with ASP.NET Core 9+ on .NET 9+.

Rationale:

  • John's primary language and deepest expertise (10+ years)
  • Mature cryptographic libraries (System.Security.Cryptography, Microsoft.IdentityModel.*)
  • High-performance HTTP pipeline (Kestrel)
  • Strong DI container (essential for plugin architecture)
  • Entity Framework Core for database abstraction
  • Excellent OpenAPI/Swagger tooling

Tradeoffs:

  • Smaller open-source identity community compared to Java (Keycloak) or Go (Ory)
  • .NET Microsoft.IdentityModel libraries are complex but battle-tested
  • Runtime size is larger than Go binaries (mitigated by Docker multi-stage builds)

Alternatives considered: Go (smaller binaries but weaker DI story), Node.js/TypeScript (weaker type safety for security-critical code), Java/Spring (too heavy for solo developer).

ADR-002: Database — PostgreSQL

Decision: PostgreSQL as primary data store.

Rationale:

  • Best open-source RDBMS for complex queries, JSON support, and extensibility
  • Strong row-level security support (useful for multi-tenant data isolation)
  • Mature EF Core provider (Npgsql)
  • Industry standard for auth servers (Keycloak, Authentik, Ory all use Postgres)
  • Excellent replication, backup, and point-in-time recovery

Tradeoffs:

  • Less familiar to John than MySQL/SQL Server (manageable — EF Core abstracts most differences)
  • Requires separate installation vs SQLite (justified by multi-tenant scale requirements)

ADR-003: Cache / Revocation Store — Redis

Decision: Redis for token revocation lists, rate limiting state, session cache, and distributed locking.

Rationale:

  • Sub-millisecond reads for revocation checks on every token validation
  • Built-in TTL expiry (tokens auto-clean from revocation list)
  • Pub/sub for distributed cache invalidation

Failover strategy: If Redis is down, fall back to database-backed revocation checks (slower, but safe). Never fail-open on revocation.

ADR-004: Token Format — JWT (Signed) with Revocation

Decision: JWT access tokens (signed, stateless) with server-side revocation list (Redis-backed). Opaque refresh tokens stored server-side.

Rationale:

  • JWTs allow resource servers to validate tokens without calling back to the auth server
  • Revocation endpoint (RFC 7009) + Redis revocation list provides defense-in-depth
  • Opaque refresh tokens force server-side validation — more secure for long-lived credentials
  • Short access token lifetimes (5-15 min) limit exposure window

ADR-005: Signing Algorithm — ES256 (primary), RS256 (compatibility)

Decision: Default to ES256 (ECDSA P-256) for new deployments. Support RS256 for backward compatibility. Support full algorithm suite for Keycloak parity (PS256/384/512, ES256/384/512, RS256/384/512, EdDSA, HS256/384/512).

Rationale:

  • ES256: smaller keys, faster signing, smaller tokens
  • RS256 necessary for older clients and enterprise environments
  • EdDSA (Ed25519) is emerging but not yet universally supported

ADR-006: Password Hashing — Argon2id (primary), bcrypt (migration)

Decision: Argon2id for all new password hashes. Support bcrypt, scrypt, and PBKDF2 for migration. Pluggable hasher interface.

Rationale:

  • Argon2id won the Password Hashing Competition — resistant to GPU and ASIC attacks
  • Memory-hard: 64MB default, 3 iterations, 4 parallelism (tunable)
  • OWASP recommendation as of 2024

ADR-007: Multi-Tenancy — Schema-per-tenant

Decision: Start single-tenant, design for schema-per-tenant (PostgreSQL schemas) with shared infrastructure.

Rationale:

  • Schema isolation provides strong data boundaries without separate databases
  • PostgreSQL schemas + EF Core HasDefaultSchema() enable clean tenant switching
  • Shared infrastructure keeps operational cost low
  • Can upgrade to database-per-tenant for high-security tenants later

ADR-008: Token Revocation — RFC 7009 + Redis + Short-Lived JWTs

Decision: Implement RFC 7009 revocation endpoint. Revoked token JTIs stored in Redis with TTL matching token expiry. Refresh tokens revoked by deletion from database.

ADR-009: Client Registration — Admin API Only (v1)

Decision: Phase 1 requires admin API to register clients. Dynamic Client Registration (RFC 7591/7592) deferred to Phase 5+. Client model designed to support dynamic registration fields from day one.

ADR-010: External IdP Adapter — Generic OIDC with Provider-Specific Mappers

Decision: Build a generic OIDC federation adapter. Provider-specific behavior handled by pluggable mapper classes. SAML adapter designed as an interface, implemented Phase 7.

ADR-011: Headless / API-Only Architecture

Decision: No server-rendered UI. All user-facing flows are API endpoints. Consuming applications render their own UI. A reference UI can be added as a separate project (Phase 7+).


2. Technology Stack

Core

Component Technology Purpose
Language C# 13 / .NET 9+ Application code
Web framework ASP.NET Core 9+ (Minimal APIs) HTTP pipeline
ORM Entity Framework Core 9+ Database access
Database PostgreSQL 16+ Primary data store
Cache Redis 7+ Revocation, rate limiting, sessions
Message queue RabbitMQ (Phase 3+) Event streaming, async processing
Containerization Docker Deployment
API documentation Swashbuckle / NSwag OpenAPI spec generation

Cryptography

Purpose Library
JWT creation/validation System.IdentityModel.Tokens.Jwt + Microsoft.IdentityModel.JsonWebTokens
JWK/JWKS Microsoft.IdentityModel.Tokens
Password hashing (Argon2id) Konscious.Security.Cryptography.Argon2
Password hashing (bcrypt) BCrypt.Net-Next
TOTP/HOTP Otp.NET
General crypto System.Security.Cryptography

Observability

Purpose Library
Structured logging Serilog + JSON sink
Metrics prometheus-net
Distributed tracing OpenTelemetry.Instrumentation.AspNetCore
Health checks AspNetCore.Diagnostics.HealthChecks

Testing

Purpose Library
Unit tests xUnit
Integration tests Microsoft.AspNetCore.Mvc.Testing
Assertions FluentAssertions
Mocking NSubstitute
Test containers Testcontainers (Postgres + Redis)
OIDC conformance OpenID Foundation conformance suite

3. System Architecture

High-Level Component Diagram

┌─────────────────────────────────────────────────────────────────┐
│                        Gatekeeper Server                        │
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌───────────────────────┐  │
│  │  Protocol     │  │  Auth Engine  │  │  Admin API            │  │
│  │  Endpoints    │  │              │  │                       │  │
│  │              │  │  ┌──────────┐│  │  Clients, Users,      │  │
│  │  /authorize  │──│  │Grant     ││  │  Scopes, Tenants,     │  │
│  │  /token      │  │  │Handlers  ││  │  IdP Config, Policies │  │
│  │  /userinfo   │  │  └──────────┘│  │                       │  │
│  │  /revoke     │  │  ┌──────────┐│  └───────────────────────┘  │
│  │  /introspect │  │  │Token     ││                             │
│  │  /jwks       │  │  │Service   ││  ┌───────────────────────┐  │
│  │  /discovery  │  │  └──────────┘│  │  Event System         │  │
│  │  /device     │  │  ┌──────────┐│  │                       │  │
│  │  /par        │  │  │Session   ││  │  Hooks, Webhooks,     │  │
│  │  /ciba       │  │  │Manager   ││  │  Audit Log, Event     │  │
│  │  /register   │  │  └──────────┘│  │  Streaming            │  │
│  └──────────────┘  │  ┌──────────┐│  └───────────────────────┘  │
│                    │  │MFA       ││                             │
│  ┌──────────────┐  │  │Engine    ││  ┌───────────────────────┐  │
│  │  Federation   │  │  └──────────┘│  │  Policy Engine        │  │
│  │  Layer        │  │  ┌──────────┐│  │                       │  │
│  │              │  │  │User      ││  │  RBAC, ABAC, Consent, │  │
│  │  OIDC Adapter│  │  │Service   ││  │  Password Policy,     │  │
│  │  SAML Adapter│  │  └──────────┘│  │  Custom Rules         │  │
│  │  LDAP Adapter│  └──────────────┘  └───────────────────────┘  │
│  │  Custom IdP  │                                               │
│  └──────────────┘                                               │
│                                                                 │
│  ┌────────────────────────────────────────────────────────────┐  │
│  │  Middleware Pipeline                                       │  │
│  │  Rate Limit → CORS → Auth → Audit → Tenant → Endpoint    │  │
│  └────────────────────────────────────────────────────────────┘  │
│                                                                 │
│  ┌────────────────────────────────────────────────────────────┐  │
│  │  Infrastructure Layer                                      │  │
│  │  ┌─────────┐  ┌─────────┐  ┌──────────┐  ┌─────────────┐ │  │
│  │  │Postgres │  │ Redis   │  │ RabbitMQ │  │ SMTP/SMS    │ │  │
│  │  │(EF Core)│  │(Cache)  │  │(Events)  │  │(Providers)  │ │  │
│  │  └─────────┘  └─────────┘  └──────────┘  └─────────────┘ │  │
│  └────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘

Project Structure

src/
├── Gatekeeper.Server/                  # Main ASP.NET Core application
│   ├── Program.cs
│   ├── appsettings.json
│   ├── Endpoints/
│   │   ├── OAuth/                      # /authorize, /token, /revoke, etc.
│   │   ├── OIDC/                       # /userinfo, /discovery, /jwks
│   │   ├── Admin/                      # Admin REST API
│   │   └── Health/
│   ├── Middleware/
│   └── Configuration/
│
├── Gatekeeper.Core/                    # Domain logic (no infrastructure deps)
│   ├── Interfaces/                     # ALL abstractions
│   ├── Models/                         # Domain entities
│   ├── Grants/                         # Grant type handlers
│   ├── Services/
│   ├── Security/                       # Crypto, hashing, key management
│   ├── Policies/
│   ├── Events/
│   └── Validation/
│
├── Gatekeeper.Infrastructure/          # External dependencies
│   ├── Persistence/                    # EF Core, migrations, repositories
│   ├── Cache/                          # Redis implementations
│   ├── Federation/                     # External IdP adapters + mappers
│   ├── Email/
│   ├── Sms/
│   ├── Events/                         # RabbitMQ, webhook dispatch
│   └── Observability/
│
tests/
├── Gatekeeper.Core.Tests/
├── Gatekeeper.Server.Tests/
├── Gatekeeper.Infrastructure.Tests/
└── Gatekeeper.Conformance.Tests/

Key Design Principles

  1. Interface-first, always. Every service has an interface in Gatekeeper.Core/Interfaces/. No concrete dependencies. This is the escape hatch for testability and swapability.

  2. Grant handlers are pluggable. Each OAuth grant type is a separate IGrantHandler registered via DI. Adding a new grant = adding a class + DI registration.

  3. Federation is adapter-based. External IdPs implement IExternalIdpAdapter. Provider-specific claim mapping implements IClaimMapper.

  4. Events everywhere. Every significant action publishes a domain event via IEventPublisher. Consumers (audit, webhooks, streaming) subscribe independently.

  5. Middleware pipeline is ordered and explicit. Rate Limiting → CORS → Correlation ID → Tenant Resolution → Authentication → Audit Logging → Endpoint.

  6. Fail-secure by default. Redis down → DB fallback (never skip revocation). MFA fails → login fails (never bypass). Policy error → deny access.


4. Security Architecture & Threat Model

T-001: Credential Stuffing / Brute Force

Attack: Automated login attempts using leaked credentials or password guessing.

Mitigations:

  • Account lockout after N failed attempts (default: 5 → 15 min lockout, escalating)
  • IP-based rate limiting on auth endpoints
  • Breached password detection (HaveIBeenPwned, k-anonymity)
  • Captcha integration after threshold (hCaptcha/Turnstile)
  • Username enumeration protection (same timing/content for valid/invalid)
  • Structured logging of failed attempts for SIEM alerting

T-002: Token Theft / Replay

Attack: Stolen access or refresh tokens used by unauthorized party.

Mitigations:

  • Short access token lifetime (5-15 min)
  • Refresh token rotation on every use
  • Refresh token reuse detection (revoke entire family on reuse)
  • DPoP support (Phase 5 — sender-constrained tokens)
  • Token revocation endpoint (RFC 7009) + Redis revocation list
  • Audience restriction enforcement (aud claim)
  • Client binding (confidential clients must authenticate for refresh)

T-003: Authorization Code Interception

Mitigations: PKCE required (public clients), single-use codes, 60-second lifetime, strict redirect URI matching, state parameter, RFC 9207 issuer identification.

T-004: Client Impersonation

Mitigations: Admin-only registration (v1), client secrets hashed (Argon2id), secret rotation API, private_key_jwt support, strict redirect URI validation.

T-005: CSRF on Authorization Endpoint

Mitigations: state parameter required, PKCE, anti-CSRF tokens on state-changing endpoints, SameSite=Strict cookies.

T-006: Key Compromise

Mitigations: Key rotation (90-day default), JWKS serves current + previous key, keys encrypted at rest (AES-256-GCM), HSM interface (Phase 8+), OS CSPRNG for key generation, emergency rotation API.

T-007: Injection Attacks

Mitigations: EF Core parameterized queries, strict input validation, structured logging (no string interpolation), Content-Type validation, output encoding, security headers (CSP, X-Content-Type-Options, X-Frame-Options, HSTS).

T-008: Session Fixation / Hijacking

Mitigations: Session ID regeneration on auth state change, session bound to user agent/IP, absolute timeout (12h), idle timeout (30m), session listing/revocation, concurrent session limiting.

T-009: Redis Failure / Cache Poisoning

Mitigations: Redis TLS + auth, revocation falls back to DB (never fail-open), rate limiting falls back to in-memory, cache entries have TTL, no sensitive data in Redis values (JTI + expiry only).

T-010: Supply Chain / Dependency Attacks

Mitigations: Minimal dependencies, dotnet list package --vulnerable in CI, lock file committed, Dependabot scanning, transitive dependency audit.

Security Defaults (Secure Out of the Box)

Setting Default Relaxable?
PKCE required (public clients) Yes No
Access token lifetime 5 minutes Yes (max 60 min)
Refresh token lifetime 24 hours Yes
Refresh token rotation Every use No
Refresh token reuse detection Enabled No
Authorization code lifetime 60 seconds Yes (max 600s)
Account lockout threshold 5 attempts Yes
Password minimum length 12 characters Yes (min 8)
Argon2id memory 64 MB Yes (min 32 MB)
Key rotation period 90 days Yes
Session absolute timeout 12 hours Yes
Session idle timeout 30 minutes Yes
TLS required (production) Yes No
Security headers All enabled Per-header
Audit logging Enabled No

5. Database Design

Core Entity Diagram

┌─────────────┐     ┌──────────────┐     ┌─────────────────┐
│   Tenants    │────<│    Users     │────<│ UserCredentials  │
│  id, name,   │     │  id, email,  │     │ (passwords,     │
│  slug,       │     │  username,   │     │  MFA seeds)     │
│  settings    │     │  status,     │     └─────────────────┘
└─────────────┘     │  metadata    │
       │            └──────────────┘     ┌─────────────────┐
       │                   │────────────<│ UserExternalIds  │
       │                   │────────────<│ Sessions         │
       │                   │────────────<│ Consents         │
       │                                 └─────────────────┘
       │
       │            ┌──────────────┐     ┌─────────────────┐
       ├───────────<│   Clients    │────<│ ClientSecrets    │
       │            │  client_id,  │────<│ ClientRedirectUris│
       │            │  client_type,│────<│ ClientScopes     │
       │            │  grant_types │     └─────────────────┘
       │            └──────────────┘
       │
       ├───────────<│ Scopes (name, display_name, claims)         │
       ├───────────<│ Roles ────< RolePermissions                 │
       ├───────────<│ Groups ────< GroupMembers                   │
       ├───────────<│ IdentityProviders (type, config, mappings)  │
       ├───────────<│ SigningKeys (algorithm, key_data_enc, status)│
       └───────────<│ AuditEvents (event_type, actor, target, IP) │

Token Storage (short-lived, high-churn):
┌────────────────────┐  ┌────────────────────┐  ┌────────────────────┐
│ AuthorizationCodes │  │  RefreshTokens     │  │  DeviceCodes       │
│  code_hash         │  │  token_hash        │  │  device_code_hash  │
│  client_id         │  │  client_id         │  │  user_code         │
│  user_id           │  │  user_id           │  │  client_id         │
│  scopes            │  │  scopes            │  │  scopes            │
│  code_challenge    │  │  family_id         │  │  status            │
│  redirect_uri      │  │  previous_hash     │  │  expires_at        │
│  expires_at        │  │  expires_at        │  └────────────────────┘
│  consumed_at       │  │  revoked_at        │
└────────────────────┘  └────────────────────┘

Key Design Decisions

  • All secrets hashed, never plaintext. Client secrets, authorization codes, refresh tokens, device codes stored as SHA-256 hashes. Plaintext returned to client once on creation.
  • Signing keys encrypted at rest. AES-256-GCM, key-encryption-key from environment variable.
  • Audit events are append-only. No UPDATE or DELETE. Retention handled by scheduled cleanup.
  • Refresh token families. Each chain has a family_id. On reuse detection, all tokens in the family are revoked.
  • Tenant isolation via PostgreSQL schema. Each tenant's data in a separate schema. TenantResolutionMiddleware sets schema context per request.

6. Extensibility Architecture

Every extension point follows the same pattern: interface in Gatekeeper.Core/Interfaces/, default implementation, DI registration supporting multiple implementations.

Extension Points

Extension Point Interface Purpose Phase
Grant Handler IGrantHandler Add new OAuth grant types 1
Password Hasher IPasswordHasher Custom hashing algorithms 1
MFA Provider IMfaProvider TOTP, WebAuthn, SMS, push 2
External IdP Adapter IExternalIdpAdapter Federation with external IdPs 1
Claim Mapper IClaimMapper Provider-specific claim transforms 1
Event Handler IEventHandler React to domain events 1
Policy Evaluator IPolicyEvaluator RBAC, ABAC, custom rules 3
User Store IUserStore Custom user storage backends 6+
Token Enricher ITokenEnricher Custom claims from external sources 3
Auth Flow Step IAuthFlowStep Custom authentication pipeline steps 5+
Notification Provider INotificationProvider Email, SMS, push backends 2
Session Store ISessionStore In-memory, Redis, DB backends 1
Audit Sink IAuditSink Route audit events to destinations 1
Rate Limit Store IRateLimitStore Redis, in-memory, custom backends 1

Event System

Every significant action publishes a strongly-typed domain event. Events are the primary extensibility mechanism.

public enum EventType
{
    // Authentication
    UserLoginAttempted, UserLoginSucceeded, UserLoginFailed, UserLoggedOut,
    MfaChallengeIssued, MfaChallengeCompleted, MfaChallengeFailed,

    // Token lifecycle
    TokenIssued, TokenRefreshed, TokenRevoked, TokenIntrospected,
    RefreshTokenReused,  // Security: possible theft

    // User lifecycle
    UserRegistered, UserEmailVerified, UserPasswordChanged,
    UserPasswordResetRequested, UserAccountLocked, UserAccountUnlocked,
    UserAccountDeleted,

    // Client lifecycle
    ClientCreated, ClientUpdated, ClientSecretRotated, ClientDeleted,

    // Federation
    ExternalIdpLoginAttempted, ExternalIdpLoginSucceeded, ExternalIdpAccountLinked,

    // Admin, Consent, Session
    AdminActionPerformed, ConfigurationChanged,
    ConsentGranted, ConsentRevoked,
    SessionCreated, SessionDestroyed, ConcurrentSessionLimitReached,
}

Hook System (TODO Markers)

The codebase includes structured TODO comments at every future hook point:

// TODO:HOOK:PRE_REGISTRATION — Phase 5: Pre-registration validation hook
// TODO:HOOK:POST_LOGIN — Phase 5: Post-login action hook
// TODO:HOOK:PRE_TOKEN_ISSUE — Phase 5: Custom claims enrichment hook
// TODO:HOOK:POST_CONSENT — Phase 5: Post-consent action hook
// TODO:HOOK:EXTERNAL_CALLOUT — Phase 6: HTTP callout during auth flow

7. Feature Inventory (All Phases)

Complete inventory from the comprehensive feature list. Every feature assigned to a phase. (STUB) = interface and TODO from Phase 1, implementation deferred.

Authentication

Feature Phase Notes
Password Authentication 1 Core
Username Enumeration Protection 1 Same timing/content
Brute-Force Detection and Account Lockout 1 Configurable
Email Verification 2 Mandatory/optional modes
Self-Service Password Reset 2 Token-based
Self-Registration / Sign-Up 2 API endpoint
OTP via Authenticator App (TOTP) 2 RFC 6238
Backup/Recovery Codes 2 One-time use
MFA — Enforced / Optional / Conditional 2 Per-tenant policy
MFA Recovery Flow 2 Via backup codes
Login Hint Support 2 login_hint param
MFA Grace Period / Remember Device 3 Cookie/fingerprint
MFA Challenge Selection 3 User picks factor
Re-Authentication / Step-Up 3 acr_values, max_age
Remember Me / Persistent Sessions 3 Extended lifetime
Password Confirmation on Sensitive Actions 3
SSO Session Management 3
Social Login / Social IdPs 4 Via federation
Account Linking 4 Merge identities
Captcha Integration 4 hCaptcha, Turnstile
Account Self-Service Deletion 4 GDPR
FIDO2/WebAuthn Passwordless 5 (STUB from Phase 1)
Passkey Support 5 Synced + device-bound
Email Magic Link 5 Passwordless flow
Email OTP 5
OTP via SMS 5 Twilio
Identifier-First Login Flow 5
Device Fingerprinting 5 Risk signal
Impersonation / Act-As-User 5 Admin, audit-logged
Adaptive Authentication (risk-based) 6 Risk scoring engine
OTP via Voice Call 6 (STUB)
OTP via Hardware Token (HOTP) 6 RFC 4226
Push Notification Auth 6 (STUB)
Progressive Profiling 6 (STUB)
Sign-Up Approval Workflow 6 (STUB)
Self-Service Account Recovery 2 Email + backup codes
Custom Authentication Flows 7 Visual designer Phase 9+
Certificate-Based Auth (X.509/mTLS) 7 (STUB)
LDAP Bind Authentication 7 Via federation
Device Trust / Posture Checks 7 (STUB)
Kerberos Authentication 8+ (STUB)
Smart Card Authentication 8+ (STUB)

Authorization

Feature Phase Notes
Client Credentials Grant 1 Core MVP
Token Exchange (RFC 8693) 1 Core MVP
Token Introspection (RFC 7662) 1
Token Revocation (RFC 7009) 1
Scope-Based Access Control 1 Core
Audience Restriction Enforcement 1 aud claim
Authorization Code Grant (RFC 6749) 2
Authorization Code + PKCE (RFC 7636) 2 Required for public
Refresh Token Grant 2 With rotation
Consent Management 2 Per-scope
Consent Revocation 3
RBAC 3
Group-Based Access Control 3
API Resource Server Registration 3
Device Authorization Grant (RFC 8628) 4 TV/IoT
PAR (RFC 9126) 4
OIDC Back-Channel Logout 4
OIDC Front-Channel Logout 4
Delegated Authorization (on-behalf-of) 4
Implicit Grant (legacy) 4 Disabled by default
ROPC Grant (legacy) 4 Disabled by default
Dynamic Scope Resolution 4
JWT Authorization Grants (RFC 7523) 5
Hierarchical / Nested Groups 5
Role Hierarchies 5
Organization / Multi-Tenant Policies 5
ABAC 6 (STUB)
PBAC 6
Custom Policy Engine 6
Fine-Grained Permissions 6
Permission Evaluation API 6
Rules Engine 6
RAR (RFC 9396) 7 (STUB)
UMA 2.0 8+ (STUB)
Transaction-Level Authorization 8+ (STUB)

Tokens & Credentials

Feature Phase Notes
Access Token (JWT) 1 Core
JWKS Endpoint 1
JWKS Rotation 1
Configurable Token Lifetimes 1 Per-client
Audience-Restricted Tokens 1
ID Token Generation (OIDC) 2
Refresh Token Generation 2
Refresh Token Rotation 2 Every use
Refresh Token Reuse Detection 2 Revoke family
Token Claims Mapping / Custom Claims 2
JWT Access Token Profile (RFC 9068) 2
PKCE (RFC 7636) 2
Client Secret Rotation 2
Userinfo Endpoint (OIDC) 2
Access Token (opaque format) 3 Optional per-client
Client Assertion Auth 3 private_key_jwt, client_secret_jwt
Session Token / SSO Cookie 3
Token Claims Enrichment 4 Via ITokenEnricher
Pairwise Subject Identifiers 4
DPoP (RFC 9449) 5 (STUB from Phase 1)
Access Token Encryption (JWE) 5
ID Token Encryption (JWE) 5
Sender-Constrained Tokens 5 Via DPoP
mTLS Certificate-Bound Tokens (RFC 8705) 7 (STUB)
Token Binding 7 (STUB)

Client / Application Management

Feature Phase Notes
Client Registration (admin) 1 Admin API
Confidential Client Support 1
Public Client Support 1
Redirect URI Validation (strict) 1 Exact match
M2M Client Type 1 Client credentials
First-Party vs Third-Party 2 Skip consent for first-party
Service Account per Client 2
SPA Client Type 2
Native / Mobile Client Type 2
Sector Identifier URI 4
Dynamic Client Registration (RFC 7591) 5
Dynamic Registration Management (RFC 7592) 5
Redirect URI Wildcard / Pattern 5 Strict validation
Software Statement Validation 6

Identity Federation & Providers

Feature Phase Notes
Generic OIDC Provider Adapter 1 Core — adapter pattern
Planning Center Online 1 First provider
OIDC Discovery for Upstream IdPs 1 Auto-configure
Social Provider Mappers 1 IClaimMapper
JIT User Provisioning from IdPs 2 Create on first login
Identity Brokering 3 Proxy auth upstream
Google, Microsoft/Entra, Apple, GitHub 4 Mapper + config
Azure AD / Entra ID (via OIDC) 4
Facebook, LinkedIn, GitLab 5
Automated IdP Discovery (email domain) 5
IdP-Initiated SSO 5
Slack, Twitter/X 6
SAML 2.0 IdP + SP Support 7 (STUB interface Phase 1)
SAML Metadata Import/Export 7
LDAP / Active Directory Federation 7
CAS Protocol 8+ (STUB)
WS-Federation 8+ (STUB)

Protocol Support

Feature Phase Notes
OAuth 2.0 (RFC 6749) 1–2 Core
OIDC Discovery 1 Required from day one
OIDC Core 1.0 2
OAuth 2.1 compliance 3 Enforce PKCE, no implicit/ROPC default
OIDC Session Management 3
OIDC Back/Front-Channel Logout 4
OIDC Dynamic Client Registration 5
SCIM 2.0 6 Inbound and outbound
SAML 2.0 7
CIBA 7 (STUB)
mTLS 7
FAPI 1.0 / 2.0 8+ (STUB)
RADIUS, WS-Federation, WS-Trust 8+ (STUB)

Multi-Tenancy & Organizations

Feature Phase Notes
Multi-Tenant Architecture (schema isolation) 1 Designed from day one
Per-Tenant IdP Configuration 3
Organization CRUD API 3
Organization Membership 3
Org-Level Role Assignments 3
Org-Level MFA Policies 4
Org-Level Password Policies 4
Invitation-Based Tenant Onboarding 4
Tenant-Level Feature Flags 5
Per-Tenant Branding/Config 5
Hierarchical Org Structure 6
Custom Domain per Tenant 6

User Management

Feature Phase Notes
User CRUD (Admin API) 1 Core
User Search (full-text) 2
User Status Workflow 2 pending → active → suspended → deleted
User Block / Suspend / Disable 2
User Lifecycle Management 2
User Metadata 2
Admin-Initiated Password Reset 2
User Credential Management 2
Role Assignment (user + group) 3
Group Management (CRUD) 3
Custom User Profile Fields 3 JSON metadata
User Attribute Mapping 3
Self-Service Profile Management 3
Session Listing/Revocation (per user) 3
User Consent History 3
Attribute Schema Extension 4
Linked Accounts View 4
Bulk User Import/Export 5
Managed Service Accounts 5
Dynamic Group Membership Rules 6
Inactive User Detection/Cleanup 6
User Migration (lazy) 6
Directory Sync (AD/LDAP) 7

Password Policy & Credential Management

Feature Phase Notes
Argon2id Hashing 1 Default
Bcrypt Support (migration) 1
Configurable Algorithm and Cost 1
Minimum Password Complexity 1
Scrypt / PBKDF2 Support 3
Password History (prevent reuse) 3
Max Password Age / Forced Rotation 4
Dictionary-Based Rejection 4
Breached Password Detection (HIBP) 4 k-anonymity
Custom Password Policy Rules 5
Password Strength Meter 5 API-provided score

Session Management

Feature Phase Notes
Session Creation and Storage 1 Redis + DB fallback
Absolute Session Timeout 1
Idle Session Timeout 1
Configurable Session Lifetimes 1
Session Clustering (Distributed) 1 Via Redis
Session Storage Backends 1 ISessionStore
Session Revocation (single/all/device) 3
Session Listing (admin + self-service) 3
Concurrent Session Limiting 3
Sliding Session Expiry 3
SSO Session Sharing 3
Device-Bound Sessions 5
Offline Session Support 5

Consent & Privacy

Feature Phase Notes
Consent Prompt (API data) 2 Scope details, client info
Consent Record Storage/Audit 2
Per-Scope Consent Granularity 2
Privacy Policy Link per Client 2
Consent Revocation 3
Terms of Service Tracking 3
Right to Be Forgotten (GDPR) 4
User Data Export (GDPR portability) 4
GDPR Compliance Tooling 4
Consent Prompt Customization 5 Per-client
DSAR Automation 6
DPA Support 6
HIPAA Compliance Mode 8+ (STUB)

Branding & Customization

Feature Phase Notes
Custom Email Templates (HTML) 2
Custom SMS Templates 5
i18n / Multi-Language 5 API returns localized strings
Per-Client Branding (API data) 5
Logo/Favicon Customization 5
Custom Error Pages 5 API error contracts
Custom Domain / Vanity URL 6
Custom CSS / Theme Editor 7 Reference UI project
Dark Mode 7 Reference UI
Full White-Labeling 7
Hosted Login Page 7 Reference UI
Embeddable Login Widget/SDK 7 React, Vue, Angular

Extensibility & Customization

Feature Phase Notes
Plugin / Extension Architecture 1 Interfaces from day one
Custom Password Hashers 1 IPasswordHasher
Custom IdP Connectors 1 IExternalIdpAdapter
Custom MFA Providers 2 IMfaProvider
Custom Token Mappers 3
Webhook Event System 3
Custom Event Handlers 3
Custom Claim Providers 4 ITokenEnricher
Actions / Hooks (pre/post-event) 5
Pre-Registration Hooks 5
Post-Login Actions 5
Middleware / Pipeline Hooks 5
Custom User Storage (SPI) 6 IUserStore
External HTTP Callouts 6
Rules Engine 6
Expression Language (CEL/Rego) 7
OPA Integration 7 (STUB)
Custom Auth Flow Steps 7 IAuthFlowStep
Lambda / Serverless Triggers 7
Terraform Provider 8+
Scripting in Flows 9+
Visual Flow Designer 9+

API & Developer Experience

Feature Phase Notes
Admin REST API (full CRUD) 1 Core
OpenAPI / Swagger Spec 1 Auto-generated
API Rate Limiting 1
API Versioning 1 /v1/ prefix
Health Check Endpoints 1 Liveness + readiness
Docker Deployment 1
Postman Collection 2 From OpenAPI
API Explorer / Swagger UI 3
Management API Scoped Permissions 3
Rate Limiting per Client/Endpoint 3
API Key Auth (M2M) 3
Server-Side SDK (Token Verification) 4 .NET package
Bulk Operations 5
CLI Tool 6
SDK Auto-Generation 6 From OpenAPI
Client SDKs (JS, Python, Go) 6+
Helm Chart 6
Embedded Login Components 7 React, Vue, Angular
GraphQL API 8+ (STUB)
IaC (Terraform, Pulumi) 8+

Security

Feature Phase Notes
Anti-CSRF Enforcement 1
CORS Configuration 1 Per-client + global
Security Headers 1 HSTS, CSP, X-Frame, etc.
IP-Based Rate Limiting 1
Key Rotation 1
TLS 1.2+ 1
OWASP Top 10 Mitigations 1 Ongoing
Encrypted Data at Rest 1 Keys, secrets
DDoS Protection (rate limiting) 1
Token Replay Prevention 2
Account Takeover Protection 3
Vulnerability Scanning (CI) 3
IP Allowlist/Denylist 4
Credential Stuffing Detection 4
Bot Detection / Captcha 4
Suspicious Activity Detection 5
Phishing-Resistant Auth Enforcement 5 WebAuthn
Cross-Origin Isolation 5
Secrets Management (Vault) 6 (STUB)
Log Tamper Detection 6
mTLS Enforcement 7
Certificate Pinning 7
HSM Integration 8+ (STUB interface Phase 1)
FIPS 140-2 8+ (STUB)
Threat Intelligence Feeds 8+ (STUB)

Audit, Logging & Accounting

Feature Phase Notes
Authentication Event Logging 1
Structured Logging (JSON) 1
Correlation ID Logging 1
Admin Action Audit Trail 1
Token Issuance Logging 1
Failed Login Tracking 1
Authorization Decision Logging 2
Audit Log Search/Filtering 3 Admin API
Audit Log Retention Policies 3
Login/Logout History per User 3
User Activity Timeline 4
Audit Log Export (CSV, JSON) 4
Real-Time Event Stream (SSE/WS) 5
Event Streaming (Kafka, EventBridge) 5
SIEM Integration 5
Syslog Forwarding 5
Compliance Reporting (SOC 2, ISO) 7

Monitoring & Observability

Feature Phase Notes
Health Checks (liveness, readiness) 1
Prometheus Metrics 2
OpenTelemetry Tracing 3
Performance Monitoring (latency) 3
Active Session Count Metric 3
Alerting Rules 4
Grafana Dashboards 4
Custom Dashboards 6
SLA / Uptime Monitoring 6
System Status Page 7

Deployment & Operations

Feature Phase Notes
Docker Compose 1
Self-Hosted / On-Prem 1
DB Migrations (EF Core) 1
Graceful Shutdown / Drain 1
Backup and Restore 2
Config as Code (YAML/JSON) 2
CI/CD (GitHub Actions) 2
Reverse Proxy Docs (Nginx) 2
Horizontal Scaling 3 Stateless app
Environment Promotion 3
HA Clustering 4
Blue-Green / Canary 4
Rolling Upgrades (zero downtime) 4
Feature Flags 5
Hot Config Reload 5
S3 Blob Storage 5
Auto-Scaling Docs 6
Helm Chart 6
Offline / Air-Gapped 6
DB Backend Support (MySQL) 6 Via EF Core
Active-Active Clustering 7
Migration Tooling (from other IdPs) 7
K8s Operator 8+
Cross-Region Replication 8+
Multi-Region Deployment 8+

Integration Ecosystem

Feature Phase Notes
SMTP Email 2
Reverse Proxy (Nginx) 2
CI/CD (GitHub Actions) 2
SendGrid, SES 4
SMS (Twilio) 5
Notification Providers 5
Kong / API Gateway Plugin 6
K8s OIDC Integration 6
SCIM Outbound Provisioning 6
SMS (Vonage, MessageBird) 6
LDAP/AD Connector 7
Cognito Migration Path 7
Service Mesh (Istio, Linkerd) 8+
Cloud IAM Integration 8+
HRIS Integration 8+
Zero Trust Integration 8+

8. Phased Implementation Plan

Phase 1: Foundation & Core Token Engine (Weeks 1–6)

Goal: Working OAuth server — Client Credentials, Token Exchange, introspection, revocation, discovery, JWKS. Admin API for clients/users/scopes. Full extensibility architecture in place.

Endpoints:

  • POST /connect/token (client_credentials, token_exchange)
  • POST /connect/revoke (RFC 7009)
  • POST /connect/introspect (RFC 7662)
  • GET /.well-known/openid-configuration
  • GET /.well-known/jwks
  • GET /health/live, GET /health/ready
  • Admin: /api/v1/clients, /api/v1/users, /api/v1/scopes, /api/v1/identity-providers, /api/v1/signing-keys

Architecture delivered:

  • 3-project solution (Server, Core, Infrastructure)
  • ALL interface definitions for every extension point (grants, MFA, IdP, hashers, events, policies, sessions, audit, rate limiting, key mgmt, consent, token enrichers, auth flows, notifications, user stores, claim mappers)
  • TODO:HOOK markers throughout codebase
  • EF Core DbContext with full schema (including future-phase tables)
  • PostgreSQL migrations
  • Redis integration (revocation, rate limiting, sessions)
  • Docker Compose (Gatekeeper + Postgres + Redis)
  • Serilog structured logging (JSON)
  • All middleware (rate limiting, CORS, security headers, correlation ID, tenant resolution, audit)
  • Key management (ES256/RS256, rotation, JWKS, encryption at rest)
  • Password hashing (Argon2id + bcrypt)
  • Generic OIDC external IdP adapter + Planning Center mapper
  • Event system (publish + in-process audit subscriber)
  • Integration test harness (WebApplicationFactory + Testcontainers)

Phase 2: OIDC Core & User Flows (Weeks 7–14)

Goal: Full OIDC Core compliance. Users register, login, MFA (TOTP), reset passwords. Apps get ID tokens and user info.

Endpoints added:

  • GET /connect/authorize
  • POST /connect/token (authorization_code, refresh_token grants)
  • GET /connect/userinfo
  • POST /connect/end-session
  • User API: /api/v1/auth/register, login, verify-email, reset-password, mfa/setup, mfa/verify

Features: Auth Code + PKCE, refresh token rotation + reuse detection, ID tokens, TOTP MFA + backup codes, consent flow, JWT Access Token Profile (RFC 9068), custom claims mapping, user status workflow, JIT provisioning, client secret rotation, Prometheus metrics, SMTP email, CI pipeline, Postman collection.

Phase 3: Sessions, RBAC, Organizations & Webhooks (Weeks 15–22)

Goal: Multi-tenant organizations, RBAC/groups, session management, webhooks, operational maturity.

Features: Per-tenant IdP config, organization CRUD, RBAC + groups, session mgmt (listing, revocation, concurrent limits, SSO), consent revocation, step-up auth, webhook system, admin 2FA/RBAC, audit log search, OpenTelemetry tracing, OAuth 2.1 hardening, identity brokering, opaque token format, client assertion auth, API key auth.

Phase 4: Extended Grants, Social Providers & Privacy (Weeks 23–32)

Goal: Device grant, PAR, social IdPs, GDPR, logout protocols, breach detection.

Features: Device Authorization Grant (RFC 8628), PAR (RFC 9126), back/front-channel logout, delegated auth, implicit + ROPC (legacy, disabled), Google/Microsoft/Apple/GitHub social login, account linking, GDPR (deletion, export, compliance tooling), breached password detection (HIBP), pairwise subjects, captcha, credential stuffing detection, IP allowlist/denylist, Grafana dashboards, HA clustering, blue-green deployment.

Phase 5: Advanced Auth, Encryption & Extensibility (Weeks 33–44)

Goal: WebAuthn/passkeys, DPoP, JWE, dynamic client registration, hooks, i18n.

Features: FIDO2/WebAuthn, passkeys, email magic link, email OTP, SMS OTP, identifier-first login, device fingerprinting, impersonation, DPoP (RFC 9449), JWE (access + ID tokens), dynamic client registration (RFC 7591/7592), JWT authorization grants (RFC 7523), hooks system (pre/post events), i18n, per-client branding, feature flags, SIEM integration, event streaming, bulk user import/export.

Phase 6: Policy Engine, SCIM, CLI & Enterprise (Weeks 45–56)

Goal: ABAC, policy engine, SCIM, CLI, advanced enterprise features.

Features: ABAC/PBAC, custom policy engine, fine-grained permissions, permission evaluation API, SCIM 2.0 (inbound + outbound), CLI tool, SDK auto-generation, custom user storage (SPI), external HTTP callouts, dynamic groups, lazy user migration, adaptive authentication, risk scoring, sign-up approval, Vault integration, Helm chart, Kong plugin.

Phase 7: SAML, LDAP, mTLS, Admin UI & Legacy (Weeks 57–72)

Goal: Enterprise federation, mTLS, reference admin UI, compliance.

Features: SAML 2.0 (IdP + SP), LDAP/AD federation + directory sync, mTLS client auth + certificate-bound tokens, CIBA, RAR (RFC 9396), custom auth flows, expression language (CEL/Rego), OPA integration, admin console UI (React), theme editor, white-labeling, hosted login page, migration tooling, compliance reporting (SOC 2, ISO 27001).

Phase 8+: Exotic Protocols, FAPI, HSM (Weeks 73+)

Goal: Full Keycloak parity — FAPI, HSM, exotic protocols, enterprise-grade deployment.

Features: FAPI 1.0/2.0, FIPS 140-2, HSM (CloudHSM, Azure Key Vault), UMA 2.0, Kerberos, smart card, CAS, WS-Federation, WS-Trust, RADIUS, HIPAA, Terraform provider, K8s operator, GraphQL API, cross-region replication, multi-region, service mesh, cloud IAM, HRIS, zero trust.

Phase 9+: Visual Designers & Scripting (Future)

Visual auth flow designer, form-based flow customization, WYSIWYG theme editor, Groovy/JS/Python scripting in flows.


9. Claude Code Task Breakdown

Task Sizing

Each task completable in one Claude Code session. Marked with recommended model tier.

Phase 1 Tasks (46 tasks, ~52 sessions)

Foundation (1.01–1.10)

Task Description Model
1.01 Solution structure (3 projects, test projects, Docker) Sonnet
1.02 EF Core + Npgsql, DbContext with tenant schema support Sonnet
1.03 ALL interfaces in Core/Interfaces/ (~20 interfaces) Opus
1.04 ALL domain models in Core/Models/ (~20 entities) Opus
1.05 EF Core entity configurations + initial migration Sonnet
1.06 Docker Compose (Gatekeeper + Postgres 16 + Redis 7) Sonnet
1.07 Serilog config (JSON, correlation ID enricher) Sonnet
1.08 CorrelationIdMiddleware Haiku
1.09 ASP.NET Core DI registration for all services Sonnet
1.10 appsettings.json schema with all configurable options Sonnet

Security & Crypto (1.11–1.18)

Task Description Model
1.11 KeyManager (ES256/RS256 generation, storage, rotation, JWKS) Opus
1.12 Argon2idPasswordHasher + BcryptPasswordHasher Opus
1.13 SecurityHeadersMiddleware Sonnet
1.14 Anti-CSRF token generation and validation Opus
1.15 Rate limiting middleware (Redis, IP + endpoint) Opus
1.16 CORS middleware (per-client + global defaults) Sonnet
1.17 Audit logging middleware + IAuditSink (DB sink) Sonnet
1.18 Signing key encryption at rest (AES-256-GCM) Opus

Core Token Engine (1.19–1.28)

Task Description Model
1.19 TokenService (JWT creation, claims, signing, lifetime) Opus
1.20 ClientCredentialsGrantHandler Opus
1.21 TokenExchangeGrantHandler (RFC 8693) Opus
1.22 Token revocation (RFC 7009) — endpoint + Redis + DB fallback Opus
1.23 Token introspection (RFC 7662) — endpoint + revocation check Opus
1.24 OIDC Discovery endpoint (/.well-known/openid-configuration) Sonnet
1.25 JWKS endpoint with rotation support Opus
1.26 POST /connect/token endpoint (route to grant handlers) Sonnet
1.27 Client authentication (client_secret_basic, client_secret_post) Opus
1.28 Audience restriction enforcement Opus

Admin API (1.29–1.34)

Task Description Model
1.29 Client CRUD (/api/v1/clients) Sonnet
1.30 User CRUD (/api/v1/users) Sonnet
1.31 Scope CRUD (/api/v1/scopes) Sonnet
1.32 Signing Key management (list, rotate, revoke) Sonnet
1.33 Admin API authentication (bootstrap API key from env) Opus
1.34 OpenAPI/Swagger configuration Sonnet

Federation (1.35–1.38)

Task Description Model
1.35 OidcExternalIdpAdapter (generic OIDC, auto-discovery) Opus
1.36 PlanningCenterMapper (claim mapping) Sonnet
1.37 IClaimMapper interface + registration pattern Sonnet
1.38 Identity Provider CRUD (/api/v1/identity-providers) Sonnet

Infrastructure (1.39–1.42)

Task Description Model
1.39 Health check endpoints (liveness, readiness) Sonnet
1.40 Tenant resolution middleware Sonnet
1.41 Redis session store + in-memory fallback Sonnet
1.42 Event system (IEventPublisher, dispatcher, audit subscriber) Sonnet

Testing (1.43–1.46)

Task Description Model
1.43 Integration test harness (WebApplicationFactory + Testcontainers) Sonnet
1.44 Tests: Client Credentials flow (happy path + errors) Opus
1.45 Tests: Token Exchange flow (happy path + errors) Opus
1.46 Tests: Revocation, introspection, JWKS, discovery Sonnet

Phase 2–8 Session Estimates

Phase Focus Est. Tasks Est. Sessions
2 OIDC Core, User Flows, MFA ~41 ~49
3 Sessions, RBAC, Orgs, Webhooks ~45 ~55
4 Device Grant, PAR, Social IdPs, Privacy ~50 ~65
5 WebAuthn, DPoP, JWE, Dynamic Reg, Hooks ~55 ~70
6 Policy Engine, SCIM, CLI, Enterprise ~50 ~65
7 SAML, LDAP, mTLS, Admin UI ~60 ~80
8+ FAPI, HSM, UMA, Exotic Protocols ~40 ~55
9+ Visual Designers, Scripting ~20 ~25
TOTAL ~407 ~516

Per-Phase Task Generation Prompt

At the start of each phase, use this in Claude Code:

Read CLAUDE.md and IMPLEMENTATION_PLAN.md Phase [N] feature list.
Generate a detailed task breakdown following the Phase 1 format:
- One task per Claude Code session
- Mark each: Opus (security/crypto/protocol), Sonnet (CRUD/infra), Haiku (file ops)
- Include integration test tasks for every endpoint
Save as PHASE_[N]_TASKS.md

10. Model Delegation Strategy

Opus (~35% of sessions) — Security-Critical

JWT signing/validation, grant handlers, PKCE, token revocation/reuse detection, password hashing, key management, client authentication, CSRF, rate limiting logic, external IdP federation, MFA, session security, consent enforcement, RFC implementations, architecture decisions, threat model updates, security integration tests.

Sonnet (~55% of sessions) — Standard Implementation

Admin API CRUD, database migrations, non-security middleware, Docker/CI/CD, OpenAPI, health checks, email/SMS templates, metrics, config loading, CRUD integration tests, documentation.

Haiku (~10% of sessions) — File Operations

Directory scanning, grepping, file reading, string replacements, boilerplate, formatting, linting, package listing.

Cost Rules

  1. Start every phase with Haiku scanning project state
  2. Sonnet for scaffolding, Opus for security logic within it
  3. Never Opus for CRUD
  4. Always Opus for crypto and protocol code
  5. Sonnet for tests unless security flow (then Opus)
  6. Haiku for multi-file search-and-replace

11. Testing Strategy

Test Pyramid

         ╱╲           OIDC Conformance (Phase 2+)
        ╱  ╲
       ╱────╲         E2E Tests (Phase 3+) — Docker Compose
      ╱      ╲
     ╱────────╲       Integration Tests (Phase 1+) — Testcontainers
    ╱          ╲
   ╱────────────╲     Unit Tests (Phase 1+) — Mocked deps
  ╱──────────────╲

Every Feature Must Have

  1. Unit tests for domain logic
  2. Integration tests for HTTP endpoints
  3. Security tests for every security control
  4. Negative tests (missing params, invalid tokens, unauthorized clients)

OIDC Conformance Targets

  • Phase 2: Basic OP
  • Phase 3: Session Management OP
  • Phase 4: Back/Front-Channel Logout OP
  • Phase 5: Dynamic OP
  • Phase 7+: FAPI 1.0

Security Test Checklist (Every Phase)

  • Revoked tokens rejected
  • Expired tokens rejected
  • Invalid signatures rejected
  • PKCE wrong verifier rejected
  • Rate limiting triggers at threshold
  • Account lockout triggers at threshold
  • Username enumeration identical responses
  • CSRF blocks cross-origin requests
  • Security headers on all responses
  • Redirect URI rejects non-registered URIs
  • Client auth rejects invalid credentials
  • Audit log records all security events

12. Deployment & Operations

Docker Compose (Phase 1)

services:
  gatekeeper:
    build: .
    ports: ["5000:8080"]
    environment:
      - GATEKEEPER__Database__ConnectionString=Host=postgres;Database=gatekeeper;...
      - GATEKEEPER__Redis__ConnectionString=redis:6379
      - GATEKEEPER__Security__KeyEncryptionKey=${KEK}
    depends_on:
      postgres: { condition: service_healthy }
      redis: { condition: service_healthy }
  postgres:
    image: postgres:16-alpine
    healthcheck: { test: ["CMD-SHELL", "pg_isready -U gatekeeper"] }
  redis:
    image: redis:7-alpine
    command: redis-server --requirepass ${REDIS_PASSWORD}

Container Hardening

Non-root user, read-only filesystem, no shell, mcr.microsoft.com/dotnet/aspnet:9.0-noble-chiseled, multi-stage build, no secrets in layers.

Configuration Hierarchy

  1. appsettings.json (defaults — committed)
  2. appsettings.{Env}.json (env-specific — committed)
  3. Environment variables (secrets — NOT committed)
  4. GATEKEEPER__* prefix for all config

Backup & Recovery

  • Database: pg_dump daily, WAL archiving for PITR
  • Signing keys: Encrypted export via Admin API
  • Configuration: Version controlled
  • Redis: Not backed up (ephemeral; rebuildable from DB)

13. RFC & Standards Reference

Core Standards

Standard Title Phase
RFC 6749 OAuth 2.0 Authorization Framework 1–2
RFC 6750 Bearer Token Usage 1
RFC 7009 Token Revocation 1
RFC 7517 JSON Web Key (JWK) 1
RFC 7518 JSON Web Algorithms (JWA) 1
RFC 7519 JSON Web Token (JWT) 1
RFC 7523 JWT Profile for Client Auth 5
RFC 7591 Dynamic Client Registration 5
RFC 7592 Dynamic Client Reg Management 5
RFC 7636 PKCE 2
RFC 7662 Token Introspection 1
RFC 8414 Auth Server Metadata 1
RFC 8628 Device Authorization Grant 4
RFC 8693 Token Exchange 1
RFC 8705 mTLS Certificate-Bound Tokens 7
RFC 9068 JWT Access Token Profile 2
RFC 9101 JWT-Secured Auth Request (JAR) 5
RFC 9126 PAR 4
RFC 9207 Auth Server Issuer ID 1
RFC 9396 Rich Authorization Requests 7
RFC 9449 DPoP 5
OIDC Core 1.0 OpenID Connect Core 2
OIDC Discovery 1.0 Discovery 1
OIDC Session Mgmt 1.0 Session Management 3
OIDC Front-Channel Logout Logout 4
OIDC Back-Channel Logout Logout 4
OIDC Dynamic Registration Client Registration 5
SCIM 2.0 (RFC 7642–7644) Identity Management 6
SAML 2.0 Assertion Markup 7
FAPI 1.0 / 2.0 Financial-Grade API 8+

Security References

Standard Title Phase
RFC 6238 TOTP 2
RFC 4226 HOTP 6
WebAuthn Level 2 Web Authentication 5
OWASP ASVS 4.0 App Security Verification Ongoing
NIST SP 800-63B Digital Identity Guidelines Ongoing

14. Open Questions & Future Considerations

Open Questions

  1. Project name: "Gatekeeper" is a working name. Check trademark conflicts before public release.

  2. License: Apache 2.0 recommended if open-sourcing (permissive, patent grant, enterprise-friendly).

  3. Planning Center OAuth specifics: Verify discovery endpoint, scopes, claim format, refresh behavior. Test against sandbox before Phase 1 completion.

  4. Admin API bootstrap: How does the first admin authenticate before any clients exist? Recommended: seed migration creates initial admin client with credentials from environment variable.

  5. Email provider: SMTP default for Phase 2. Decide on transactional service (SendGrid/SES) for deliverability.

  6. Test environment: Testcontainers for CI. Consider docker-compose-test.yml for local dev.

Future Considerations

  • Managed cloud offering: Architecture supports hosted SaaS (multi-tenant built in). Would require billing, metering, SLA.
  • Mobile SDKs: Headless API design enables Swift/Kotlin SDKs (Phase 6+).
  • Edge deployment: Cloudflare Workers for JWKS caching and token validation at edge.
  • Community plugins: Extension architecture designed for third-party plugins.

Appendix A: Keycloak Discovery Parity Checklist

Discovery Field Phase
issuer 1
authorization_endpoint 2
token_endpoint 1
introspection_endpoint 1
userinfo_endpoint 2
end_session_endpoint 2
jwks_uri 1
registration_endpoint 5
revocation_endpoint 1
device_authorization_endpoint 4
pushed_authorization_request_endpoint 4
backchannel_authentication_endpoint 7
grant_types_supported (all 9) 1–7
response_types_supported (all 8) 2–4
subject_types_supported (public, pairwise) 1, 4
id_token_signing_alg_values_supported (13) 1–2
id_token_encryption_alg/enc 5
userinfo_signing_alg/encryption 2, 5
token_endpoint_auth_methods (5) 1–7
claims_supported (14) 2
scopes_supported 1
code_challenge_methods (plain, S256) 2
dpop_signing_alg_values 5
backchannel_logout_supported 4
frontchannel_logout_supported 4
require_pushed_authorization_requests 4
tls_client_certificate_bound 7
mtls_endpoint_aliases 7
authorization_response_iss_parameter 1
response_modes_supported (7) 2–5
prompt_values_supported 2

Appendix B: Feature Count Summary

Domain Total Ph1 Ph2 Ph3 Ph4 Ph5 Ph6 Ph7 Ph8+
Authentication 38 3 7 5 3 8 4 4 4
Authorization 28 5 3 4 6 4 4 1 1
Tokens 24 6 6 3 2 5 0 2 0
Client Mgmt 14 5 3 0 1 3 1 0 1
Federation 24 4 1 1 5 5 2 5 1
Protocols 18 3 1 1 2 2 1 4 4
Multi-Tenancy 12 1 0 3 2 2 2 0 2
User Mgmt 24 1 5 5 2 3 4 2 2
Password 9 3 0 2 3 1 0 0 0
Sessions 12 4 0 5 0 2 0 0 1
Consent 12 0 3 2 3 1 2 0 1
Branding 14 0 1 0 0 5 1 6 1
Extensibility 22 3 1 2 1 5 3 4 3
API/DevEx 17 4 1 3 1 0 4 1 3
Security 28 8 1 2 4 3 2 3 5
Audit/Logging 17 5 1 3 2 3 1 1 1
Monitoring 10 2 1 2 2 0 2 1 0
Deployment 22 4 2 2 2 3 3 2 4
Integrations 15 0 2 0 1 2 4 2 4
TOTAL ~400 ~61 ~40 ~45 ~42 ~57 ~40 ~38 ~38

End of Implementation Plan.