Fable test
This commit is contained in:
@@ -0,0 +1,455 @@
|
||||
# SOR.Auth 12-Factor Refactor Plan
|
||||
|
||||
Date: 2026-06-10
|
||||
|
||||
Scope reviewed:
|
||||
- `Server/src/SOR.Auth`
|
||||
- `Server/src/SOR.Shared.Proto/Protos/auth.proto`
|
||||
- Identity persistence in `Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs`
|
||||
- Identity entities under `Server/src/SOR.Database/Entities/Identity`
|
||||
- Auth and gRPC wiring in `Server/src/SOR.Host`
|
||||
|
||||
Reference: https://12factor.net/
|
||||
|
||||
## Executive Summary
|
||||
|
||||
`SOR.Auth` has a solid base for a 12-Factor service. It is a service module, is enabled by host process formation, exposes a gRPC contract, uses ASP.NET Core Identity for password and lockout behavior, stores durable session records in PostgreSQL, caches active session tokens in Redis, and validates Keycloak tokens through OIDC discovery.
|
||||
|
||||
The main issue is structure. `AuthGrpcHandler.cs` currently contains transport handling, login/register workflows, session creation, token hashing, Redis cache behavior, account-property persistence, Keycloak account linking, OAuth feature-flag checks, and response mapping. That makes the service harder to test, harder to validate operationally, and riskier to evolve.
|
||||
|
||||
The plan is to keep the public gRPC contract stable while splitting `SOR.Auth` into:
|
||||
|
||||
- thin gRPC handlers
|
||||
- application services for auth workflows
|
||||
- repositories for Identity database access
|
||||
- session-store abstractions for Redis plus PostgreSQL
|
||||
- external identity provider services for Keycloak and future OAuth providers
|
||||
- typed config and startup validation
|
||||
- dependency-aware readiness checks
|
||||
|
||||
## Current Structure Observations
|
||||
|
||||
### Strong Foundations
|
||||
|
||||
- `SOR.Auth` is registered through `AddAuthService`.
|
||||
- Auth uses ASP.NET Core Identity for account creation, password hashing, roles, token providers, and lockout.
|
||||
- Session tokens are opaque random values.
|
||||
- Raw session tokens are cached in Redis with TTL.
|
||||
- Only SHA-256 token hashes are persisted in PostgreSQL.
|
||||
- `ValidateToken` has a Redis fast path and PostgreSQL fallback.
|
||||
- Logout and revoke-all-session flows are idempotent in spirit.
|
||||
- Keycloak JWT validation uses OIDC discovery and cached signing keys.
|
||||
- Auth gRPC contract is centralized in `auth.proto`.
|
||||
|
||||
### Main Problems
|
||||
|
||||
- `AuthGrpcHandler.cs` is the service layer, repository layer, session-store layer, provider-integration layer, and transport layer in one file.
|
||||
- Identity password and lockout options are hardcoded in `ServiceRegistration.cs`.
|
||||
- Keycloak options are bound but not validated.
|
||||
- `KeycloakOptions.ClientId` exists but audience validation is disabled and the client ID is not actively enforced.
|
||||
- Session expiration is hardcoded to 30 days.
|
||||
- Redis session set entries store raw tokens in `UserSessions`, which is operationally convenient but should be reviewed as a security tradeoff.
|
||||
- Account property operations are mixed into auth transport handling and likely belong behind a small account-property service.
|
||||
- OAuth provider support is stubbed inside the handler.
|
||||
- Feature flags are read directly from Redis in the handler.
|
||||
- There is no visible `Server/tests/SOR.Auth.Tests` project.
|
||||
- Auth readiness is not explicit for PostgreSQL, Redis, Keycloak discovery, and gRPC route availability.
|
||||
|
||||
## Target Auth Shape
|
||||
|
||||
Keep `SOR.Auth` as the service module, but split responsibilities:
|
||||
|
||||
```text
|
||||
Server/src/SOR.Auth/
|
||||
ServiceRegistration.cs
|
||||
Configuration/
|
||||
AuthOptions.cs
|
||||
PasswordPolicyOptions.cs
|
||||
SessionOptions.cs
|
||||
KeycloakOptions.cs
|
||||
OAuthProviderOptions.cs
|
||||
AuthOptionsValidator.cs
|
||||
Contracts/
|
||||
AuthResponseMapper.cs
|
||||
AuthErrorCodes.cs
|
||||
Handlers/
|
||||
AuthGrpcHandler.cs
|
||||
Application/
|
||||
AuthService.cs
|
||||
SessionService.cs
|
||||
AccountPropertyService.cs
|
||||
KeycloakExchangeService.cs
|
||||
OAuthLoginService.cs
|
||||
Persistence/
|
||||
IAccountRepository.cs
|
||||
IAccountSessionRepository.cs
|
||||
IAccountPropertyRepository.cs
|
||||
EfAccountRepository.cs
|
||||
EfAccountSessionRepository.cs
|
||||
EfAccountPropertyRepository.cs
|
||||
Sessions/
|
||||
ISessionTokenGenerator.cs
|
||||
ISessionTokenHasher.cs
|
||||
ISessionCache.cs
|
||||
RedisSessionCache.cs
|
||||
SessionRecord.cs
|
||||
Providers/
|
||||
KeycloakTokenValidator.cs
|
||||
IExternalIdentityProvider.cs
|
||||
GoogleOAuthProvider.cs
|
||||
SteamOAuthProvider.cs
|
||||
AppleOAuthProvider.cs
|
||||
MicrosoftOAuthProvider.cs
|
||||
Health/
|
||||
AuthHealthChecks.cs
|
||||
```
|
||||
|
||||
`AuthGrpcHandler` should become transport mapping only:
|
||||
|
||||
1. Receive gRPC request.
|
||||
2. Call the relevant application service.
|
||||
3. Map result to gRPC response.
|
||||
4. Avoid direct EF Core, Redis, token generation, and provider-specific logic.
|
||||
|
||||
## 12-Factor Gap Map
|
||||
|
||||
### I. Codebase
|
||||
|
||||
Status: Mostly aligned.
|
||||
|
||||
Current state:
|
||||
- Auth lives in the shared server codebase and is enabled through `ENABLED_SERVICES=auth`.
|
||||
- Auth contract lives in `SOR.Shared.Proto`.
|
||||
|
||||
Plan:
|
||||
- Keep one codebase.
|
||||
- Document Auth as an independently scalable process formation.
|
||||
- Keep generated gRPC contract stable while moving implementation behind application services.
|
||||
|
||||
### II. Dependencies
|
||||
|
||||
Status: Mostly aligned, with layering gaps.
|
||||
|
||||
Current state:
|
||||
- Auth uses ASP.NET Identity, EF Core via `SOR.Database`, Redis, gRPC, and Microsoft identity token validation packages.
|
||||
- The handler directly depends on EF Core and Redis.
|
||||
|
||||
Plan:
|
||||
- Keep package dependencies explicit and centrally versioned.
|
||||
- Move direct EF Core usage behind repositories.
|
||||
- Move Redis session operations behind `ISessionCache`.
|
||||
- Keep provider validation libraries isolated under `Providers`.
|
||||
- Avoid leaking concrete Redis or EF dependencies into handlers.
|
||||
|
||||
### III. Config
|
||||
|
||||
Status: Partially aligned.
|
||||
|
||||
Current state:
|
||||
- Keycloak config is read from `Keycloak`.
|
||||
- Connection strings are environment-overridable.
|
||||
- Password policy, lockout policy, and session TTL are hardcoded.
|
||||
|
||||
Plan:
|
||||
- Add typed options and validation for:
|
||||
- `Auth:SessionTtlDays`
|
||||
- `Auth:SingleSessionPerAccount`
|
||||
- `Auth:TokenBytes`
|
||||
- `Auth:PasswordPolicy`
|
||||
- `Auth:Lockout`
|
||||
- `Keycloak:Authority`
|
||||
- `Keycloak:ClientId`
|
||||
- OAuth provider credentials and enablement
|
||||
- Use `ValidateOnStart` so bad auth config fails before serving requests.
|
||||
- Keep secrets in environment variables or secret providers, never committed JSON.
|
||||
|
||||
### IV. Backing Services
|
||||
|
||||
Status: Mostly aligned.
|
||||
|
||||
Current state:
|
||||
- PostgreSQL stores durable identity data and session hashes.
|
||||
- Redis stores active raw session token lookups and feature flags.
|
||||
- Keycloak is an external identity provider.
|
||||
|
||||
Plan:
|
||||
- Treat PostgreSQL, Redis, and Keycloak discovery as attached resources.
|
||||
- Add readiness checks for PostgreSQL and Redis.
|
||||
- Add optional readiness for Keycloak discovery when Keycloak login is enabled.
|
||||
- Keep session cache rebuildable from PostgreSQL so Redis remains disposable.
|
||||
- Document Redis feature flags and their operational ownership.
|
||||
|
||||
### V. Build, Release, Run
|
||||
|
||||
Status: Mostly aligned.
|
||||
|
||||
Current state:
|
||||
- Auth is built into the host image.
|
||||
- Runtime formation is selected by `ENABLED_SERVICES`.
|
||||
- Migrations exist under `SOR.Database`.
|
||||
|
||||
Plan:
|
||||
- Keep build and runtime separated through `SOR.Host`.
|
||||
- Run Identity database migrations as an explicit release/admin process.
|
||||
- Do not run migrations implicitly from auth startup.
|
||||
- Add release checks for password policy, session TTL, Redis connectivity, and Keycloak config.
|
||||
|
||||
### VI. Processes
|
||||
|
||||
Status: Mostly aligned.
|
||||
|
||||
Current state:
|
||||
- Auth can run as a module in one host process or co-located with gateway.
|
||||
- Auth stores correctness state in PostgreSQL and Redis, not process memory.
|
||||
|
||||
Plan:
|
||||
- Keep auth process stateless between requests.
|
||||
- Ensure all session state required for correctness is in PostgreSQL.
|
||||
- Treat Redis as an acceleration layer and revocation fanout helper.
|
||||
- Ensure multiple auth replicas can issue, validate, and revoke sessions consistently.
|
||||
|
||||
### VII. Port Binding
|
||||
|
||||
Status: Aligned through host.
|
||||
|
||||
Current state:
|
||||
- `SOR.Host` maps `AuthGrpcHandler` when auth is enabled.
|
||||
- Co-located auth/gateway can expose auth gRPC on a loopback HTTP/2 listener.
|
||||
|
||||
Plan:
|
||||
- Keep port binding in host.
|
||||
- Document supported formations:
|
||||
- `auth` as internal gRPC service
|
||||
- `gateway,auth` co-located local or small deployment mode
|
||||
- Ensure Auth does not assume public internet exposure.
|
||||
|
||||
### VIII. Concurrency
|
||||
|
||||
Status: Partially aligned.
|
||||
|
||||
Current state:
|
||||
- ASP.NET Core handles concurrent gRPC calls.
|
||||
- Login revokes prior sessions, then creates a new session.
|
||||
- Registration checks email/display-name uniqueness before create.
|
||||
|
||||
Plan:
|
||||
- Add database constraints or transactional handling for display-name uniqueness if business rules require it.
|
||||
- Make session revoke/create flows transactionally safe for concurrent login attempts.
|
||||
- Use idempotent logout and revoke-all behavior.
|
||||
- Add tests for concurrent login and registration races.
|
||||
- Consider optimistic concurrency or serializable transaction boundaries for session replacement.
|
||||
|
||||
### IX. Disposability
|
||||
|
||||
Status: Mostly aligned.
|
||||
|
||||
Current state:
|
||||
- Auth has no long-running internal loops.
|
||||
- Keycloak OIDC metadata is cached and refreshed by `ConfigurationManager`.
|
||||
- Redis cache misses fall back to PostgreSQL.
|
||||
|
||||
Plan:
|
||||
- Keep startup fast.
|
||||
- Validate config at startup without requiring expensive provider calls unless readiness performs them.
|
||||
- Ensure all request paths honor `ServerCallContext.CancellationToken`.
|
||||
- Bound external calls and Redis operations with timeouts where appropriate.
|
||||
|
||||
### X. Dev/Prod Parity
|
||||
|
||||
Status: Partially aligned.
|
||||
|
||||
Current state:
|
||||
- Local config has Keycloak and connection-string defaults.
|
||||
- Production credentials are expected from environment variables or secrets.
|
||||
|
||||
Plan:
|
||||
- Add local auth run modes:
|
||||
- local email/password auth only
|
||||
- production-like auth with local or staging Keycloak
|
||||
- Keep config keys identical across environments.
|
||||
- Document how to seed roles, accounts, and Keycloak client config locally.
|
||||
|
||||
### XI. Logs
|
||||
|
||||
Status: Mostly aligned.
|
||||
|
||||
Current state:
|
||||
- Auth uses structured logging.
|
||||
- Successful login/register/session revoke events are logged.
|
||||
- Some failure logs include email or Keycloak subject.
|
||||
|
||||
Plan:
|
||||
- Keep logs as stdout event streams through host Serilog.
|
||||
- Never log passwords, raw session tokens, OAuth tokens, or Keycloak access tokens.
|
||||
- Review PII logging:
|
||||
- email in registration failure logs
|
||||
- Keycloak subject in migration logs
|
||||
- Add consistent fields:
|
||||
- `AccountId`
|
||||
- `Provider`
|
||||
- `ErrorCode`
|
||||
- `SessionRevokedCount`
|
||||
- `AuthFlow`
|
||||
|
||||
### XII. Admin Processes
|
||||
|
||||
Status: Partially aligned.
|
||||
|
||||
Current state:
|
||||
- Auth exposes revoke-all-session RPC.
|
||||
- Database migrations are external to the service module.
|
||||
- Role seeding is not visible in `SOR.Auth`.
|
||||
|
||||
Plan:
|
||||
- Keep migrations as one-off release/admin tasks.
|
||||
- Add explicit admin/process commands for:
|
||||
- migrate identity database
|
||||
- seed roles
|
||||
- revoke expired sessions cleanup
|
||||
- audit or prune stale account sessions
|
||||
- validate Keycloak discovery and realm roles
|
||||
- Keep these out of normal auth runtime startup.
|
||||
|
||||
## Refactor Phases
|
||||
|
||||
### Phase 0: Baseline and Tests
|
||||
|
||||
Deliverables:
|
||||
- Add `Server/tests/SOR.Auth.Tests`.
|
||||
- Add tests for:
|
||||
- login success
|
||||
- invalid password lockout increment
|
||||
- locked account
|
||||
- register email taken
|
||||
- register display name taken
|
||||
- weak password mapping
|
||||
- session create and validate
|
||||
- Redis miss with PostgreSQL fallback
|
||||
- logout idempotency
|
||||
- revoke all sessions
|
||||
- Keycloak exchange success, missing role, invalid token
|
||||
- account property get/set/delete/list
|
||||
|
||||
Acceptance:
|
||||
- Current behavior is covered before extracting services.
|
||||
|
||||
### Phase 1: Extract Session Services
|
||||
|
||||
Deliverables:
|
||||
- Add `ISessionTokenGenerator`.
|
||||
- Add `ISessionTokenHasher`.
|
||||
- Add `ISessionCache`.
|
||||
- Add `IAccountSessionRepository`.
|
||||
- Move `CreateSessionAsync`, `ComputeHash`, `ValidateToken`, `Logout`, and revoke-all helper logic into `SessionService`.
|
||||
|
||||
Acceptance:
|
||||
- Session behavior can be tested without gRPC.
|
||||
- Handler no longer touches Redis directly for session operations.
|
||||
|
||||
### Phase 2: Extract Auth Application Service
|
||||
|
||||
Deliverables:
|
||||
- Add `AuthService` for email/password login and registration.
|
||||
- Move account lookup, password checks, lockout handling, role assignment, and last-login updates into the service.
|
||||
- Add result models with stable error codes.
|
||||
|
||||
Acceptance:
|
||||
- `AuthGrpcHandler.Login` and `AuthGrpcHandler.Register` only map requests and responses.
|
||||
|
||||
### Phase 3: Extract Account Property Service
|
||||
|
||||
Deliverables:
|
||||
- Add `AccountPropertyService`.
|
||||
- Add repository abstraction for account properties.
|
||||
- Validate keys and values consistently.
|
||||
- Decide and document size limits for property keys and values.
|
||||
|
||||
Acceptance:
|
||||
- Account property RPCs no longer directly use EF Core.
|
||||
|
||||
### Phase 4: Extract Keycloak Exchange Service
|
||||
|
||||
Deliverables:
|
||||
- Add `KeycloakExchangeService`.
|
||||
- Keep token validation in `KeycloakTokenValidator`.
|
||||
- Move account linking, lazy migration, role checks, display-name sync, and session issuance out of handler.
|
||||
- Validate Keycloak config at startup.
|
||||
|
||||
Acceptance:
|
||||
- Keycloak exchange can be tested by mocking token validation and repositories.
|
||||
|
||||
### Phase 5: OAuth Provider Boundary
|
||||
|
||||
Deliverables:
|
||||
- Replace inline OAuth stub with `OAuthLoginService`.
|
||||
- Add provider interfaces for Google, Steam, Apple, and Microsoft.
|
||||
- Move feature flag access behind `IFeatureFlagReader`.
|
||||
- Add provider config validation only when provider is enabled.
|
||||
|
||||
Acceptance:
|
||||
- Disabled providers still return `FEATURE_DISABLED`.
|
||||
- Enabling a provider does not require editing `AuthGrpcHandler`.
|
||||
|
||||
### Phase 6: Config and Health Hardening
|
||||
|
||||
Deliverables:
|
||||
- Add typed `AuthOptions`, `SessionOptions`, `PasswordPolicyOptions`, and validators.
|
||||
- Move hardcoded password, lockout, and session TTL settings into config.
|
||||
- Add readiness checks for:
|
||||
- Identity database
|
||||
- Redis
|
||||
- Keycloak discovery when enabled
|
||||
- Add auth startup summary logging without secrets.
|
||||
|
||||
Acceptance:
|
||||
- Auth fails fast on invalid config.
|
||||
- `/ready` can reflect auth dependency health when host readiness is implemented.
|
||||
|
||||
### Phase 7: Security Review and Cleanup Jobs
|
||||
|
||||
Deliverables:
|
||||
- Review whether raw tokens should remain in Redis user session sets.
|
||||
- Consider storing token hashes in sets and keeping raw token only as the direct Redis session key.
|
||||
- Add expired-session cleanup admin task.
|
||||
- Add audit logging plan for force logout, lockout, and Keycloak migration.
|
||||
|
||||
Acceptance:
|
||||
- Session storage tradeoffs are documented.
|
||||
- Cleanup is explicit admin process work, not startup behavior.
|
||||
|
||||
## Suggested Milestone Order
|
||||
|
||||
1. Add auth tests around current behavior.
|
||||
2. Extract session token generation, hashing, cache, and repository logic.
|
||||
3. Extract email/password login and registration service.
|
||||
4. Extract account property service.
|
||||
5. Extract Keycloak exchange service.
|
||||
6. Add OAuth provider boundary and feature-flag abstraction.
|
||||
7. Add typed options and validation.
|
||||
8. Add readiness checks and auth runbook.
|
||||
9. Add cleanup/admin tasks for identity maintenance.
|
||||
|
||||
## Risk Register
|
||||
|
||||
| Risk | Why It Matters | Mitigation |
|
||||
|---|---|---|
|
||||
| Session compatibility regression | Existing clients rely on current token behavior. | Keep token format and Redis/Postgres lookup behavior stable during extraction. |
|
||||
| Login race conditions | Single-session policy can behave unpredictably with concurrent logins. | Add concurrency tests and transactional session replacement. |
|
||||
| Keycloak migration mistakes | Lazy email-based linking can attach external identity to the wrong account if email trust is weak. | Document trust assumptions and consider verified-email checks. |
|
||||
| PII leakage in logs | Auth logs can expose email or external subject identifiers. | Audit structured logging fields and redact sensitive values. |
|
||||
| Redis outage behavior | ValidateToken can fall back to PostgreSQL, but create/logout paths expect Redis. | Define degraded behavior and readiness rules. |
|
||||
| OAuth implementation creep | Provider-specific flows vary significantly. | Keep provider adapters isolated behind a common interface. |
|
||||
|
||||
## Definition of Done
|
||||
|
||||
The auth refactor is complete when:
|
||||
|
||||
- `AuthGrpcHandler` is a thin gRPC adapter.
|
||||
- Login, registration, session validation, logout, account properties, Keycloak exchange, and OAuth are separate application services.
|
||||
- Redis session cache behavior is behind `ISessionCache`.
|
||||
- PostgreSQL session persistence is behind repositories.
|
||||
- Password, lockout, session, Keycloak, and OAuth options are typed and validated.
|
||||
- Auth has focused unit tests and integration tests.
|
||||
- Readiness covers Identity database, Redis, and enabled external identity providers.
|
||||
- Logs are structured and avoid credentials, tokens, and unnecessary PII.
|
||||
- Admin work such as migrations, role seeding, session cleanup, and provider validation runs as explicit one-off processes.
|
||||
Reference in New Issue
Block a user