diff --git a/.gitignore b/.gitignore index 3f16268..2bda0ff 100644 --- a/.gitignore +++ b/.gitignore @@ -424,3 +424,4 @@ deploy/.env out/ # License signing keys (tools/Khaemhat.LicenseTool): the private key never enters the repository (ADR 0008). *.khkey +*.pem diff --git a/CHANGELOG.md b/CHANGELOG.md index a596fa9..50ee032 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,43 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. ## [Unreleased] +## [0.2.0] - 2026-11-11 + +M2 — Sistema e sicurezza. L'istanza si avvia da sola, crea super utente e prima azienda, e si entra con password e +verifica in due passaggi. + +### Added +- Avvio guidato dalle variabili `KHAEMHAT_*` (anche `_FILE`): tutte le variabili sbagliate elencate insieme e uscita + con codice 2; migrazioni del sistema e delle aziende all'avvio, super utente e prima azienda al primo avvio, + pagina "Avvio in corso" e `/health/ready` a 503 finché non è pronto (ADR 0019). +- Account di istanza (super utente, amministratori) e utenti aziendali, password PBKDF2-SHA256 con storico, blocco + dopo 5 errori, limite di 10 accessi al minuto per indirizzo IP. +- Pagine di accesso (mockup 001-003): scelta dell'azienda, cambio password obbligatorio, attivazione e verifica in + due passaggi (TOTP, RFC 6238) con 10 codici di recupero; uscita con `POST /logout`. +- Sessioni nel database con token salvato come hash, rigenerato a ogni passo, revocabili, riverificate dal circuito + Blazor ogni minuto; audit di sicurezza in `sys_security_audit` con catena di hash. +- Ruoli predefiniti, permessi `modulo.area.azione` con override per utente, attributi `[RequirePermission]`, + `[RequireLevel]`, `[RequireModule]`. +- Licenze: trial di 60 giorni, file `.khl` firmati ECDSA P-256, codici di attivazione dei moduli, modalità test con + i codici fittizi, limite di aziende e di utenti contemporanei; strumento `tools/Khaemhat.LicenseTool`. +- Chiavi DataProtection nel database di sistema, cifrate con la chiave di istanza. +- Cache in memoria o su Redis (client RESP scritto in casa, `KHAEMHAT_REDIS`), con ritorno alla memoria se Redis non + risponde. +- Log su database (`sys_log`) per sezioni, con identificativo di traccia (`X-Trace-Id`), utente e azienda; query + lente nella sezione *Prestazioni*; esito delle migrazioni nella sezione *Migrazioni*. +- Attività programmate: cron a 5 campi con fuso orario, lock, timeout, tentativi, storico; job di sistema per pulizia + sessioni, controllo licenza e retention del log. +- Storico dei record (`audit_log` aziendale) con i soli campi cambiati. +- Aziende: creazione e collegamento, stati attiva / manutenzione / sola lettura / disattivata, contesto azienda per + pagine e API (`X-Company`), risposta 503 per le aziende in manutenzione. +- Header di sicurezza su tutte le risposte (CSP senza script inline, `X-Frame-Options`, `nosniff`, + `Referrer-Policy`, `Permissions-Policy`). +- Tabelle di sistema e aziendali di M2, documentate in `docs/DATA-MODEL.md` (rigenerato). + +### Changed +- La home richiede l'accesso: senza sessione porta a `/login`. +- I database SQLite in memoria restano disponibili per tutta la vita del processo. + ## [0.1.0] - 2026-11-11 M1 — Strato dati. Nessuna funzione visibile nell'interfaccia: è il motore su cui si appoggiano tutte le milestone diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index 46d5aa7..9dd3fca 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -376,6 +376,15 @@ Migrazioni applicate in ordine: - `core` 20261111001 `create_sys_companies` (M20261111_001_CreateSysCompanies) - `core` 20261111002 `create_sys_settings` (M20261111_002_CreateSysSettings) +- `core` 20261111003 `create_sys_users` (M20261111_003_CreateSysUsers) +- `core` 20261111004 `create_sys_sessions` (M20261111_004_CreateSysSessions) +- `core` 20261111005 `create_sys_roles_templates` (M20261111_005_CreateSysRolesTemplates) +- `core` 20261111006 `create_sys_licenses` (M20261111_006_CreateSysLicenses) +- `core` 20261111007 `create_sys_data_protection_keys` (M20261111_007_CreateSysDataProtectionKeys) +- `core` 20261111008 `create_sys_log` (M20261111_008_CreateSysLog) +- `core` 20261111009 `create_sys_security_audit` (M20261111_009_CreateSysSecurityAudit) +- `core` 20261111010 `create_sys_scheduler` (M20261111_010_CreateSysScheduler) +- `core` 20261111011 `create_sys_notifications` (M20261111_011_CreateSysNotifications) #### `schema_version` @@ -409,6 +418,212 @@ Chiave primaria: `module`, `version`. - indice unico `ux_sys_companies_code` su `code` +#### `sys_data_protection_keys` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `friendly_name` | String(200) | no | | | +| `xml` | Text | no | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_sys_data_protection_keys_friendly_name` su `friendly_name` + +#### `sys_job_locks` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | String(100) | no | | chiave primaria | +| `owner` | String(100) | no | | | +| `acquired_at` | DateTimeUtc | no | | | +| `expires_at` | DateTimeUtc | no | | | + +#### `sys_job_runs` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `task_code` | String(100) | no | | | +| `started_at` | DateTimeUtc | no | | | +| `finished_at` | DateTimeUtc | sì | | | +| `outcome` | String(40) | no | | | +| `attempt` | Int32 | no | `1` | | +| `message` | Text | sì | | | +| `trace_id` | String(64) | sì | | | + +- indice `ix_sys_job_runs_task_code_started_at` su `task_code`, `started_at` + +#### `sys_license_activations` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `action` | String(40) | no | | | +| `source` | String(40) | no | | | +| `modules` | String(400) | sì | | | +| `outcome` | String(60) | no | | | +| `message` | Text | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +#### `sys_licenses` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `source` | String(40) | no | | | +| `payload` | Text | no | | | +| `licensee` | String(200) | sì | | | +| `modules` | String(400) | no | | | +| `max_concurrent_users` | Int32 | no | `0` | | +| `max_companies` | Int32 | no | `0` | | +| `issued_at` | DateTimeUtc | sì | | | +| `expires_at` | DateTimeUtc | sì | | | +| `grace_period_days` | Int32 | no | `0` | | +| `is_active` | Bool | no | `true` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +#### `sys_log` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `at` | DateTimeUtc | no | | | +| `level` | String(20) | no | | | +| `section` | String(40) | no | | | +| `source` | String(200) | no | | | +| `message` | Text | no | | | +| `exception` | Text | sì | | | +| `user_name` | String(100) | sì | | | +| `company_code` | String(20) | sì | | | +| `trace_id` | String(64) | sì | | | +| `request` | String(400) | sì | | | +| `entity` | String(100) | sì | | | +| `entity_id` | String(100) | sì | | | +| `data` | Json | sì | | | + +- indice `ix_sys_log_at` su `at` +- indice `ix_sys_log_section_at` su `section`, `at` +- indice `ix_sys_log_trace_id` su `trace_id` + +#### `sys_notifications` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `recipient_user_id` | Int64 | sì | | | +| `category` | String(40) | no | | | +| `severity` | String(40) | no | | | +| `title` | String(200) | no | | | +| `body` | Text | sì | | | +| `link` | String(400) | sì | | | +| `read_at` | DateTimeUtc | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_sys_notifications_recipient_user_id` su `recipient_user_id` + +#### `sys_roles_templates` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(50) | no | | | +| `name` | String(100) | no | | | +| `description` | Text | sì | | | +| `permissions` | Json | no | | | +| `sort_order` | Int32 | no | `0` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_sys_roles_templates_code` su `code` + +#### `sys_scheduled_tasks` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(100) | no | | | +| `name` | String(200) | no | | | +| `job_type` | String(100) | no | | | +| `company_code` | String(20) | sì | | | +| `cron` | String(100) | no | | | +| `time_zone` | String(64) | no | | | +| `timeout_seconds` | Int32 | no | `600` | | +| `max_retries` | Int32 | no | `0` | | +| `is_enabled` | Bool | no | `true` | | +| `is_system` | Bool | no | `false` | | +| `parameters` | Json | sì | | | +| `last_run_at` | DateTimeUtc | sì | | | +| `next_run_at` | DateTimeUtc | sì | | | +| `last_outcome` | String(40) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_sys_scheduled_tasks_code` su `code` + +#### `sys_security_audit` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `at` | DateTimeUtc | no | | | +| `action` | String(100) | no | | | +| `user_name` | String(100) | sì | | | +| `company_code` | String(20) | sì | | | +| `ip_address` | String(64) | sì | | | +| `target` | String(200) | sì | | | +| `details` | Json | sì | | | +| `previous_hash` | String(64) | no | | | +| `hash` | String(64) | no | | | + +- indice `ix_sys_security_audit_at` su `at` + +#### `sys_sessions` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `token_hash` | String(64) | no | | | +| `user_id` | Int64 | no | | -> `sys_users` (Cascade) | +| `state` | String(40) | no | | | +| `company_code` | String(20) | sì | | | +| `ip_address` | String(64) | sì | | | +| `user_agent` | String(400) | sì | | | +| `persistent` | Bool | no | `false` | | +| `last_seen_at` | DateTimeUtc | no | | | +| `expires_at` | DateTimeUtc | no | | | +| `revoked_at` | DateTimeUtc | sì | | | +| `revoked_reason` | String(100) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_sys_sessions_user_id` su `user_id` +- indice unico `ux_sys_sessions_token_hash` su `token_hash` + #### `sys_settings` | Colonna | Tipo | Null | Default | Note | @@ -425,9 +640,118 @@ Chiave primaria: `module`, `version`. - indice unico `ux_sys_settings_key` su `key` +#### `sys_users` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `user_name` | String(100) | no | | | +| `display_name` | String(200) | no | | | +| `email` | String(254) | sì | | | +| `level` | String(40) | no | | | +| `password_hash` | String(200) | sì | | | +| `password_history` | Json | sì | | | +| `password_changed_at` | DateTimeUtc | sì | | | +| `must_change_password` | Bool | no | `false` | | +| `temporary_password_expires_at` | DateTimeUtc | sì | | | +| `failed_login_count` | Int32 | no | `0` | | +| `locked_until` | DateTimeUtc | sì | | | +| `totp_secret` | Text | sì | | | +| `totp_enabled` | Bool | no | `false` | | +| `totp_last_step` | Int64 | sì | | | +| `totp_recovery_codes` | Json | sì | | | +| `recovery_token_hash` | String(64) | sì | | | +| `recovery_token_expires_at` | DateTimeUtc | sì | | | +| `is_active` | Bool | no | `true` | | +| `last_login_at` | DateTimeUtc | sì | | | +| `linked_company_code` | String(20) | sì | | | +| `linked_user_id` | Int64 | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_sys_users_user_name` su `user_name` + ### Database aziendale -Nessuna migrazione: la tabella `schema_version` è l'unica presente. +Migrazioni applicate in ordine: + +- `core` 20261111001 `create_users` (M20261111_001_CreateUsers) +- `core` 20261111002 `create_user_sessions` (M20261111_002_CreateUserSessions) +- `core` 20261111003 `create_roles` (M20261111_003_CreateRoles) +- `core` 20261111004 `create_audit_log` (M20261111_004_CreateAuditLog) +- `core` 20261111005 `create_notifications` (M20261111_005_CreateNotifications) + +#### `audit_log` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `at` | DateTimeUtc | no | | | +| `entity` | String(100) | no | | | +| `entity_id` | String(100) | no | | | +| `action` | String(20) | no | | | +| `user_name` | String(100) | sì | | | +| `diff` | Json | sì | | | +| `trace_id` | String(64) | sì | | | + +- indice `ix_audit_log_at` su `at` +- indice `ix_audit_log_entity_entity_id` su `entity`, `entity_id` + +#### `notifications` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `recipient_user_id` | Int64 | sì | | | +| `category` | String(40) | no | | | +| `severity` | String(40) | no | | | +| `title` | String(200) | no | | | +| `body` | Text | sì | | | +| `link` | String(400) | sì | | | +| `read_at` | DateTimeUtc | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_notifications_recipient_user_id` su `recipient_user_id` + +#### `role_permissions` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `role_id` | Int64 | no | | -> `roles` (Cascade) | +| `permission` | String(100) | no | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_role_permissions_role_id_permission` su `role_id`, `permission` + +#### `roles` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `code` | String(50) | no | | | +| `name` | String(100) | no | | | +| `description` | Text | sì | | | +| `is_predefined` | Bool | no | `false` | | +| `template_code` | String(50) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_roles_code` su `code` #### `schema_version` @@ -441,4 +765,97 @@ Nessuna migrazione: la tabella `schema_version` è l'unica presente. Chiave primaria: `module`, `version`. +#### `user_permission_overrides` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `user_id` | Int64 | no | | -> `users` (Cascade) | +| `permission` | String(100) | no | | | +| `allowed` | Bool | no | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_user_permission_overrides_user_id_permission` su `user_id`, `permission` + +#### `user_roles` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `user_id` | Int64 | no | | -> `users` (Cascade) | +| `role_id` | Int64 | no | | -> `roles` (Cascade) | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_user_roles_user_id_role_id` su `user_id`, `role_id` + +#### `user_sessions` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `token_hash` | String(64) | no | | | +| `user_id` | Int64 | no | | -> `users` (Cascade) | +| `state` | String(40) | no | | | +| `company_code` | String(20) | sì | | | +| `ip_address` | String(64) | sì | | | +| `user_agent` | String(400) | sì | | | +| `persistent` | Bool | no | `false` | | +| `last_seen_at` | DateTimeUtc | no | | | +| `expires_at` | DateTimeUtc | no | | | +| `revoked_at` | DateTimeUtc | sì | | | +| `revoked_reason` | String(100) | sì | | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice `ix_user_sessions_user_id` su `user_id` +- indice unico `ux_user_sessions_token_hash` su `token_hash` + +#### `users` + +| Colonna | Tipo | Null | Default | Note | +|---|---|---|---|---| +| `id` | Int64 | no | | chiave primaria, identity | +| `user_name` | String(100) | no | | | +| `display_name` | String(200) | no | | | +| `email` | String(254) | sì | | | +| `kind` | String(40) | no | | | +| `password_hash` | String(200) | sì | | | +| `password_history` | Json | sì | | | +| `password_changed_at` | DateTimeUtc | sì | | | +| `must_change_password` | Bool | no | `false` | | +| `temporary_password_expires_at` | DateTimeUtc | sì | | | +| `failed_login_count` | Int32 | no | `0` | | +| `locked_until` | DateTimeUtc | sì | | | +| `totp_secret` | Text | sì | | | +| `totp_enabled` | Bool | no | `false` | | +| `totp_required` | Bool | no | `false` | | +| `totp_last_step` | Int64 | sì | | | +| `totp_recovery_codes` | Json | sì | | | +| `recovery_token_hash` | String(64) | sì | | | +| `recovery_token_expires_at` | DateTimeUtc | sì | | | +| `is_active` | Bool | no | `true` | | +| `last_login_at` | DateTimeUtc | sì | | | +| `own_customers_only` | Bool | no | `false` | | +| `can_see_costs` | Bool | no | `false` | | +| `can_export` | Bool | no | `false` | | +| `can_use_api` | Bool | no | `false` | | +| `created_at` | DateTimeUtc | no | | | +| `created_by` | String(100) | sì | | | +| `updated_at` | DateTimeUtc | sì | | | +| `updated_by` | String(100) | sì | | | +| `row_version` | Int64 | no | `1` | | + +- indice unico `ux_users_user_name` su `user_name` + diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 0d630ec..bc04237 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -136,8 +136,8 @@ programmata passa da un controllo esplicito. | Aspetto | Regola | |---|---| -| Autenticazione | cookie ASP.NET Core con `CookieSessionAuthenticationHandler`; nessun ASP.NET Identity/EF | -| Attributi del cookie | `HttpOnly; Secure; SameSite=Lax` | +| Autenticazione | schema `KhaemhatSession` scritto in casa (`SessionAuthenticationHandler`, ADR 0019); nessun ASP.NET Identity/EF | +| Attributi del cookie | `khaemhat_session`, `HttpOnly; SameSite=Lax`; `Secure` quando la richiesta è HTTPS o `KHAEMHAT_PUBLIC_URL` è `https` | | Identificatore | 256 bit casuali da `SecureTokenGenerator` (`RandomNumberGenerator`) | | Stato | riga di sessione in `sys_sessions` (account di istanza) o `user_sessions` (utenti aziendali): dispositivo, IP, creazione, ultimo uso, revoca | | Scadenza | scorrevole, con timeout di inattività da impostazioni (mockup 086: 480 minuti) | @@ -148,9 +148,12 @@ programmata passa da un controllo esplicito. | Antiforgery | sui form statici (login, cambio password, recupero) | | Cookie ammessi | sessione e tema prima del login (SPEC §1.5); nessun cookie di profilazione | -Proposta: nella riga di sessione salvare l'**hash SHA-256** dell'identificatore, non il valore, così una lettura del -database non consente di impersonare le sessioni attive. Rigenerare l'identificatore dopo il login e dopo il -passaggio TOTP (prevenzione della session fixation). +**Implementato in M2.** La riga di sessione contiene solo l'**hash SHA-256** dell'identificatore: una lettura del +database non consente di impersonare le sessioni attive. L'identificatore viene **rigenerato a ogni passaggio di +stato** (password verificata, TOTP verificato, password cambiata), contro la session fixation. Una sessione che non è +ancora *attiva* (manca il TOTP o il cambio password) apre solo le pagine del suo passo. Il circuito Blazor ricontrolla +la sessione ogni minuto e si chiude se è stata revocata; mettere un'azienda in manutenzione o disattivarla revoca le +sessioni dei suoi utenti. --- @@ -253,8 +256,8 @@ passaggio TOTP (prevenzione della session fixation). interfaccia `ISecretProtector` in `Khaemhat.Core`. - La chiave e i segreti in chiaro **non vanno mai** in log, messaggi d'errore, diagnostica, risposte API o file su disco (SPEC §1.5: nessun `appsettings..json` con segreti, nessun file temporaneo). -- Le varianti `_FILE` delle variabili (Docker secrets) sono previste per `KHAEMHAT_SYSTEM_DB` e le credenziali del - super utente; proposta: estenderle a `KHAEMHAT_SECRET_KEY` e alle altre variabili sensibili. +- Le varianti `_FILE` (Docker secrets) valgono per tutte le variabili sensibili, `KHAEMHAT_SECRET_KEY` compresa + (ADR 0014); impostare sia la variabile sia la sua `_FILE` è un errore di avvio. ### 7.2 Rotazione (`SecretRotationService`, `SecretRotation`) @@ -275,8 +278,9 @@ della vecchia chiave come chiave di sola decifratura identificata dalla versione - Le chiavi DataProtection di ASP.NET Core (cookie, antiforgery) sono nel **database di sistema** (`sys_data_protection_keys`) tramite `DataProtectionDbXmlRepository`: nessun file su disco, cookie validi dopo un riavvio o un nuovo container. -- Proposta: cifrare l'XML delle chiavi a riposo con un `IXmlEncryptor` basato su `SecretProtector`, così la sola - lettura del database di sistema non consente di falsificare cookie. +- **Implementato in M2** (`DataProtectionKeyStore`, `SecretKeyXmlEncryptor`): l'XML delle chiavi è cifrato a riposo + con `SecretProtector` (scopo `dataprotection:keys`), così la sola lettura del database di sistema non consente di + falsificare cookie o token antiforgery. Il database di sistema è migrato prima che DataProtection legga le chiavi. --- @@ -286,14 +290,18 @@ della vecchia chiave come chiave di sola decifratura identificata dalla versione | Header | Valore | |---|---| -| `Content-Security-Policy` | `default-src 'self'`; script solo `'self'` + **nonce** per gli script di Blazor; `connect-src 'self'` (WebSocket del circuito sullo stesso host); `frame-ancestors 'none'`; `object-src 'none'`; `base-uri 'self'` (dettaglio proposto) | +| `Content-Security-Policy` | `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; object-src 'none'` | | `X-Frame-Options` | `DENY` | -| `Referrer-Policy` | proposta: `strict-origin-when-cross-origin` (o `no-referrer`) | -| `X-Content-Type-Options` | proposta: `nosniff` | +| `Referrer-Policy` | `same-origin` | +| `X-Content-Type-Options` | `nosniff` | +| `Permissions-Policy` | `camera=(), microphone=(), geolocation=(), payment=()` | +| `Cross-Origin-Opener-Policy` | `same-origin` | | `Strict-Transport-Security` | impostato dal **reverse proxy**, che termina TLS | - Nessuna risorsa da CDN, nessun font scaricato, nessuno script di terze parti (SPEC §1.2): la CSP può restare - rigorosa. JavaScript solo in `wwwroot/js`, senza `eval` né gestori inline. + rigorosa. In M2 non serve nemmeno il nonce: nessuna pagina ha script inline (la `` di Blazor, che + ne scriverebbe uno, non è usata). `style-src 'unsafe-inline'` resta perché Blazor applica stili agli elementi + durante la riconnessione. JavaScript solo in `wwwroot/js`, senza `eval` né gestori inline. - L'impostazione *CSP rigorosa (nonce)* (mockup 086) esiste per la diagnosi; disattivarla è un evento di audit. - Blazor esegue l'escaping dell'output: vietato `MarkupString` su contenuti provenienti da utenti o da file (eccezione: l'anteprima XML formattata, che va resa come testo). diff --git a/docs/STATUS.md b/docs/STATUS.md index 27c3602..0d5c4da 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -3,16 +3,16 @@ > Punto di ripresa per ogni sessione. Aggiornare a fine sessione. **Ultimo aggiornamento:** 2026-11-11 -**Milestone corrente:** M2 — Sistema e sicurezza (M1 chiusa con il tag `v0.1.0`) -**Prossimo passo:** M2 partendo dall'issue #15 (colonna *Da fare* del progetto *Khaemhat 1.0 — Sviluppo*). Da -recuperare in M2: registrazione dell'esito delle migrazioni nella sezione di log *Migrazioni* (ADR 0018), avvio che -rifiuta di partire senza `KHAEMHAT_SECRET_KEY` valida, misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` -§6.1. +**Milestone corrente:** M2 — Sistema e sicurezza, completata nel ramo `feat/15-sistema-e-sicurezza` (PR verso `main`); +il tag `v0.2.0` si crea dopo il merge. +**Prossimo passo:** M3 — Interfaccia (issue #25-#36): layout, navigazione e componenti sopra le pagine di accesso di M2. +Da recuperare: misure di riferimento su PostgreSQL in `docs/DATA-MODEL.md` §6.1; pagina di cambio password con +indicatore di robustezza (mockup 003) in M3. ## Fatto - Specifica normativa in `docs/SPEC.md`; `CLAUDE.md` con emendamenti E1-E6. -- ADR 0001-0018. +- ADR 0001-0019. - Mockup in `docs/mockups/` (22 in alta risoluzione + galleria, 88 miniature, `mockup.css`, indice). - Icone in `assets/`; deploy in `deploy/` (compose Unraid, `.env.example`, template Unraid). - Documentazione tecnica: `ARCHITECTURE.md`, `DATA-MODEL.md` (provvisorio, sarà generato), `MODULES.md`, `API.md`, @@ -30,6 +30,14 @@ rifiuta di partire senza `KHAEMHAT_SECRET_KEY` valida, misure di riferimento su (AES-256-GCM, formato `khs1`), `tools/Khaemhat.DataModelTool` e gli script `new-migration.sh` e `gen-datamodel.sh`; ADR 0018. Test: 106 test dello strato dati verdi su SQLite in locale e su PostgreSQL 16 e 17 in CI (in locale Docker non è disponibile). +- **M2 (`v0.2.0`, PR da aprire):** avvio da variabili con elenco degli errori, migrazioni all'avvio, super utente e + prima azienda; account di istanza e aziendali, password con storico e blocco, sessioni nel database, TOTP con codici + di recupero, pagine di accesso (mockup 001-003); ruoli, permessi e attributi di autorizzazione; licenze firmate, + codici di attivazione, modalità test, `tools/Khaemhat.LicenseTool`; DataProtection nel database cifrata; cache + memoria/Redis (client RESP in casa); log su database per sezioni con traccia; attività programmate con cron, lock e + job di sistema; storico dei record; aziende con stati e contesto (`X-Company`); header di sicurezza; ADR 0019. + Test: 180 verdi in locale, più 21 di PostgreSQL saltati senza Docker (girano in CI). La chiave privata delle licenze è fuori dal + repository (`Khaemhat-private/khaemhat-license.khkey`) e va conservata dal titolare. - Su Gitea: etichette, milestone M0-M14, 114 issue con checklist, progetti *Khaemhat 1.0 — Sviluppo* (M0-M13) e *Khaemhat 1.1+ — Fase 2* (M14). Numerazione: M0 #1-#6 e #114, M1 #7-#14, M2 #15-#24, M3 #25-#36, M4 #37-#46, M5 #47-#54, M6 #55-#61, M7 #62-#68, M8 #69-#73, M9 #74-#81, M10 #82-#87, M11 #88-#91, diff --git a/docs/adr/0019-sistema-e-sicurezza.md b/docs/adr/0019-sistema-e-sicurezza.md new file mode 100644 index 0000000..df7a10c --- /dev/null +++ b/docs/adr/0019-sistema-e-sicurezza.md @@ -0,0 +1,54 @@ +# ADR 0019 - Sistema e sicurezza: scelte di M2 + +- **Stato:** accettata +- **Data:** 2026-11-11 +- **Modifica:** SPEC §5.4, §6, §7, §8, §9.3, §9.5, §9.6; milestone M2, issue #15-#24 + +## Contesto + +M2 costruisce avvio, account, accesso, licenze, cache, log, attività programmate e contesto azienda. La specifica +indica il risultato ma lascia aperti alcuni dettagli, o li descrive con componenti che non si possono usare senza +librerie esterne (SPEC §1.2). Questo ADR fissa le scelte fatte. + +## Decisione + +1. **Autenticazione con uno schema proprio.** Lo schema `KhaemhatSession` (`SessionAuthenticationHandler`) legge il + cookie `khaemhat_session` = `.`: `_` per gli account di istanza (`sys_sessions`), il codice + azienda per gli utenti aziendali (`user_sessions`). Nel database c'è solo l'hash SHA-256 del token. Non si usa il + cookie di autenticazione di ASP.NET Core: la sessione deve essere revocabile e contata per la licenza, e il suo + stato vive nel database, non nel cookie. +2. **Accesso in passi.** Una sessione nasce in uno stato (`PendingPasswordChange`, `PendingTotpSetup`, + `PendingTotp`, `Active`) e solo `Active` autentica le pagine. Ogni passaggio di stato rigenera il token. Le pagine + di accesso sono SSR statiche con `EditForm` (antiforgery incluso), escluse dal routing interattivo. +3. **Attivazione TOTP senza QR.** La pagina mostra la chiave in base32 a gruppi di quattro e il collegamento + `otpauth://`; un codice QR richiederebbe una libreria o un generatore scritto in casa che non vale il costo. Dopo + la conferma si mostrano 10 codici di recupero monouso (salvati come hash). +4. **Avvio in due tempi.** `BootstrapService.StartAsync` migra il database di sistema **prima** che parta il server + (DataProtection legge le chiavi da lì); il resto (licenza, super utente, prima azienda, migrazioni delle aziende) + gira in background mentre `/health/ready` risponde 503 e le pagine mostrano "Avvio in corso". Un errore di + configurazione ferma il processo con codice 2 ed elenca tutte le variabili sbagliate; un errore di avvio con + codice 1. Un'azienda che non si migra va in manutenzione senza fermare le altre. +5. **Chiavi DataProtection** in `sys_data_protection_keys`, cifrate con `SecretProtector`. +6. **Log su database** con un `ILoggerProvider` scritto in casa: coda limitata (20 000 eventi, si scartano i più + vecchi), scrittura a blocchi di 200 ogni secondo, sezione ricavata dalla categoria o dallo scope `Section`, + `TraceId`, utente e azienda dallo scope della richiesta. Gli eventi di `Microsoft.*` e `System.*` sotto + `Warning` non vanno nel database. Retention per livello con un job notturno. +7. **Redis** con un client RESP2 scritto in casa (una connessione, un comando alla volta, `AUTH`, `SELECT`, TLS + con `rediss://`). Se Redis non risponde la cache passa alla memoria e lo scrive nel log una volta al minuto: + la cache non fa mai fallire una richiesta. +8. **Attività programmate**: cron a 5 campi con fuso orario (le ore che non esistono al cambio dell'ora legale si + saltano), lock per attività in `sys_job_locks` con scadenza pari al timeout (un lock scaduto si riprende), una + riga di `sys_job_runs` per tentativo, notifica agli account di istanza quando l'ultimo tentativo fallisce. +9. **Contesto azienda**: gli utenti aziendali lavorano solo nella propria azienda; gli account di istanza la + scelgono (sessione, o header `X-Company` per le API). Un'azienda in manutenzione è chiusa agli utenti aziendali, + una disattivata a tutti: pagine con avviso 503, API con 503 e `Retry-After`; un `X-Company` di un'altra azienda + dà 403. +10. **Database SQLite in memoria** (test e demo): il provider tiene aperta una connessione per ogni database in + memoria creato con `EnsureDatabaseExistsAsync`, che altrimenti sparirebbe con l'ultima connessione. + +## Conseguenze + +- Nessuna dipendenza nuova; tutto è coperto da test (vettori RFC 6238, RESP, cron con ora legale, flusso di accesso + sull'host reale, isolamento di due aziende). +- Le schermate di amministrazione (utenti, ruoli, licenze, log, attività) arrivano in M12 sopra questi servizi. +- La pagina di cambio password è più semplice del mockup 003 (niente indicatore di robustezza) fino a M3. diff --git a/docs/wiki/Attivita-programmate.md b/docs/wiki/Attivita-programmate.md index a066da1..faec5c4 100644 --- a/docs/wiki/Attivita-programmate.md +++ b/docs/wiki/Attivita-programmate.md @@ -1,8 +1,13 @@ # Attività programmate -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2 e M12) +> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2 e M12) > **Modulo di licenza:** CORE (procedure oltre quelle di sistema: AUTO; report pianificati: REPORT) · **Livello richiesto:** amministratore · **Specifica:** SPEC §9, §11.12, §11.13, §12.5 +> **Nella versione 0.2.0** c'è il motore: espressioni cron a 5 campi con fuso orario, lock per attività (una sola +> esecuzione anche con più istanze), timeout, tentativi, storico delle esecuzioni e notifica agli amministratori +> quando un'attività fallisce. Girano i tre job di sistema (pulizia sessioni, controllo licenza, retention del log). +> La schermata e le attività create dagli utenti arrivano in M12. + ## A cosa serve Le **attività programmate** fanno lavorare Khaemhat da solo a orari stabiliti: backup notturni, fatturazione @@ -132,6 +137,14 @@ il dettaglio dell'ultima. Le esecuzioni sono registrate nel database di sistema. ## Job di sistema +Nella versione 0.2.0 i job di sistema sono questi (orari nel fuso `Europe/Rome`): + +| Codice | Cosa fa | Quando | +|---|---|---| +| `system.sessions-cleanup` | elimina le sessioni scadute o revocate da più di 30 giorni, nel database di sistema e in ogni azienda non disattivata | al minuto 15 di ogni ora | +| `system.license-check` | ricalcola la licenza; avvisa gli amministratori a 30, 14, 7, 3 e 1 giorno dalla scadenza e quando è scaduta | ogni ora | +| `system.log-retention` | elimina gli eventi di log più vecchi della retention del loro livello | ogni notte alle 03:30 | + Oltre alle attività degli amministratori, Khaemhat esegue sempre alcuni **job di sistema**: pulizia (log e sessioni secondo la retention), controllo della licenza, aggiornamento dei cambi BCE, lettura dell'inbox e dei canali SDI, coda delle e-mail, verifica delle giacenze, backup. Le attività di sistema predefinite sono create con le tabelle di diff --git a/docs/wiki/Istanza-e-database.md b/docs/wiki/Istanza-e-database.md index 8244dbd..ef4e898 100644 --- a/docs/wiki/Istanza-e-database.md +++ b/docs/wiki/Istanza-e-database.md @@ -1,8 +1,13 @@ # Istanza e database -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2 e M12) +> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2 e M12) > **Modulo di licenza:** CORE (aziende oltre la prima: MULTI) · **Livello richiesto:** amministratore; azioni distruttive solo super utente · **Specifica:** SPEC §5.3, §5.4, §7.1, §12.1, §13 +> **Nella versione 0.2.0** ci sono la creazione della prima azienda al primo avvio, la creazione e il collegamento +> di altre aziende (dal codice, con il modulo MULTI), gli stati *attiva / manutenzione / sola lettura / disattivata* +> con le sessioni chiuse quando un'azienda va in manutenzione e il contesto azienda per pagine e API (header +> `X-Company`). Le schermate descritte qui arrivano in M12. + ## A cosa serve Un'installazione di Khaemhat (una **istanza**, cioè un container) può servire più aziende. Ogni azienda ha il diff --git a/docs/wiki/Licenze-e-moduli.md b/docs/wiki/Licenze-e-moduli.md index 118ee7c..9f18c7a 100644 --- a/docs/wiki/Licenze-e-moduli.md +++ b/docs/wiki/Licenze-e-moduli.md @@ -1,8 +1,13 @@ # Licenze e moduli -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2) +> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2) > **Modulo di licenza:** CORE · **Livello richiesto:** super utente (attivazione); amministratore (consultazione) · **Specifica:** SPEC §1.8, §6, §8, §12.2 +> **Nella versione 0.2.0** ci sono verifica e applicazione della licenza: trial di 60 giorni, file `.khl` firmati +> (ECDSA P-256) da `KHAEMHAT_LICENSE` o caricati, codici di attivazione dei moduli, modalità test con i codici +> fittizi, controllo orario della scadenza con notifiche, limite di aziende e di utenti contemporanei. La schermata +> **Licenze e moduli** arriva in M12. + ## A cosa serve Khaemhat è diviso in **moduli** attivabili con licenza. La pagina **Licenze e moduli** mostra la licenza diff --git a/docs/wiki/Log.md b/docs/wiki/Log.md index 2b6aa02..fb105ff 100644 --- a/docs/wiki/Log.md +++ b/docs/wiki/Log.md @@ -1,8 +1,13 @@ # Log -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2) +> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2) > **Modulo di licenza:** CORE · **Livello richiesto:** amministratore · **Specifica:** SPEC §7.3, §9.5, §12.7 +> **Nella versione 0.2.0** il log è scritto nel database di sistema (`sys_log`) con sezione, livello, utente, +> azienda e identificativo di traccia (header `X-Trace-Id`), oltre che su console in JSON; la retention per livello +> gira ogni notte. La schermata **Log** con filtri e regole di avviso arriva in M12: fino ad allora si legge il log +> del container. + ## A cosa serve Il **log applicativo** registra ciò che succede in Khaemhat: accessi, documenti emessi, invii SDI, backup, diff --git a/docs/wiki/Primi-passi.md b/docs/wiki/Primi-passi.md index 03b6630..4b8bb9c 100644 --- a/docs/wiki/Primi-passi.md +++ b/docs/wiki/Primi-passi.md @@ -1,6 +1,6 @@ # Primi passi -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2-M5) +> **Stato:** parziale (passi 1-4 completi) · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (passi 1-4), passi successivi M3-M5 > **Modulo di licenza:** CORE · **Livello richiesto:** super utente, poi amministratore · **Specifica:** SPEC §5.4, §7, §8, §12, §14 Questa pagina accompagna chi ha appena installato Khaemhat dal primo avvio del container fino alla prima fattura @@ -57,15 +57,20 @@ disattivata al primo cambio password. *Mockup 001 — pagina di accesso: a sinistra marca e funzioni principali, a destra il modulo con azienda, nome utente, password e l'avviso della modalità Trial (anteprima ridotta).* -1. Nel campo **Azienda** scegli la prima azienda (quella creata dal container, ad esempio *Khaemhat Demo S.r.l.*). +1. Nel campo **Azienda** lascia la prima azienda, già proposta (quella creata dal container, ad esempio + *Khaemhat Demo S.r.l.*). Il super utente e gli amministratori possono anche scegliere **Nessuna (account di + istanza)** per lavorare solo sulle pagine di amministrazione dell'istanza. 2. In **Nome utente** scrivi il nome del super utente (`KHAEMHAT_SUPERUSER`, predefinito `root`). 3. In **Password** scrivi la password iniziale (`KHAEMHAT_SUPERUSER_PASSWORD`). 4. Spunta **Ricordami su questo dispositivo** solo su un computer personale. 5. Premi **Accedi**. Il riquadro giallo in fondo al modulo ricorda che l'istanza è in **modalità Trial** finché non attivi una licenza -(passo 6). Il collegamento **Password dimenticata?** invia un link monouso all'indirizzo e-mail registrato; funziona -solo dopo aver configurato la posta (SMTP) in **Amministrazione → Impostazioni**. +(passo 6). Il collegamento **Password dimenticata?** invia un link monouso all'indirizzo e-mail registrato; arriva con +la posta (SMTP) in una milestone successiva: nella versione 0.2.0 non è ancora presente. + +Dopo 5 tentativi sbagliati l'account resta bloccato per 15 minuti; da uno stesso indirizzo IP sono accettati al +massimo 10 invii al minuto del modulo di accesso. ## Passo 3 — Cambio password obbligatorio @@ -74,11 +79,15 @@ solo dopo aver configurato la posta (SMTP) in **Amministrazione → Impostazioni *Mockup 003 — cambio password al primo accesso, con indicatore di robustezza e avviso che la password del container viene disattivata (anteprima ridotta).* -1. In **Password attuale (provvisoria)** riscrivi la password iniziale. +1. In **Password attuale o provvisoria** riscrivi la password iniziale. 2. In **Nuova password** scrivi la nuova password. La regola predefinita chiede almeno **10 caratteri** e **3 classi** - (lettere, numeri, simboli) e non ammette nessuna delle ultime 5 password usate. -3. Ripetila in **Conferma nuova password** e controlla la barra **Robustezza**. -4. Premi **Imposta password e continua**. + (minuscole, maiuscole, numeri, simboli), non deve contenere il nome utente e non ammette nessuna delle ultime 5 + password usate. +3. Ripetila in **Ripeti la nuova password**. +4. Premi **Salva e continua**. + +Nella versione 0.2.0 la pagina è più essenziale del mockup 003: l'indicatore di robustezza arriva con l'interfaccia +completa (M3). Da questo momento la password scritta nelle variabili del container non vale più. Puoi toglierla dal file `.env` o dal template: non viene più letta. @@ -87,12 +96,15 @@ dal template: non viene più letta. Per il super utente e per gli amministratori la verifica in due passaggi è **obbligatoria** (SPEC §7.3). Al primo accesso Khaemhat chiede di collegare un'app di autenticazione (qualunque app compatibile con lo standard TOTP, -RFC 6238). La schermata di attivazione non è tra i mockup: il formato esatto (chiave testuale e/o codice QR) sarà -definito in sviluppo. +RFC 6238). La schermata **Configura la verifica in due passaggi** non è tra i mockup (ADR 0019): mostra la chiave +in gruppi di quattro caratteri e il collegamento **Apri nell'app di autenticazione** (`otpauth://`), utile sul +telefono. Non c'è un codice QR, perché generarlo richiederebbe una libreria esterna (SPEC §1.2). -1. Apri l'app di autenticazione sul telefono e aggiungi un nuovo account con la chiave mostrata da Khaemhat. -2. Scrivi in Khaemhat il codice a 6 cifre generato dall'app per confermare il collegamento. -3. Conserva in un luogo sicuro le eventuali informazioni di recupero proposte. +1. Apri l'app di autenticazione (Google Authenticator, Microsoft Authenticator, Aegis, 2FAS…) e aggiungi un nuovo + account scrivendo la chiave mostrata da Khaemhat, oppure tocca **Apri nell'app di autenticazione** dal telefono. +2. In **Primo codice dell'app** scrivi le 6 cifre generate dall'app e premi **Attiva**. +3. Khaemhat mostra **10 codici di recupero**: copiali in un luogo sicuro. Ognuno vale una volta sola al posto del + codice dell'app e non verrà mostrato di nuovo. Poi premi **Ho salvato i codici, continua**. ![002 · Accesso · verifica in due passaggi (TOTP)](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/002-accesso-2fa.png) @@ -102,8 +114,10 @@ ogni 30 secondi (anteprima ridotta).* Agli accessi successivi, dopo la password, compare la schermata **Verifica in due passaggi**: scrivi le 6 cifre mostrate dall'app e premi **Verifica**. Il codice cambia ogni 30 secondi. +Al posto delle 6 cifre puoi scrivere uno dei codici di recupero. + > **Attenzione.** Se perdi il telefono con l'app e sei il super utente, nessun altro può reimpostare il tuo accesso -> dall'interfaccia. Tieni una copia sicura della chiave TOTP o delle informazioni di recupero. +> dall'interfaccia. Tieni al sicuro i codici di recupero. ## Passo 5 — Creare un amministratore diff --git a/docs/wiki/Utenti-e-permessi.md b/docs/wiki/Utenti-e-permessi.md index b4f951e..b4f2281 100644 --- a/docs/wiki/Utenti-e-permessi.md +++ b/docs/wiki/Utenti-e-permessi.md @@ -1,8 +1,14 @@ # Utenti e permessi -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M2) +> **Stato:** parziale · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.2.0 (milestone M2) > **Modulo di licenza:** CORE · **Livello richiesto:** amministratore (amministratori: solo super utente) · **Permessi principali:** `company.users.manage` · **Specifica:** SPEC §7, §12.3, §12.4 +> **Nella versione 0.2.0** ci sono il motore e l'accesso: i tre livelli, gli account di istanza e gli utenti di +> azienda, password con storico e blocco, verifica in due passaggi con codici di recupero, sessioni revocabili, ruoli +> predefiniti e permessi `modulo.area.azione` con override, controlli sulle pagine (`[RequirePermission]`, +> `[RequireLevel]`, `[RequireModule]`). Le schermate **Utenti** e **Ruoli e permessi** descritte qui arrivano in M12: +> fino ad allora gli utenti si gestiscono solo con il super utente creato dal container. + ## A cosa serve Queste due pagine stabiliscono **chi entra** in Khaemhat e **cosa può fare**: diff --git a/src/Khaemhat.Application/Audit/AuditTrail.cs b/src/Khaemhat.Application/Audit/AuditTrail.cs new file mode 100644 index 0000000..dd024d8 --- /dev/null +++ b/src/Khaemhat.Application/Audit/AuditTrail.cs @@ -0,0 +1,124 @@ +using System.Diagnostics; +using System.Globalization; +using System.Reflection; +using System.Text.Json; +using Khaemhat.Core.Entities; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Audit; + +/// What happened to a record. +public enum AuditAction +{ + /// Created. + Insert = 0, + + /// Changed. + Update = 1, + + /// Deleted. + Delete = 2, +} + +/// +/// The history of the records of a company (SPEC §7.4): every insert, update and delete of master data, documents, +/// entries and settings writes a row in the company's audit_log, in the same unit of work as the change, with the +/// changed fields as JSON {"Field": [old, new]}. Audit columns and secrets are never written. +/// +public sealed class AuditTrail(TimeProvider clock) +{ + private static readonly HashSet Skipped = new(StringComparer.Ordinal) + { + nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion", + "PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString", + }; + + /// Writes the history row of a change, inside the caller's unit of work. + /// The entity type. + /// The company unit of work holding the change. + /// What happened. + /// The record. + /// The record before (updates and deletes). + /// The record after (inserts and updates). + /// Who did it. + /// Cancellation. + /// when a row was written (an update that changes nothing writes none). + public async Task RecordAsync( + IUnitOfWork unitOfWork, AuditAction action, object entityId, T? before, T? after, string? userName, CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(unitOfWork); + ArgumentNullException.ThrowIfNull(entityId); + var diff = Diff(before, after); + if (action == AuditAction.Update && diff.Count == 0) + { + return false; + } + + await unitOfWork.Repository().InsertAsync( + new AuditEntry + { + At = clock.GetUtcNow().UtcDateTime, + Entity = typeof(T).Name, + EntityId = Convert.ToString(entityId, CultureInfo.InvariantCulture) ?? string.Empty, + Action = action.ToString(), + UserName = userName, + Diff = JsonSerializer.Serialize(diff), + TraceId = Activity.Current?.TraceId.ToString(), + }, + cancellationToken).ConfigureAwait(false); + return true; + } + + /// The history of a record, newest first (the "Storico" panel). + /// A company unit of work. + /// The entity name. + /// The record. + /// Cancellation. + /// The rows. + public static async Task> HistoryAsync(IUnitOfWork unitOfWork, string entity, string entityId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(unitOfWork); + return (await unitOfWork.Repository().ListAsync( + Query.For().Where(a => a.Entity == entity && a.EntityId == entityId).OrderByDescending(a => a.Id), cancellationToken).ConfigureAwait(false)).Items; + } + + /// The changed fields between two versions of a record. + /// The entity type. + /// The old version, or . + /// The new version, or . + /// Field name to [old, new]. + public static IReadOnlyDictionary Diff(T? before, T? after) + where T : class + { + var result = new SortedDictionary(StringComparer.Ordinal); + foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (!property.CanRead || property.GetIndexParameters().Length > 0 || Skipped.Contains(property.Name)) + { + continue; + } + + var old = before is null ? null : Simple(property.GetValue(before)); + var current = after is null ? null : Simple(property.GetValue(after)); + if (!Equals(old, current)) + { + result[property.Name] = [old, current]; + } + } + + return result; + } + + private static object? Simple(object? value) => value switch + { + null => null, + string or bool or int or long or decimal or double => value, + DateTime date => date.ToString("O", CultureInfo.InvariantCulture), + Enum e => e.ToString(), + IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString(), + }; +} diff --git a/src/Khaemhat.Application/Audit/SecurityAuditLog.cs b/src/Khaemhat.Application/Audit/SecurityAuditLog.cs new file mode 100644 index 0000000..1afc9db --- /dev/null +++ b/src/Khaemhat.Application/Audit/SecurityAuditLog.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Audit; + +/// A security or instance action to record. +/// The action code, for example login.succeeded, user.created, license.activated. +/// Who acted. +/// The company concerned. +/// What the action was about. +/// Further details, serialized as JSON (never secrets). +/// The client address. +public sealed record SecurityEvent( + string Action, string? UserName, string? CompanyCode = null, string? Target = null, object? Details = null, string? IpAddress = null); + +/// Writes sys_security_audit. +public interface ISecurityAuditLog +{ + /// Records an action. + /// The action. + /// Cancellation. + /// A task. + Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default); +} + +/// +/// The immutable security audit (SPEC §7.3): rows are only inserted, each with the SHA-256 of its content chained to +/// the previous row, under an application lock so that two writers never fork the chain. +/// finds a changed or removed row. +/// +/// Opens the system database. +/// The clock. +public sealed class SecurityAuditLog(IUnitOfWorkFactory factory, TimeProvider clock) : ISecurityAuditLog +{ + private const string LockKey = "security-audit"; + + /// + public async Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(securityEvent); + var entry = new SecurityAuditEntry + { + At = Truncate(clock.GetUtcNow().UtcDateTime), + Action = Clip(securityEvent.Action, 100)!, + UserName = Clip(securityEvent.UserName, 100), + CompanyCode = Clip(securityEvent.CompanyCode, 20), + Target = Clip(securityEvent.Target, 200), + IpAddress = Clip(securityEvent.IpAddress, 64), + Details = securityEvent.Details is null ? null : JsonSerializer.Serialize(securityEvent.Details), + }; + + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + await unitOfWork.InTransactionAsync( + async ct => + { + await unitOfWork.AcquireLockAsync(LockKey, ct).ConfigureAwait(false); + var repository = unitOfWork.Repository(); + var last = await repository.FindAsync(Query.For().OrderByDescending(e => e.Id).Take(1), ct).ConfigureAwait(false); + entry.PreviousHash = last?.Hash ?? string.Empty; + entry.Hash = ComputeHash(entry); + await repository.InsertAsync(entry, ct).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); + } + + /// Checks the whole chain. + /// Cancellation. + /// The identifier of the first row that does not match, or when the chain is intact. + public async Task VerifyAsync(CancellationToken cancellationToken = default) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var previous = string.Empty; + const int PageSize = 1000; + for (var offset = 0; ; offset += PageSize) + { + var page = await unitOfWork.Repository() + .ListAsync(Query.For().OrderBy(e => e.Id).Page(offset, PageSize), cancellationToken).ConfigureAwait(false); + foreach (var entry in page.Items) + { + if (entry.PreviousHash != previous || entry.Hash != ComputeHash(entry)) + { + return entry.Id; + } + + previous = entry.Hash; + } + + if (page.Items.Count < PageSize) + { + return null; + } + } + } + + /// The hash of a row: every field and the previous hash, separated so that fields cannot run into each other. + /// The row. + /// 64 hexadecimal digits. + public static string ComputeHash(SecurityAuditEntry entry) + { + ArgumentNullException.ThrowIfNull(entry); + var content = string.Join( + '\u001F', + entry.PreviousHash, + DateTime.SpecifyKind(entry.At, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ss.ffffffZ", CultureInfo.InvariantCulture), + entry.Action, + entry.UserName ?? string.Empty, + entry.CompanyCode ?? string.Empty, + entry.IpAddress ?? string.Empty, + entry.Target ?? string.Empty, + entry.Details ?? string.Empty); + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(content))); + } + + private static DateTime Truncate(DateTime value) => DateTime.SpecifyKind(new DateTime(value.Ticks - (value.Ticks % 10)), DateTimeKind.Utc); + + private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length]; +} diff --git a/src/Khaemhat.Application/Configuration/EnvironmentConfigurationReader.cs b/src/Khaemhat.Application/Configuration/EnvironmentConfigurationReader.cs new file mode 100644 index 0000000..bec0f5a --- /dev/null +++ b/src/Khaemhat.Application/Configuration/EnvironmentConfigurationReader.cs @@ -0,0 +1,115 @@ +namespace Khaemhat.Application.Configuration; + +/// +/// Reads the KHAEMHAT_* variables of SPEC §6 into , applying the _FILE +/// rule of ADR 0014 to the sensitive ones: when X_FILE is set, the value of X is the content of that file +/// without the final line break; setting both is a configuration error, and so is a file that cannot be read. +/// Problems are collected in ; values never appear in messages. +/// +public sealed class EnvironmentConfigurationReader +{ + /// The variables that accept a _FILE variant (ADR 0014). + public static readonly IReadOnlySet FileVariables = new HashSet(StringComparer.Ordinal) + { + "KHAEMHAT_SYSTEM_DB", "KHAEMHAT_DB_SERVER", "KHAEMHAT_SECRET_KEY", "KHAEMHAT_SECRET_KEY_NEW", + "KHAEMHAT_SUPERUSER", "KHAEMHAT_SUPERUSER_PASSWORD", "KHAEMHAT_SUPERUSER_EMAIL", "KHAEMHAT_LICENSE", + "KHAEMHAT_REDIS", "KHAEMHAT_SMTP_PASSWORD", "KHAEMHAT_UPDATE_TOKEN", + }; + + private readonly Func _lookup; + private readonly Func _readFile; + + /// Creates a reader. + /// Returns a variable, or when unset (the host configuration: environment and command line). + /// Reads a secret file; the default reads from disk. + public EnvironmentConfigurationReader(Func lookup, Func? readFile = null) + { + ArgumentNullException.ThrowIfNull(lookup); + _lookup = lookup; + _readFile = readFile ?? File.ReadAllText; + } + + /// Reads every variable. + /// The options, with the reading problems in . + public KhaemhatOptions Read() + { + var errors = new List(); + string? Get(string name) => Value(name, errors); + + return new KhaemhatOptions + { + SystemDb = Get("KHAEMHAT_SYSTEM_DB"), + DbServer = Get("KHAEMHAT_DB_SERVER"), + SecretKey = Get("KHAEMHAT_SECRET_KEY"), + RotationSecretKey = Get("KHAEMHAT_SECRET_KEY_NEW"), + SuperUser = Get("KHAEMHAT_SUPERUSER"), + SuperUserPassword = Get("KHAEMHAT_SUPERUSER_PASSWORD"), + SuperUserEmail = Get("KHAEMHAT_SUPERUSER_EMAIL"), + CompanyCode = Get("KHAEMHAT_COMPANY_CODE"), + CompanyName = Get("KHAEMHAT_COMPANY_NAME"), + Country = Get("KHAEMHAT_COUNTRY") ?? "IT", + LicenseMode = Get("KHAEMHAT_LICENSE_MODE") ?? "production", + License = Get("KHAEMHAT_LICENSE"), + Redis = Get("KHAEMHAT_REDIS"), + DataDir = Get("KHAEMHAT_DATA_DIR") ?? "/data", + Urls = Get("KHAEMHAT_URLS"), + PublicUrl = Get("KHAEMHAT_PUBLIC_URL"), + SmtpHost = Get("KHAEMHAT_SMTP_HOST"), + SmtpPort = Get("KHAEMHAT_SMTP_PORT"), + SmtpUser = Get("KHAEMHAT_SMTP_USER"), + SmtpPassword = Get("KHAEMHAT_SMTP_PASSWORD"), + SmtpFrom = Get("KHAEMHAT_SMTP_FROM"), + SmtpSecurity = Get("KHAEMHAT_SMTP_SECURITY"), + LogLevel = Get("KHAEMHAT_LOG_LEVEL"), + SeedBase = Get("KHAEMHAT_SEED_BASE"), + SeedDemo = Get("KHAEMHAT_SEED_DEMO"), + UpdateFeed = Get("KHAEMHAT_UPDATE_FEED"), + UpdateToken = Get("KHAEMHAT_UPDATE_TOKEN"), + TimeZone = Get("TZ"), + ReadErrors = errors, + }; + } + + private string? Value(string name, List errors) + { + var direct = Normalize(_lookup(name)); + if (!FileVariables.Contains(name)) + { + return direct; + } + + var path = Normalize(_lookup(name + "_FILE")); + if (path is null) + { + return direct; + } + + if (direct is not null) + { + errors.Add($"{name} and {name}_FILE are both set: keep only one of them."); + return null; + } + + try + { + return Normalize(TrimFinalLineBreak(_readFile(path))); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + errors.Add($"{name}_FILE points to a file that cannot be read ({ex.GetType().Name}): check the path and the permissions of the secret."); + return null; + } + } + + private static string? Normalize(string? value) => string.IsNullOrWhiteSpace(value) ? null : value; + + private static string TrimFinalLineBreak(string value) + { + if (value.EndsWith("\r\n", StringComparison.Ordinal)) + { + return value[..^2]; + } + + return value.EndsWith('\n') ? value[..^1] : value; + } +} diff --git a/src/Khaemhat.Application/Configuration/KhaemhatOptions.cs b/src/Khaemhat.Application/Configuration/KhaemhatOptions.cs new file mode 100644 index 0000000..0a71204 --- /dev/null +++ b/src/Khaemhat.Application/Configuration/KhaemhatOptions.cs @@ -0,0 +1,356 @@ +using System.Globalization; +using System.Net.Mail; +using Khaemhat.Application.Security; +using Khaemhat.Data; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Configuration; + +/// How the licences behave (KHAEMHAT_LICENSE_MODE). +public enum LicenseMode +{ + /// Only signed licences count. + Production = 0, + + /// The fictitious codes of SPEC §8.3 are accepted too. Never in production. + Test = 1, +} + +/// The connection security of the mail server. +public enum SmtpSecurity +{ + /// STARTTLS on a plain connection (port 587). + StartTls = 0, + + /// TLS from the start (port 465). + Ssl = 1, + + /// No encryption: only for a local relay. + None = 2, +} + +/// A configuration that does not let the instance start. The message lists every problem, never a value. +public sealed class ConfigurationException : Exception +{ + /// Creates the exception. + public ConfigurationException() + : this([]) + { + } + + /// Creates the exception. + /// The message. + public ConfigurationException(string message) + : base(message) => Errors = [message]; + + /// Creates the exception. + /// The message. + /// The cause. + public ConfigurationException(string message, Exception innerException) + : base(message, innerException) => Errors = [message]; + + /// Creates the exception from a list of problems. + /// The problems. + public ConfigurationException(IReadOnlyList errors) + : base(Describe(errors)) => Errors = errors; + + /// The problems, one per line of the message. + public IReadOnlyList Errors { get; } + + private static string Describe(IReadOnlyList errors) => + "Khaemhat cannot start: the configuration is not valid (see docs/DEPLOY.md and the wiki page Installazione-Docker)." + + string.Concat((errors ?? []).Select(e => Environment.NewLine + " - " + e)); +} + +/// +/// The instance configuration of SPEC §6, read from the environment by . +/// Values stay in memory: nothing is written to disk. checks everything before the host starts; +/// the typed accessors (, ...) are meant for a validated instance. +/// +public sealed class KhaemhatOptions +{ + /// KHAEMHAT_SYSTEM_DB: the system database URL (required). + public string? SystemDb { get; init; } + + /// KHAEMHAT_DB_SERVER: the PostgreSQL server where company databases are created. + public string? DbServer { get; init; } + + /// KHAEMHAT_SECRET_KEY: base64 of at least 32 bytes (required). + public string? SecretKey { get; init; } + + /// KHAEMHAT_SECRET_KEY_NEW: the new key during a rotation (SPEC §12.9). + public string? RotationSecretKey { get; init; } + + /// KHAEMHAT_SUPERUSER: the super user name, read only while sys_users is empty. + public string? SuperUser { get; init; } + + /// KHAEMHAT_SUPERUSER_PASSWORD: its first password, to change at the first access. + public string? SuperUserPassword { get; init; } + + /// KHAEMHAT_SUPERUSER_EMAIL: its e-mail address. + public string? SuperUserEmail { get; init; } + + /// KHAEMHAT_COMPANY_CODE: the first company, read only while sys_companies is empty. + public string? CompanyCode { get; init; } + + /// KHAEMHAT_COMPANY_NAME: its name. + public string? CompanyName { get; init; } + + /// KHAEMHAT_COUNTRY: the fiscal package of the first company (default IT). + public string Country { get; init; } = "IT"; + + /// KHAEMHAT_LICENSE_MODE: production (default) or test. + public string LicenseMode { get; init; } = "production"; + + /// KHAEMHAT_LICENSE: the text of a .khl licence; absent means Trial. + public string? License { get; init; } + + /// KHAEMHAT_REDIS: redis:// or rediss://; absent means in-memory cache. + public string? Redis { get; init; } + + /// KHAEMHAT_DATA_DIR: the only folder the instance writes to (default /data). + public string DataDir { get; init; } = "/data"; + + /// KHAEMHAT_URLS: the listening addresses. + public string? Urls { get; init; } + + /// KHAEMHAT_PUBLIC_URL: the address users reach, for links in e-mails. + public string? PublicUrl { get; init; } + + /// KHAEMHAT_SMTP_HOST. + public string? SmtpHost { get; init; } + + /// KHAEMHAT_SMTP_PORT. + public string? SmtpPort { get; init; } + + /// KHAEMHAT_SMTP_USER. + public string? SmtpUser { get; init; } + + /// KHAEMHAT_SMTP_PASSWORD. + public string? SmtpPassword { get; init; } + + /// KHAEMHAT_SMTP_FROM. + public string? SmtpFrom { get; init; } + + /// KHAEMHAT_SMTP_SECURITY: starttls (default), ssl or none. + public string? SmtpSecurity { get; init; } + + /// KHAEMHAT_LOG_LEVEL: the minimum level on stdout. + public string? LogLevel { get; init; } + + /// KHAEMHAT_SEED_BASE: load the base tables when a company is created (default true). + public string? SeedBase { get; init; } + + /// KHAEMHAT_SEED_DEMO: load the demo data into an empty company (default false). + public string? SeedDemo { get; init; } + + /// KHAEMHAT_UPDATE_FEED: the package list read by the update check. + public string? UpdateFeed { get; init; } + + /// KHAEMHAT_UPDATE_TOKEN: a read-only token for the feed. + public string? UpdateToken { get; init; } + + /// TZ: the time zone of the container. + public string? TimeZone { get; init; } + + /// The problems met while reading (both X and X_FILE, unreadable files). + public IReadOnlyList ReadErrors { get; init; } = []; + + /// The system database, parsed. + public DatabaseUrl SystemDatabase => DatabaseUrl.Parse(SystemDb ?? throw new ConfigurationException("KHAEMHAT_SYSTEM_DB is not set.")); + + /// + /// Where company databases are created: when set, otherwise the server (PostgreSQL) or the + /// folder (SQLite) of the system database. + /// + public DatabaseUrl CompanyServer => DbServer is { } server ? DatabaseUrl.Parse(server) : SystemDatabase; + + /// The licence mode, parsed. + public LicenseMode Mode => string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase) + ? Configuration.LicenseMode.Test + : Configuration.LicenseMode.Production; + + /// Whether base data is loaded into new companies. + public bool SeedBaseEnabled => ParseBool(SeedBase) ?? true; + + /// Whether demo data is loaded into new, empty companies. + public bool SeedDemoEnabled => ParseBool(SeedDemo) ?? false; + + /// The SMTP port, defaulting by security mode. + public int SmtpPortNumber => int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) + ? port + : SmtpSecurityMode == Configuration.SmtpSecurity.Ssl ? 465 : 587; + + /// The SMTP security, parsed. + public SmtpSecurity SmtpSecurityMode => SmtpSecurity?.ToUpperInvariant() switch + { + "SSL" or "TLS" => Configuration.SmtpSecurity.Ssl, + "NONE" => Configuration.SmtpSecurity.None, + _ => Configuration.SmtpSecurity.StartTls, + }; + + /// + /// Checks the whole configuration. Messages name the variable and the expected form, never its value. + /// The variables needed only at first start (super user, first company) are checked by the bootstrap, which knows + /// whether the tables are still empty; here only their form is checked when they are set. + /// + /// The problems; empty when the instance can start. + public IReadOnlyList Validate() + { + var errors = new List(ReadErrors); + + if (SystemDb is null) + { + if (!ReadErrors.Any(e => e.StartsWith("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal))) + { + errors.Add("KHAEMHAT_SYSTEM_DB is required: postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db."); + } + } + else if (!DatabaseUrl.TryParse(SystemDb, out _)) + { + errors.Add("KHAEMHAT_SYSTEM_DB is not a valid database URL: use postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db."); + } + + if (DbServer is not null && (!DatabaseUrl.TryParse(DbServer, out var server) || server.Engine != DbEngine.PostgreSql)) + { + errors.Add("KHAEMHAT_DB_SERVER must be a PostgreSQL server URL: postgres://user:password@host:5432/ (a role with CREATEDB)."); + } + + CheckKey("KHAEMHAT_SECRET_KEY", SecretKey, required: true, errors); + CheckKey("KHAEMHAT_SECRET_KEY_NEW", RotationSecretKey, required: false, errors); + + if (SuperUser is not null && !UserNames.IsValid(SuperUser)) + { + errors.Add("KHAEMHAT_SUPERUSER must be 3 to 50 characters: letters, digits, dot, dash or underscore."); + } + + if (SuperUserEmail is not null && !IsEmail(SuperUserEmail)) + { + errors.Add("KHAEMHAT_SUPERUSER_EMAIL is not a valid e-mail address."); + } + + if (CompanyCode is not null && !CompanyCodes.IsValid(CompanyCode.Trim().ToUpperInvariant())) + { + errors.Add("KHAEMHAT_COMPANY_CODE must be 1 to 20 characters: letters, digits or underscore, starting with a letter."); + } + + if (CompanyName is { Length: > 200 }) + { + errors.Add("KHAEMHAT_COMPANY_NAME is longer than 200 characters."); + } + + if (!string.Equals(Country, "IT", StringComparison.OrdinalIgnoreCase)) + { + errors.Add("KHAEMHAT_COUNTRY: the only fiscal package available is IT."); + } + + if (!string.Equals(LicenseMode, "production", StringComparison.OrdinalIgnoreCase) + && !string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase)) + { + errors.Add("KHAEMHAT_LICENSE_MODE must be production or test."); + } + + if (Redis is not null && !(Uri.TryCreate(Redis, UriKind.Absolute, out var redis) && redis.Scheme is "redis" or "rediss")) + { + errors.Add("KHAEMHAT_REDIS must be redis://[:password@]host:6379/0 or rediss:// for TLS."); + } + + if (string.IsNullOrWhiteSpace(DataDir) || !Path.IsPathFullyQualified(DataDir)) + { + errors.Add("KHAEMHAT_DATA_DIR must be an absolute path (default /data)."); + } + + if (PublicUrl is not null && !IsHttpUrl(PublicUrl)) + { + errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com."); + } + + if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536)) + { + errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535."); + } + + if (SmtpSecurity is not null && SmtpSecurity.ToUpperInvariant() is not ("STARTTLS" or "SSL" or "TLS" or "NONE")) + { + errors.Add("KHAEMHAT_SMTP_SECURITY must be starttls, ssl or none."); + } + + if (SmtpFrom is not null && !IsEmail(SmtpFrom)) + { + errors.Add("KHAEMHAT_SMTP_FROM is not a valid e-mail address."); + } + + if (LogLevel is not null && !(Enum.TryParse(LogLevel, ignoreCase: true, out var level) && Enum.IsDefined(level))) + { + errors.Add("KHAEMHAT_LOG_LEVEL must be Trace, Debug, Information, Warning, Error, Critical or None."); + } + + if (SeedBase is not null && ParseBool(SeedBase) is null) + { + errors.Add("KHAEMHAT_SEED_BASE must be true or false."); + } + + if (SeedDemo is not null && ParseBool(SeedDemo) is null) + { + errors.Add("KHAEMHAT_SEED_DEMO must be true or false."); + } + + if (UpdateFeed is not null && !IsHttpUrl(UpdateFeed)) + { + errors.Add("KHAEMHAT_UPDATE_FEED must be an absolute http or https address."); + } + + if (TimeZone is not null && !TimeZoneInfo.TryFindSystemTimeZoneById(TimeZone, out _)) + { + errors.Add("TZ is not a known time zone, for example Europe/Rome."); + } + + return errors; + } + + /// Throws when finds problems. + /// The configuration is not valid. + public void EnsureValid() + { + var errors = Validate(); + if (errors.Count > 0) + { + throw new ConfigurationException(errors); + } + } + + private static void CheckKey(string name, string? value, bool required, List errors) + { + if (value is null) + { + if (required) + { + errors.Add($"{name} is required: the base64 of at least 32 random bytes (for example: openssl rand -base64 32)."); + } + + return; + } + + try + { + _ = Infrastructure.Security.SecretKey.FromBase64(value); + } + catch (FormatException ex) + { + errors.Add(ex.Message.Replace("KHAEMHAT_SECRET_KEY", name, StringComparison.Ordinal)); + } + } + + private static bool? ParseBool(string? value) => value?.Trim().ToUpperInvariant() switch + { + null => null, + "TRUE" or "1" or "YES" or "SI" => true, + "FALSE" or "0" or "NO" => false, + _ => null, + }; + + private static bool IsHttpUrl(string value) => + Uri.TryCreate(value, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps); + + private static bool IsEmail(string value) => MailAddress.TryCreate(value, out var address) && address.Address == value.Trim(); +} diff --git a/src/Khaemhat.Application/Instance/CompanyContext.cs b/src/Khaemhat.Application/Instance/CompanyContext.cs new file mode 100644 index 0000000..266f910 --- /dev/null +++ b/src/Khaemhat.Application/Instance/CompanyContext.cs @@ -0,0 +1,116 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Companies; + +namespace Khaemhat.Application.Instance; + +/// The outcome of choosing the company a request or a circuit works in. +public enum CompanyAccess +{ + /// The company can be used. + Granted = 0, + + /// No company chosen (an instance account on instance pages). + None = 1, + + /// The company does not exist. + NotFound = 2, + + /// A company account asked for another company. + Forbidden = 3, + + /// The company is in maintenance and the account is not an instance account. + Maintenance = 4, + + /// The company is disabled. + Disabled = 5, +} + +/// The company of the current request or Blazor circuit (SPEC §5.4). +/// Whether the company can be used. +/// The company, when it exists. +public sealed record CompanyContextResult(CompanyAccess Access, Company? Company) +{ + /// No company. + public static CompanyContextResult None { get; } = new(CompanyAccess.None, null); + + /// The company code, when granted. + public string? Code => Access == CompanyAccess.Granted ? Company!.Code : null; + + /// Whether writes are refused (company in ). + public bool IsReadOnly => Company?.Status == CompanyStatus.ReadOnly; + + /// Whether the company is temporarily unavailable (the API answers 503). + public bool IsUnavailable => Access is CompanyAccess.Maintenance or CompanyAccess.Disabled; + + /// The database scope of the company. + /// The scope. + /// No company is granted. + public DatabaseScope Scope() => + Access == CompanyAccess.Granted ? DatabaseScope.Company(Company!.Code) : throw new InvalidOperationException("No company is available in this context."); +} + +/// The company the current user works in. Scoped: one per request and one per Blazor circuit. +public interface ICompanyContext +{ + /// Resolves (once) and returns the company. + /// Cancellation. + /// The result. + ValueTask GetAsync(CancellationToken cancellationToken = default); +} + +/// +/// The rules that choose the company (SPEC §1.4, §5.4): company accounts work only in their own company; instance +/// accounts choose it (session company, or the X-Company header of an API call). A company in maintenance is open +/// only to instance accounts; a disabled company to nobody. +/// +/// The company registry. +public sealed class CompanyContextResolver(ICompanyRegistry companies) +{ + /// The header naming the company of an API call. + public const string Header = "X-Company"; + + /// Chooses the company. + /// The signed-in user, or . + /// The company asked by the request (header), or . + /// Cancellation. + /// The result. + public async Task ResolveAsync(Actor? actor, string? requested, CancellationToken cancellationToken = default) + { + if (actor is null) + { + return CompanyContextResult.None; + } + + requested = string.IsNullOrWhiteSpace(requested) ? null : requested.Trim().ToUpperInvariant(); + string? code; + if (actor.IsInstanceAccount) + { + code = requested ?? actor.CompanyCode; + } + else + { + if (requested is not null && !string.Equals(requested, actor.CompanyCode, StringComparison.OrdinalIgnoreCase)) + { + return new CompanyContextResult(CompanyAccess.Forbidden, null); + } + + code = actor.CompanyCode; + } + + if (code is null) + { + return CompanyContextResult.None; + } + + var company = await companies.FindAsync(code, cancellationToken).ConfigureAwait(false); + return company switch + { + null => new CompanyContextResult(CompanyAccess.NotFound, null), + { Status: CompanyStatus.Disabled } => new CompanyContextResult(CompanyAccess.Disabled, company), + { Status: CompanyStatus.Maintenance } when !actor.IsInstanceAccount => new CompanyContextResult(CompanyAccess.Maintenance, company), + _ => new CompanyContextResult(CompanyAccess.Granted, company), + }; + } +} diff --git a/src/Khaemhat.Application/Instance/CompanyService.cs b/src/Khaemhat.Application/Instance/CompanyService.cs new file mode 100644 index 0000000..387f15d --- /dev/null +++ b/src/Khaemhat.Application/Instance/CompanyService.cs @@ -0,0 +1,314 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Logging; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Migrations; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Instance; + +/// Where the databases of the instance are and which migrations they get. +/// The system database (KHAEMHAT_SYSTEM_DB). +/// Where new company databases are created (KHAEMHAT_DB_SERVER, or next to the system one). +/// The migrations of the system database. +/// The migrations of every company database. +public sealed record InstanceDatabases(DatabaseUrl System, DatabaseUrl CompanyServer, MigrationCatalog SystemMigrations, MigrationCatalog CompanyMigrations); + +/// A company to create. +/// The code (database khaemhat_<code>). +/// The company name. +/// Whether it becomes the default company. +/// Notes for administrators. +/// Whether to load the demo data. +public sealed record NewCompany(string Code, string Name, bool IsDefault = false, string? Notes = null, bool SeedDemo = false); + +/// +/// Fills a new or migrated company database. Modules register their own: base data at creation (plan of accounts, VAT +/// codes) and demo data when asked (SPEC §5.5). Seeders must be idempotent: they run again at every start. +/// +public interface ICompanySeeder +{ + /// The order among seeders (lower first). + int Order { get; } + + /// Fills the database. + /// The company. + /// What to load. + /// Cancellation. + /// A task. + Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default); +} + +/// What a seeder is asked to load. +/// Whether the database was just created. +/// Whether the base data is wanted (KHAEMHAT_SEED_BASE). +/// Whether the demo data is wanted. +public sealed record CompanySeedContext(bool IsNew, bool Base, bool Demo); + +/// The predefined roles of SPEC §7.2, kept equal to their templates in every company. +/// The role service. +public sealed class PredefinedRolesSeeder(RoleService roles) : ICompanySeeder +{ + /// + public int Order => 0; + + /// + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) => + roles.SyncPredefinedRolesAsync(companyCode, cancellationToken); +} + +/// +/// Creates, attaches and migrates company databases (SPEC §5.4, §12.1; mockup 080). Creating a company is an +/// instance administration task: super user or administrators. The number of companies is limited by the licence +/// (module MULTI). +/// +public sealed class CompanyService +{ + private readonly ICompanyRegistry _registry; + private readonly DbProviderCatalog _providers; + private readonly MigrationRunner _migrations; + private readonly InstanceDatabases _databases; + private readonly ILicenseGate _licenses; + private readonly SessionStore _sessions; + private readonly ISecurityAuditLog _audit; + private readonly IReadOnlyList _seeders; + private readonly ILogger _logger; + + /// Creates the service. + /// The company registry. + /// The database providers. + /// Applies migrations. + /// Where databases are. + /// The licence in force. + /// The sessions (revoked when a company goes into maintenance). + /// The security audit. + /// The seeders of the modules. + /// The log. + public CompanyService( + ICompanyRegistry registry, DbProviderCatalog providers, MigrationRunner migrations, InstanceDatabases databases, ILicenseGate licenses, + SessionStore sessions, ISecurityAuditLog audit, IEnumerable seeders, ILogger logger) + { + ArgumentNullException.ThrowIfNull(registry); + ArgumentNullException.ThrowIfNull(providers); + ArgumentNullException.ThrowIfNull(migrations); + ArgumentNullException.ThrowIfNull(databases); + ArgumentNullException.ThrowIfNull(licenses); + ArgumentNullException.ThrowIfNull(sessions); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(seeders); + ArgumentNullException.ThrowIfNull(logger); + _registry = registry; + _providers = providers; + _migrations = migrations; + _databases = databases; + _licenses = licenses; + _sessions = sessions; + _audit = audit; + _seeders = [.. seeders.OrderBy(s => s.Order)]; + _logger = logger; + } + + /// The companies of the instance. + /// Cancellation. + /// The companies by code. + public Task> ListAsync(CancellationToken cancellationToken = default) => _registry.ListAsync(cancellationToken); + + /// + /// Creates a company: a new database khaemhat_<code> on the company server, registered, migrated and + /// filled by the seeders. + /// + /// Who acts: an instance account. + /// The company. + /// Cancellation. + /// The registered company. + /// The actor is not an instance account, or the licence allows no more companies. + public async Task CreateAsync(Actor actor, NewCompany company, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(company); + RequireInstanceAdministrator(actor); + var code = Validate(company.Code, company.Name); + await RequireRoomAsync(cancellationToken).ConfigureAwait(false); + + var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code)); + var target = _providers.Resolve(url); + if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false)) + { + throw new ValidationFailedException([$"Il database {url.DatabaseName} esiste già: usa «Collega database esistente»."]); + } + + await target.Provider.EnsureDatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false); + var registered = await _registry.RegisterAsync(new CompanyRegistration(code, company.Name, url, company.IsDefault, company.Notes), cancellationToken) + .ConfigureAwait(false); + await PrepareAsync(registered, new CompanySeedContext(IsNew: true, Base: true, Demo: company.SeedDemo), cancellationToken).ConfigureAwait(false); + await _audit.WriteAsync(new SecurityEvent("company.created", actor.UserName, Target: code), cancellationToken).ConfigureAwait(false); + return registered; + } + + /// + /// Attaches an existing company database (restored from a backup or moved from another instance) and migrates it. + /// + /// Who acts: an instance account. + /// The company code. + /// The company name. + /// Where the database is. + /// Cancellation. + /// The registered company. + public async Task AttachAsync(Actor actor, string code, string name, DatabaseUrl database, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(database); + RequireInstanceAdministrator(actor); + var normalized = Validate(code, name); + await RequireRoomAsync(cancellationToken).ConfigureAwait(false); + + var target = _providers.Resolve(database); + if (!await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false)) + { + throw new ValidationFailedException(["Il database indicato non esiste o non è raggiungibile."]); + } + + var registered = await _registry.RegisterAsync(new CompanyRegistration(normalized, name, database), cancellationToken).ConfigureAwait(false); + await PrepareAsync(registered, new CompanySeedContext(IsNew: false, Base: false, Demo: false), cancellationToken).ConfigureAwait(false); + await _audit.WriteAsync(new SecurityEvent("company.attached", actor.UserName, Target: normalized), cancellationToken).ConfigureAwait(false); + return registered; + } + + /// + /// Changes the state of a company. Maintenance and disabling sign out its users at once; instance accounts can still + /// open a company in maintenance. + /// + /// Who acts: an instance account. + /// The company. + /// The new state. + /// Cancellation. + /// A task. + public async Task SetStatusAsync(Actor actor, string code, CompanyStatus status, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + RequireInstanceAdministrator(actor); + await _registry.SetStatusAsync(code, status, cancellationToken).ConfigureAwait(false); + if (status is CompanyStatus.Maintenance or CompanyStatus.Disabled) + { + var revoked = await _sessions.RevokeCompanyAsync(code, "company-" + status.ToString().ToLowerInvariant(), cancellationToken).ConfigureAwait(false); + _logger.LogInformation("Company {Company} is now {Status}: {Count} sessions closed.", code, status, revoked); + } + + await _audit.WriteAsync( + new SecurityEvent("company.status", actor.UserName, Target: CompanyCodes.Normalize(code), Details: status.ToString()), cancellationToken).ConfigureAwait(false); + } + + /// + /// Migrates every company that is not disabled and runs the seeders again (at each start). A company whose + /// migration fails is put in maintenance and logged; the others go on. + /// + /// Whether demo data is wanted (KHAEMHAT_SEED_DEMO). + /// Cancellation. + /// The companies that failed. + public async Task> PrepareAllAsync(bool seedDemo, CancellationToken cancellationToken = default) + { + var failed = new List(); + foreach (var company in await _registry.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (company.Status == CompanyStatus.Disabled) + { + continue; + } + + try + { + await PrepareAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: seedDemo), cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + failed.Add(company.Code); + using (_logger.BeginScope(LogSections.Scope(LogSection.Migrations))) + { + _logger.LogError(ex, "Company {Company} could not be migrated: it is put in maintenance.", company.Code); + } + + await _registry.SetStatusAsync(company.Code, CompanyStatus.Maintenance, cancellationToken).ConfigureAwait(false); + } + } + + return failed; + } + + private async Task PrepareAsync(Company company, CompanySeedContext context, CancellationToken cancellationToken) + { + var target = await _registry.ResolveAsync(company.Code, cancellationToken).ConfigureAwait(false); + var report = await _migrations.RunAsync(target, _databases.CompanyMigrations, cancellationToken).ConfigureAwait(false); + LogMigrations(_logger, report, company.Code); + foreach (var seeder in _seeders) + { + await seeder.SeedAsync(company.Code, context, cancellationToken).ConfigureAwait(false); + } + } + + /// Writes a migration report in the section Migrazioni. + /// The log. + /// The report. + /// The company, or for the system database. + public static void LogMigrations(ILogger logger, MigrationReport report, string? companyCode) + { + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(report); + using var section = logger.BeginScope(LogSections.Scope(LogSection.Migrations)); + using var company = logger.BeginScope(new Dictionary { [LogSections.CompanyKey] = companyCode }); + foreach (var (migration, duration) in report.Applied) + { + logger.LogInformation("Migration {Migration} applied to {Database} in {Milliseconds} ms.", migration.ToString(), report.Database, (long)duration.TotalMilliseconds); + } + + foreach (var warning in report.Warnings) + { + logger.LogWarning("Database {Database}: {Warning}", report.Database, warning); + } + + if (report.Applied.Count == 0) + { + logger.LogDebug("Database {Database} is up to date ({Count} migrations).", report.Database, report.AlreadyApplied); + } + } + + private static string Validate(string code, string name) + { + var errors = new List(); + if (!CompanyCodes.IsValid((code ?? string.Empty).Trim().ToUpperInvariant())) + { + errors.Add("Il codice azienda deve avere da 1 a 20 caratteri tra lettere, cifre e trattino basso."); + } + + if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > 200) + { + errors.Add("La ragione sociale è obbligatoria (al massimo 200 caratteri)."); + } + + return errors.Count > 0 ? throw new ValidationFailedException(errors) : CompanyCodes.Normalize(code!); + } + + private async Task RequireRoomAsync(CancellationToken cancellationToken) + { + var limit = _licenses.Current.MaxCompanies; + var count = (await _registry.ListAsync(cancellationToken).ConfigureAwait(false)).Count; + if (count >= limit) + { + throw new AccessDeniedException( + SecurityErrors.LicenseLimitReached, + limit <= 1 + ? "La licenza consente una sola azienda: per gestirne altre serve il modulo Multi-azienda (MULTI)." + : $"La licenza consente al massimo {limit} aziende."); + } + } + + private static void RequireInstanceAdministrator(Actor actor) + { + if (!actor.IsInstanceAccount) + { + throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Solo gli account di istanza possono gestire le aziende."); + } + } +} diff --git a/src/Khaemhat.Application/Instance/StartupOrchestrator.cs b/src/Khaemhat.Application/Instance/StartupOrchestrator.cs new file mode 100644 index 0000000..51dd9d6 --- /dev/null +++ b/src/Khaemhat.Application/Instance/StartupOrchestrator.cs @@ -0,0 +1,264 @@ +using System.Globalization; +using Khaemhat.Application.Configuration; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Core.Logging; +using Khaemhat.Data; +using Khaemhat.Data.Migrations; +using Khaemhat.Infrastructure.Logging; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Instance; + +/// Where the start of the instance is. +public enum BootstrapPhase +{ + /// Migrations and first-start setup in progress: /health/ready answers 503. + Starting = 0, + + /// Ready to serve. + Ready = 1, + + /// The start failed; the process is stopping. + Failed = 2, +} + +/// The start state, read by the readiness endpoint and the middleware. +public sealed class BootstrapState +{ + private volatile BootstrapPhase _phase; + + /// The phase. + public BootstrapPhase Phase => _phase; + + /// Whether the instance serves requests. + public bool IsReady => _phase == BootstrapPhase.Ready; + + /// Why the start failed (no secrets). + public string? Error { get; private set; } + + /// Companies put in maintenance because their migration failed. + public IReadOnlyList FailedCompanies { get; private set; } = []; + + /// Marks the start as completed. + /// The companies that could not be migrated. + public void MarkReady(IReadOnlyList failedCompanies) + { + FailedCompanies = failedCompanies ?? []; + _phase = BootstrapPhase.Ready; + } + + /// Marks the start as failed. + /// Why. + public void MarkFailed(string error) + { + Error = error; + _phase = BootstrapPhase.Failed; + } +} + +/// +/// The start sequence (SPEC §5.3, §7.1, §8, §23): migrate the system database, start writing the log there, fix the +/// instance identifier and the trial start, seed the role templates, compute the licence, create the super user and the +/// first company from the variables when the tables are empty, then migrate every company. Every step is idempotent: a +/// second start, or two instances starting together, change nothing. +/// +public sealed class StartupOrchestrator +{ + private readonly InstanceDatabases _databases; + private readonly DbProviderCatalog _providers; + private readonly MigrationRunner _migrations; + private readonly SystemSettingsStore _settings; + private readonly RoleService _roles; + private readonly ILicenseGate _licenses; + private readonly SystemUserService _systemUsers; + private readonly CompanyService _companies; + private readonly KhaemhatOptions _options; + private readonly IUnitOfWorkFactory _factory; + private readonly DbLogSink? _logSink; + private readonly BootstrapState _state; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + private bool _systemReady; + + /// Creates the orchestrator. + /// Where databases are. + /// The providers. + /// Applies migrations. + /// The instance settings. + /// The role templates. + /// The licence. + /// The instance accounts. + /// The companies. + /// The variables. + /// Opens the databases. + /// The database log, started once the system database is ready (absent in some tests). + /// The start state. + /// The clock. + /// The log. + public StartupOrchestrator( + InstanceDatabases databases, DbProviderCatalog providers, MigrationRunner migrations, SystemSettingsStore settings, RoleService roles, + ILicenseGate licenses, SystemUserService systemUsers, CompanyService companies, KhaemhatOptions options, IUnitOfWorkFactory factory, + DbLogSink? logSink, BootstrapState state, TimeProvider clock, ILogger logger) + { + ArgumentNullException.ThrowIfNull(databases); + ArgumentNullException.ThrowIfNull(providers); + ArgumentNullException.ThrowIfNull(migrations); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(roles); + ArgumentNullException.ThrowIfNull(licenses); + ArgumentNullException.ThrowIfNull(systemUsers); + ArgumentNullException.ThrowIfNull(companies); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(state); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _databases = databases; + _providers = providers; + _migrations = migrations; + _settings = settings; + _roles = roles; + _licenses = licenses; + _systemUsers = systemUsers; + _companies = companies; + _options = options; + _factory = factory; + _logSink = logSink; + _state = state; + _clock = clock; + _logger = logger; + } + + /// + /// Creates (when missing) and migrates the system database, then starts writing the log there. It runs before the + /// host starts serving, because DataProtection and sessions read the system database from the first request. + /// + /// Cancellation (host stopping). + /// A task. + public async Task PrepareSystemDatabaseAsync(CancellationToken cancellationToken = default) + { + if (_systemReady) + { + return; + } + + using var section = _logger.BeginScope(LogSections.Scope(LogSection.System)); + var system = _providers.Resolve(_databases.System); + await system.Provider.EnsureDatabaseExistsAsync(system.ConnectionString, cancellationToken).ConfigureAwait(false); + var report = await _migrations.RunAsync(system, _databases.SystemMigrations, cancellationToken).ConfigureAwait(false); + CompanyService.LogMigrations(_logger, report, null); + _logSink?.Start(_factory); + _systemReady = true; + } + + /// Runs the start sequence and marks the state ready. + /// Cancellation (host stopping). + /// A task. + /// First start without the variables it needs. + public async Task RunAsync(CancellationToken cancellationToken = default) + { + // 1. System database: created when missing (SQLite file, PostgreSQL database if the role may), then migrated. + await PrepareSystemDatabaseAsync(cancellationToken).ConfigureAwait(false); + using var section = _logger.BeginScope(LogSections.Scope(LogSection.System)); + + // 2. Instance identity and trial start, fixed at the first start and never changed. + await _settings.GetOrAddAsync(SystemSettingsStore.InstanceIdKey, Guid.NewGuid().ToString("D"), cancellationToken).ConfigureAwait(false); + await _settings.GetOrAddAsync( + SystemSettingsStore.TrialStartedKey, _clock.GetUtcNow().UtcDateTime.ToString("O", CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false); + + // 3. Role templates and licence. + await _roles.SeedTemplatesAsync(cancellationToken).ConfigureAwait(false); + var license = await _licenses.RefreshAsync(cancellationToken).ConfigureAwait(false); + _logger.LogInformation( + "License: {Kind} {Status}, modules {Modules}, {Users} concurrent users, {Companies} companies.", + license.Kind, license.Status, string.Join(',', license.Modules.Order(StringComparer.Ordinal)), license.MaxConcurrentUsers, license.MaxCompanies); + + // 4. Super user, only when there is no instance account at all. + if (!await _systemUsers.AnyAsync(cancellationToken).ConfigureAwait(false)) + { + await CreateSuperUserAsync(cancellationToken).ConfigureAwait(false); + } + + // 5. First company, only when the registry is empty. + if ((await _companies.ListAsync(cancellationToken).ConfigureAwait(false)).Count == 0) + { + await CreateFirstCompanyAsync(cancellationToken).ConfigureAwait(false); + } + + // 6. Every company migrated and seeded again. + var failed = await _companies.PrepareAllAsync(_options.SeedDemoEnabled, cancellationToken).ConfigureAwait(false); + _state.MarkReady(failed); + _logger.LogInformation("Khaemhat is ready."); + } + + private async Task CreateSuperUserAsync(CancellationToken cancellationToken) + { + var missing = new List(); + if (_options.SuperUser is null) + { + missing.Add("KHAEMHAT_SUPERUSER is required at the first start: the user name of the super user."); + } + + if (_options.SuperUserPassword is null) + { + missing.Add("KHAEMHAT_SUPERUSER_PASSWORD (or KHAEMHAT_SUPERUSER_PASSWORD_FILE) is required at the first start: the first password of the super user."); + } + + if (missing.Count > 0) + { + throw new ConfigurationException(missing); + } + + try + { + var user = await _systemUsers.CreateSuperUserAsync( + new NewSystemUser(_options.SuperUser!, _options.SuperUser!, _options.SuperUserEmail), _options.SuperUserPassword!, cancellationToken).ConfigureAwait(false); + _logger.LogInformation("Super user {UserName} created: change the password and set up the two-step verification at the first access.", user.UserName); + } + catch (ValidationFailedException ex) + { + throw new ConfigurationException([.. ex.Errors.Select(e => "KHAEMHAT_SUPERUSER_PASSWORD does not satisfy the password policy: " + e)]); + } + catch (InvalidOperationException) + { + // Another instance created it a moment ago. + } + } + + private async Task CreateFirstCompanyAsync(CancellationToken cancellationToken) + { + var code = _options.CompanyCode?.Trim().ToUpperInvariant(); + if (code is null) + { + _logger.LogWarning("No company exists and KHAEMHAT_COMPANY_CODE is not set: create the first company from Amministrazione > Aziende."); + return; + } + + try + { + var name = string.IsNullOrWhiteSpace(_options.CompanyName) ? code : _options.CompanyName.Trim(); + var url = _databases.CompanyServer.WithDatabase(CompanyCodes.DatabaseName(code)); + var target = _providers.Resolve(url); + if (!url.IsInMemory && await target.Provider.DatabaseExistsAsync(target.ConnectionString, cancellationToken).ConfigureAwait(false)) + { + // The system database was recreated but the company one survived: attach it instead of refusing. + await _companies.AttachAsync(Actor.System, code, name, url, cancellationToken).ConfigureAwait(false); + _logger.LogWarning("Company database {Database} already existed: attached as company {Company}.", url.DatabaseName, code); + return; + } + + await _companies.CreateAsync(Actor.System, new NewCompany(code, name, IsDefault: true, SeedDemo: _options.SeedDemoEnabled), cancellationToken) + .ConfigureAwait(false); + _logger.LogInformation("Company {Company} created.", code); + } + catch (InvalidOperationException) + { + // Another instance registered it a moment ago; anything else is a real failure. + if ((await _companies.ListAsync(cancellationToken).ConfigureAwait(false)).Count == 0) + { + throw; + } + } + } +} diff --git a/src/Khaemhat.Application/Instance/SystemSettingsStore.cs b/src/Khaemhat.Application/Instance/SystemSettingsStore.cs new file mode 100644 index 0000000..139ad16 --- /dev/null +++ b/src/Khaemhat.Application/Instance/SystemSettingsStore.cs @@ -0,0 +1,82 @@ +using Khaemhat.Core.Instance; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Instance; + +/// +/// Instance settings in sys_settings. Secret values are encrypted with the instance key and the purpose +/// setting:<key>. +/// +/// Opens the system database. +/// Encrypts secret values. +public sealed class SystemSettingsStore(IUnitOfWorkFactory factory, ISecretProtector protector) +{ + /// The identifier of the instance, created at first start. + public const string InstanceIdKey = "instance.id"; + + /// When the trial started (ISO 8601 UTC), set at first start. + public const string TrialStartedKey = "license.trial-started-at"; + + /// Reads a setting. + /// The key. + /// Cancellation. + /// The value (decrypted when secret), or . + public async Task GetAsync(string key, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var setting = await unitOfWork.Repository().FindAsync(Query.For().Where(s => s.Key == key), cancellationToken) + .ConfigureAwait(false); + if (setting?.Value is null) + { + return null; + } + + return setting.IsSecret ? protector.Unprotect(setting.Value, Purpose(key)) : setting.Value; + } + + /// Writes a setting. + /// The key. + /// The value. + /// Whether to encrypt it. + /// Cancellation. + /// A task. + public async Task SetAsync(string key, string? value, bool secret = false, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var settings = unitOfWork.Repository(); + var stored = value is null || !secret ? value : protector.Protect(value, Purpose(key)); + var setting = await settings.FindAsync(Query.For().Where(s => s.Key == key), cancellationToken).ConfigureAwait(false); + if (setting is null) + { + await settings.InsertAsync(new SystemSetting { Key = key, Value = stored, IsSecret = secret }, cancellationToken).ConfigureAwait(false); + return; + } + + setting.Value = stored; + setting.IsSecret = secret; + await settings.UpdateAsync(setting, cancellationToken).ConfigureAwait(false); + } + + /// Writes a setting only if it does not exist yet (bootstrap values such as the instance id). + /// The key. + /// The value. + /// Cancellation. + /// The value now stored. + public async Task GetOrAddAsync(string key, string value, CancellationToken cancellationToken = default) + { + var existing = await GetAsync(key, cancellationToken).ConfigureAwait(false); + if (existing is not null) + { + return existing; + } + + await SetAsync(key, value, secret: false, cancellationToken).ConfigureAwait(false); + return value; + } + + private static string Purpose(string key) => "setting:" + key; +} diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs new file mode 100644 index 0000000..b57bad6 --- /dev/null +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -0,0 +1,361 @@ +using System.Diagnostics; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Notifications; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Logging; +using Khaemhat.Core.Scheduling; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Jobs; + +/// What a job run receives. +/// The task (code, company, parameters). +/// The attempt number, from 1. +/// The trace identifier of the run, also in the log. +public sealed record JobContext(ScheduledTask Task, int Attempt, string TraceId); + +/// +/// A kind of job the scheduler can run (SPEC §9.4). Modules register theirs (e-mail import, SDI polling, reminders, +/// backups); is what sys_scheduled_tasks.job_type names. +/// +public interface IScheduledJob +{ + /// The job type. + string Type { get; } + + /// Runs the job. The token is cancelled at the task timeout or at shutdown. + /// The run. + /// Cancellation. + /// A message for the run history, or . + Task RunAsync(JobContext context, CancellationToken cancellationToken); +} + +/// A task created at start when missing. +/// The task code. +/// The name shown. +/// The job type. +/// When it runs. +/// Its timeout. +public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600); + +/// +/// The scheduler (SPEC §9.4; mockup 083): reads sys_scheduled_tasks, runs the due ones with a lock in +/// sys_job_locks (so two instances never run the same task together), applies timeout and retries, writes +/// sys_job_runs and the section Attività programmate of the log, and notifies the instance accounts when a +/// task fails for good. +/// +public sealed class JobScheduler +{ + /// The system tasks of M2. + public static readonly IReadOnlyList SystemTasks = + [ + new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300), + new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120), + new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800), + ]; + + private readonly IUnitOfWorkFactory _factory; + private readonly Dictionary _jobs; + private readonly NotificationDispatcher _notifications; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + private readonly string _owner = Environment.MachineName + ":" + Environment.ProcessId; + + /// Creates the scheduler. + /// Opens the system database. + /// The job types. + /// Notifies failures. + /// The clock. + /// The log. + public JobScheduler(IUnitOfWorkFactory factory, IEnumerable jobs, NotificationDispatcher notifications, TimeProvider clock, ILogger logger) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(jobs); + ArgumentNullException.ThrowIfNull(notifications); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _factory = factory; + _jobs = jobs.ToDictionary(j => j.Type, StringComparer.Ordinal); + _notifications = notifications; + _clock = clock; + _logger = logger; + } + + /// Creates the system tasks that are missing and computes the next run of every task without one. + /// Cancellation. + /// A task. + public async Task EnsureSystemTasksAsync(CancellationToken cancellationToken = default) + { + var now = _clock.GetUtcNow().UtcDateTime; + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var tasks = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + await unitOfWork.AcquireLockAsync("scheduler-setup", ct).ConfigureAwait(false); + foreach (var definition in SystemTasks) + { + var code = definition.Code; + if (await tasks.CountAsync(Query.For().Where(t => t.Code == code), ct).ConfigureAwait(false) == 0) + { + var task = new ScheduledTask + { + Code = code, + Name = definition.Name, + JobType = definition.JobType, + Cron = definition.Cron, + TimeoutSeconds = definition.TimeoutSeconds, + IsSystem = true, + }; + task.NextRunAt = Next(task, now); + await tasks.InsertAsync(task, ct).ConfigureAwait(false); + } + } + }, + cancellationToken).ConfigureAwait(false); + } + + /// Runs every enabled task that is due, one after the other. + /// Cancellation (shutdown). + /// How many tasks ran. + public async Task RunDueAsync(CancellationToken cancellationToken = default) + { + var now = _clock.GetUtcNow().UtcDateTime; + IReadOnlyList due; + await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) + { + due = (await unitOfWork.Repository().ListAsync( + Query.For().Where(t => t.IsEnabled && t.NextRunAt != null && t.NextRunAt <= now).OrderBy(t => t.NextRunAt), cancellationToken) + .ConfigureAwait(false)).Items; + } + + var count = 0; + foreach (var task in due) + { + cancellationToken.ThrowIfCancellationRequested(); + if (await RunAsync(task.Code, cancellationToken).ConfigureAwait(false) is not JobOutcome.Skipped) + { + count++; + } + } + + return count; + } + + /// Runs a task now (also "Esegui ora" from the administration page). + /// The task code. + /// Cancellation. + /// The outcome; when another run holds the lock. + public async Task RunAsync(string code, CancellationToken cancellationToken = default) + { + ScheduledTask? task; + await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) + { + task = await unitOfWork.Repository().FindAsync(Query.For().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false); + } + + if (task is null) + { + throw new KeyNotFoundException($"No scheduled task has code {code}."); + } + + var timeout = TimeSpan.FromSeconds(Math.Max(1, task.TimeoutSeconds)); + if (!await TryLockAsync(task.Code, timeout, cancellationToken).ConfigureAwait(false)) + { + return JobOutcome.Skipped; + } + + try + { + return await RunLockedAsync(task, timeout, cancellationToken).ConfigureAwait(false); + } + finally + { + await UnlockAsync(task.Code).ConfigureAwait(false); + } + } + + private async Task RunLockedAsync(ScheduledTask task, TimeSpan timeout, CancellationToken cancellationToken) + { + using var section = _logger.BeginScope(LogSections.Scope(LogSection.ScheduledJobs)); + var outcome = JobOutcome.Failed; + string? message = null; + for (var attempt = 1; attempt <= task.MaxRetries + 1; attempt++) + { + var traceId = ActivityTraceId.CreateRandom().ToString(); + using var scope = _logger.BeginScope(new Dictionary { [LogSections.TraceIdKey] = traceId, [LogSections.CompanyKey] = task.CompanyCode }); + var run = new JobRun { TaskCode = task.Code, StartedAt = _clock.GetUtcNow().UtcDateTime, Outcome = JobOutcome.Running, Attempt = attempt, TraceId = traceId }; + run.Id = await SaveRunAsync(run, insert: true, cancellationToken).ConfigureAwait(false); + (outcome, message) = await ExecuteAsync(task, new JobContext(task, attempt, traceId), timeout, cancellationToken).ConfigureAwait(false); + run.Outcome = outcome; + run.Message = message is { Length: > 2000 } ? message[..2000] : message; + run.FinishedAt = _clock.GetUtcNow().UtcDateTime; + await SaveRunAsync(run, insert: false, CancellationToken.None).ConfigureAwait(false); + if (outcome == JobOutcome.Succeeded || cancellationToken.IsCancellationRequested) + { + break; + } + } + + await FinishAsync(task, outcome, cancellationToken).ConfigureAwait(false); + if (outcome is JobOutcome.Failed or JobOutcome.TimedOut) + { + await _notifications.NotifyInstanceAsync( + new NotificationMessage("jobs", NotificationSeverity.Error, $"Attività «{task.Name}» non riuscita", message, "/amministrazione/attivita"), + cancellationToken: CancellationToken.None).ConfigureAwait(false); + } + + return outcome; + } + + private async Task<(JobOutcome Outcome, string? Message)> ExecuteAsync(ScheduledTask task, JobContext context, TimeSpan timeout, CancellationToken cancellationToken) + { + if (!_jobs.TryGetValue(task.JobType, out var job)) + { + _logger.LogError("Task {Task}: job type {JobType} is not known.", task.Code, task.JobType); + return (JobOutcome.Failed, "Tipo di attività sconosciuto: " + task.JobType); + } + + using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutSource.CancelAfter(timeout); + var started = Stopwatch.GetTimestamp(); + try + { + var message = await job.RunAsync(context, timeoutSource.Token).ConfigureAwait(false); + _logger.LogInformation("Task {Task} completed in {Milliseconds} ms. {Message}", task.Code, (long)Stopwatch.GetElapsedTime(started).TotalMilliseconds, message); + return (JobOutcome.Succeeded, message); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + _logger.LogError("Task {Task} stopped after the timeout of {Seconds} s (attempt {Attempt}).", task.Code, (int)timeout.TotalSeconds, context.Attempt); + return (JobOutcome.TimedOut, $"Interrotta dopo {(int)timeout.TotalSeconds} secondi."); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogError(ex, "Task {Task} failed (attempt {Attempt}).", task.Code, context.Attempt); + return (JobOutcome.Failed, ex.Message); + } + } + + private async Task FinishAsync(ScheduledTask task, JobOutcome outcome, CancellationToken cancellationToken) + { + var now = _clock.GetUtcNow().UtcDateTime; + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, CancellationToken.None).ConfigureAwait(false); + var tasks = unitOfWork.Repository(); + var current = await tasks.GetAsync(task.Id, CancellationToken.None).ConfigureAwait(false); + if (current is null) + { + return; + } + + current.LastRunAt = now; + current.LastOutcome = outcome; + current.NextRunAt = Next(current, now); + await tasks.UpdateAsync(current, cancellationToken.IsCancellationRequested ? CancellationToken.None : cancellationToken).ConfigureAwait(false); + } + + private async Task SaveRunAsync(JobRun run, bool insert, CancellationToken cancellationToken) + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var runs = unitOfWork.Repository(); + if (insert) + { + return await runs.InsertAsync(run, cancellationToken).ConfigureAwait(false); + } + + await runs.UpdateAsync(run, cancellationToken).ConfigureAwait(false); + return run.Id; + } + + // A lock row per task; an expired lock (a process that died) is taken over. + private async Task TryLockAsync(string code, TimeSpan timeout, CancellationToken cancellationToken) + { + var now = _clock.GetUtcNow().UtcDateTime; + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var locks = unitOfWork.Repository(); + var acquired = false; + await unitOfWork.InTransactionAsync( + async ct => + { + await unitOfWork.AcquireLockAsync("job-locks", ct).ConfigureAwait(false); + var existing = await locks.GetAsync(code, ct).ConfigureAwait(false); + if (existing is not null && existing.ExpiresAt > now) + { + return; + } + + if (existing is not null) + { + await locks.DeleteAsync(code, ct).ConfigureAwait(false); + } + + await locks.InsertAsync(new JobLock { Id = code, Owner = _owner, AcquiredAt = now, ExpiresAt = now + timeout + TimeSpan.FromMinutes(1) }, ct).ConfigureAwait(false); + acquired = true; + }, + cancellationToken).ConfigureAwait(false); + return acquired; + } + + private async Task UnlockAsync(string code) + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, CancellationToken.None).ConfigureAwait(false); + var owner = _owner; + await unitOfWork.ExecuteAsync( + SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier("sys_job_locks")} WHERE id = {code} AND owner = {owner}"), CancellationToken.None).ConfigureAwait(false); + } + + private DateTime? Next(ScheduledTask task, DateTime now) + { + if (!CronExpression.TryParse(task.Cron, out var cron, out _)) + { + _logger.LogError("Task {Task}: the cron expression '{Cron}' is not valid; the task will not run.", task.Code, task.Cron); + return null; + } + + var zone = TimeZoneInfo.TryFindSystemTimeZoneById(task.TimeZone, out var found) ? found : TimeZoneInfo.Utc; + return cron.NextAfter(now, zone); + } +} + +/// Runs the scheduler every 30 seconds once the instance is ready. +/// The scheduler. +/// The start state. +/// The log. +public sealed class JobSchedulerService(JobScheduler scheduler, BootstrapState state, ILogger logger) : BackgroundService +{ + /// How often due tasks are looked for. + public static readonly TimeSpan Interval = TimeSpan.FromSeconds(30); + + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!state.IsReady) + { + if (state.Phase == BootstrapPhase.Failed) + { + return; + } + + await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken).ConfigureAwait(false); + } + + await scheduler.EnsureSystemTasksAsync(stoppingToken).ConfigureAwait(false); + using var timer = new PeriodicTimer(Interval); + do + { + try + { + await scheduler.RunDueAsync(stoppingToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + using var section = logger.BeginScope(LogSections.Scope(LogSection.ScheduledJobs)); + logger.LogError(ex, "The scheduler could not read the tasks."); + } + } + while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)); + } +} diff --git a/src/Khaemhat.Application/Jobs/SystemJobs.cs b/src/Khaemhat.Application/Jobs/SystemJobs.cs new file mode 100644 index 0000000..ad6f543 --- /dev/null +++ b/src/Khaemhat.Application/Jobs/SystemJobs.cs @@ -0,0 +1,119 @@ +using System.Globalization; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Notifications; +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Companies; + +namespace Khaemhat.Application.Jobs; + +/// Deletes sessions expired or revoked more than 30 days ago, in the system database and in every company. +/// The sessions. +/// The companies. +public sealed class SessionCleanupJob(SessionStore sessions, ICompanyRegistry companies) : IScheduledJob +{ + /// The job type. + public const string JobType = "system.sessions-cleanup"; + + /// How long ended sessions stay for the history. + public static readonly TimeSpan Keep = TimeSpan.FromDays(30); + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + var deleted = await sessions.PurgeAsync(DatabaseScope.System, Keep, cancellationToken).ConfigureAwait(false); + foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (company.Status is not CompanyStatus.Disabled) + { + deleted += await sessions.PurgeAsync(DatabaseScope.Company(company.Code), Keep, cancellationToken).ConfigureAwait(false); + } + } + + return string.Create(CultureInfo.InvariantCulture, $"{deleted} sessioni eliminate."); + } +} + +/// +/// Computes the licence again every hour (SPEC §8.2) and notifies the instance accounts when it is about to expire or +/// has expired. +/// +/// The licence. +/// The notifications. +/// The clock. +public sealed class LicenseCheckJob(ILicenseGate licenses, NotificationDispatcher notifications, TimeProvider clock) : IScheduledJob +{ + /// The job type. + public const string JobType = "system.license-check"; + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + var state = await licenses.RefreshAsync(cancellationToken).ConfigureAwait(false); + var now = clock.GetUtcNow().UtcDateTime; + var days = state.DaysLeft(now); + if (state.Status != LicenseStatus.Valid) + { + await notifications.NotifyInstanceAsync( + new NotificationMessage("licenses", NotificationSeverity.Error, "Licenza scaduta", "Rinnova la licenza da Amministrazione > Licenze e moduli.", "/amministrazione/licenze"), + cancellationToken: cancellationToken).ConfigureAwait(false); + } + else if (days is 30 or 14 or 7 or 3 or 1 && now.Hour == 9) + { + await notifications.NotifyInstanceAsync( + new NotificationMessage("licenses", NotificationSeverity.Warning, $"La licenza scade tra {days} giorni", null, "/amministrazione/licenze"), + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + return $"{state.Kind} {state.Status}, moduli {string.Join(',', state.Modules.Order(StringComparer.Ordinal))}."; + } +} + +/// +/// Deletes old log events (SPEC §9.5): debug and trace after 7 days, information after 90, warnings after 180, errors +/// and critical events after 365. +/// +/// Opens the system database. +/// The clock. +public sealed class LogRetentionJob(IUnitOfWorkFactory factory, TimeProvider clock) : IScheduledJob +{ + /// The job type. + public const string JobType = "system.log-retention"; + + /// How many days each level is kept. + public static readonly IReadOnlyDictionary RetentionDays = new Dictionary(StringComparer.Ordinal) + { + ["Trace"] = 7, + ["Debug"] = 7, + ["Information"] = 90, + ["Warning"] = 180, + ["Error"] = 365, + ["Critical"] = 365, + }; + + /// + public string Type => JobType; + + /// + public async Task RunAsync(JobContext context, CancellationToken cancellationToken) + { + var now = clock.GetUtcNow().UtcDateTime; + var deleted = 0; + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + foreach (var (level, days) in RetentionDays) + { + var limit = now.AddDays(-days); + deleted += await unitOfWork.ExecuteAsync( + SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier("sys_log")} WHERE level = {level} AND at < {limit}"), cancellationToken).ConfigureAwait(false); + } + + return string.Create(CultureInfo.InvariantCulture, $"{deleted} eventi eliminati."); + } +} diff --git a/src/Khaemhat.Application/Khaemhat.Application.csproj b/src/Khaemhat.Application/Khaemhat.Application.csproj index c361324..c5adc45 100644 --- a/src/Khaemhat.Application/Khaemhat.Application.csproj +++ b/src/Khaemhat.Application/Khaemhat.Application.csproj @@ -4,6 +4,11 @@ Khaemhat.Application + + + + + diff --git a/src/Khaemhat.Application/Licensing/LicenseGate.cs b/src/Khaemhat.Application/Licensing/LicenseGate.cs new file mode 100644 index 0000000..5f8d390 --- /dev/null +++ b/src/Khaemhat.Application/Licensing/LicenseGate.cs @@ -0,0 +1,384 @@ +using System.Globalization; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Configuration; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Infrastructure.Licensing; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Licensing; + +/// The licence in force and the modules it activates. +public interface ILicenseGate +{ + /// The licence computed at the last refresh. + LicenseState Current { get; } + + /// Whether a module is licensed. + /// The module code. + /// if active. + bool IsModuleActive(string moduleCode); + + /// Recomputes the licence from the database and the environment. + /// Cancellation. + /// The new state. + Task RefreshAsync(CancellationToken cancellationToken = default); +} + +/// Where the gate reads the licence from the environment. +/// The text of KHAEMHAT_LICENSE, if set. +/// The licence mode. +public sealed record LicenseSettings(string? EnvironmentLicense, LicenseMode Mode); + +/// +/// Computes the licence (SPEC §8): the best signed licence (environment or installed) bound to this instance, else the +/// trial; plus the module activation codes; plus, in test mode only, the fictitious codes. Every signature is checked +/// again at each refresh, so a row changed in the database does not grant anything. +/// +public sealed class LicenseGate : ILicenseGate +{ + private readonly IUnitOfWorkFactory _factory; + private readonly SystemSettingsStore _settings; + private readonly LicenseVerifier _verifier; + private readonly LicenseSettings _licenseSettings; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + private volatile LicenseState _current; + + /// Creates the gate. Until the first refresh the state is the trial. + /// Opens the system database. + /// The instance settings. + /// Checks signatures. + /// The environment licence and mode. + /// The clock. + /// The log. + public LicenseGate( + IUnitOfWorkFactory factory, SystemSettingsStore settings, LicenseVerifier verifier, LicenseSettings licenseSettings, + TimeProvider clock, ILogger logger) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(verifier); + ArgumentNullException.ThrowIfNull(licenseSettings); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _factory = factory; + _settings = settings; + _verifier = verifier; + _licenseSettings = licenseSettings; + _clock = clock; + _logger = logger; + var now = clock.GetUtcNow().UtcDateTime; + _current = Trial(now, now, 0, [], 0, licenseSettings.Mode == LicenseMode.Test); + } + + /// + public LicenseState Current => _current; + + /// The instance identifier read at the last refresh. + public string? InstanceId { get; private set; } + + /// + public bool IsModuleActive(string moduleCode) => _current.Includes(moduleCode); + + /// + public async Task RefreshAsync(CancellationToken cancellationToken = default) + { + var now = _clock.GetUtcNow().UtcDateTime; + var testMode = _licenseSettings.Mode == LicenseMode.Test; + InstanceId = await _settings.GetAsync(SystemSettingsStore.InstanceIdKey, cancellationToken).ConfigureAwait(false); + var trialStart = DateTime.TryParse( + await _settings.GetAsync(SystemSettingsStore.TrialStartedKey, cancellationToken).ConfigureAwait(false), + CultureInfo.InvariantCulture, + DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, + out var started) ? started : now; + + IReadOnlyList records; + await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) + { + records = (await unitOfWork.Repository() + .ListAsync(Query.For().Where(r => r.IsActive).OrderBy(r => r.Id), cancellationToken).ConfigureAwait(false)).Items; + } + + var documents = records.Where(r => r.Source == LicenseSource.File).Select(r => r.Payload).ToList(); + if (_licenseSettings.EnvironmentLicense is { } environment) + { + documents.Insert(0, environment); + } + + var license = documents + .Select(text => _verifier.Verify(text).Document) + .Where(d => d is not null && (d.InstanceId is null || string.Equals(d.InstanceId, InstanceId, StringComparison.OrdinalIgnoreCase))) + .OrderByDescending(d => d!.ExpiresAt ?? DateTime.MaxValue) + .FirstOrDefault(); + + var extraModules = new HashSet(StringComparer.Ordinal); + foreach (var record in records.Where(r => r.Source == LicenseSource.ActivationCode)) + { + var (code, _) = _verifier.VerifyActivationCode(record.Payload); + if (code is not null && code.ExpiresAt > now && (InstanceId is null || code.IsFor(InstanceId))) + { + extraModules.Add(code.Module); + } + } + + var testUsers = 0; + var trialExtension = 0; + if (testMode) + { + foreach (var test in records.Where(r => r.Source == LicenseSource.TestCode).Select(r => TestLicenseCatalog.Find(r.Payload)).OfType()) + { + extraModules.UnionWith(test.Modules); + testUsers = Math.Max(testUsers, test.ConcurrentUsers); + trialExtension += test.TrialExtensionDays; + } + } + + var state = license is null + ? Trial(now, trialStart, trialExtension, extraModules, testUsers, testMode) + : Licensed(now, license, extraModules, testUsers, testMode); + if (state.Status != _current.Status || state.Kind != _current.Kind) + { + _logger.LogInformation("Licence {Kind} {Status}: modules {Modules}, {Users} users.", state.Kind, state.Status, string.Join(',', state.Modules), state.MaxConcurrentUsers); + } + + _current = state; + return state; + } + + private static LicenseState Trial(DateTime now, DateTime trialStart, int extensionDays, IEnumerable extra, int testUsers, bool testMode) + { + var modules = new HashSet(LicenseState.TrialModules, StringComparer.Ordinal); + modules.UnionWith(extra); + var expires = trialStart + LicenseState.TrialLength + TimeSpan.FromDays(extensionDays); + return new LicenseState + { + Kind = LicenseKind.Trial, + Status = now <= expires ? LicenseStatus.Valid : LicenseStatus.Expired, + Modules = modules, + MaxConcurrentUsers = Math.Max(LicenseState.TrialUsers, testUsers), + MaxCompanies = modules.Contains(ModuleCodes.MultiCompany) ? int.MaxValue : 1, + ExpiresAt = expires, + GraceEndsAt = expires, + IsTestMode = testMode, + }; + } + + private static LicenseState Licensed(DateTime now, LicenseDocument license, IEnumerable extra, int testUsers, bool testMode) + { + var modules = new HashSet(license.Modules.Select(m => m.Trim().ToUpperInvariant()), StringComparer.Ordinal) { ModuleCodes.Core }; + modules.UnionWith(extra); + var graceEnds = license.ExpiresAt?.AddDays(license.GracePeriodDays); + var status = license.ExpiresAt is not { } expires || now <= expires + ? LicenseStatus.Valid + : now <= graceEnds ? LicenseStatus.Grace : LicenseStatus.Expired; + return new LicenseState + { + Kind = LicenseKind.Licensed, + Status = status, + Licensee = license.Licensee, + Modules = modules, + MaxConcurrentUsers = Math.Max(license.MaxConcurrentUsers, testUsers), + MaxCompanies = modules.Contains(ModuleCodes.MultiCompany) ? (license.MaxCompanies > 1 ? license.MaxCompanies : int.MaxValue) : 1, + ExpiresAt = license.ExpiresAt, + GraceEndsAt = graceEnds, + IsTestMode = testMode, + }; + } +} + +/// The outcome of an activation. +/// Whether the licence or code was installed. +/// The outcome code: ok or one of . +/// The licence in force afterwards. +public sealed record ActivationResult(bool Succeeded, string Outcome, LicenseState State); + +/// Installs and removes licences (SPEC §8.2). Today offline; a remote activation server may come later. +public interface ILicenseActivationService +{ + /// Installs a .khl licence, a module activation code or, in test mode, a fictitious code. + /// Who acts: only the super user. + /// The licence text or the code. + /// Cancellation. + /// The outcome. + Task ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default); + + /// Removes an installed licence or code (it stays in the history). + /// Who acts: only the super user. + /// The row of sys_licenses. + /// Cancellation. + /// The licence in force afterwards. + Task DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default); +} + +/// Activation checked locally with the public key: no network involved. +public sealed class OfflineActivationService( + IUnitOfWorkFactory factory, LicenseGate gate, LicenseVerifier verifier, LicenseSettings settings, ModuleRegistry modules, + ISecurityAuditLog audit, TimeProvider clock) : ILicenseActivationService +{ + /// + public async Task ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + RequireSuperUser(actor); + var text = (input ?? string.Empty).Trim(); + var now = clock.GetUtcNow().UtcDateTime; + if (gate.InstanceId is null) + { + await gate.RefreshAsync(cancellationToken).ConfigureAwait(false); + } + + var (record, outcome) = Prepare(text, now); + await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) + { + await unitOfWork.InTransactionAsync( + async ct => + { + if (record is not null) + { + var licenses = unitOfWork.Repository(); + if (record.Source == LicenseSource.File) + { + // A new instance licence replaces the previous one; codes stay. + foreach (var old in (await licenses.ListAsync( + Query.For().Where(r => r.IsActive && r.Source == LicenseSource.File), ct).ConfigureAwait(false)).Items) + { + old.IsActive = false; + await licenses.UpdateAsync(old, ct).ConfigureAwait(false); + } + } + + await licenses.InsertAsync(record, ct).ConfigureAwait(false); + } + + await unitOfWork.Repository().InsertAsync( + new LicenseActivation + { + Action = record is null ? "rejected" : "activated", + Source = record?.Source ?? SourceOf(text), + Modules = record?.Modules, + Outcome = outcome, + }, + ct).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); + } + + await audit.WriteAsync( + new SecurityEvent(record is null ? "license.rejected" : "license.activated", actor.UserName, Target: record?.Modules, Details: new { outcome }), + cancellationToken).ConfigureAwait(false); + var state = await gate.RefreshAsync(cancellationToken).ConfigureAwait(false); + return new ActivationResult(record is not null, outcome, state); + } + + /// + public async Task DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + RequireSuperUser(actor); + string? modules; + await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) + { + var licenses = unitOfWork.Repository(); + var record = await licenses.GetAsync(licenseId, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException("No installed licence has this identifier."); + record.IsActive = false; + modules = record.Modules; + await licenses.UpdateAsync(record, cancellationToken).ConfigureAwait(false); + await unitOfWork.Repository().InsertAsync( + new LicenseActivation { Action = "deactivated", Source = record.Source, Modules = record.Modules, Outcome = "ok" }, cancellationToken) + .ConfigureAwait(false); + } + + await audit.WriteAsync(new SecurityEvent("license.deactivated", actor.UserName, Target: modules), cancellationToken).ConfigureAwait(false); + return await gate.RefreshAsync(cancellationToken).ConfigureAwait(false); + } + + private (LicenseRecord? Record, string Outcome) Prepare(string text, DateTime now) + { + if (TestLicenseCatalog.LooksLikeTestCode(text)) + { + if (settings.Mode != LicenseMode.Test) + { + return (null, LicenseErrors.TestOnly); + } + + var test = TestLicenseCatalog.Find(text); + return test is null + ? (null, LicenseErrors.FormatInvalid) + : (new LicenseRecord { Source = LicenseSource.TestCode, Payload = text.ToUpperInvariant(), Modules = string.Join(',', test.Modules), Licensee = "Test" }, "ok"); + } + + if (text.StartsWith(ModuleActivationCode.Prefix + "-", StringComparison.OrdinalIgnoreCase)) + { + var (code, error) = verifier.VerifyActivationCode(text); + if (code is null) + { + return (null, error!); + } + + if (modules.FindModule(code.Module) is null) + { + return (null, LicenseErrors.UnknownModule); + } + + if (code.ExpiresAt <= now) + { + return (null, LicenseErrors.Expired); + } + + if (gate.InstanceId is { } instance && !code.IsFor(instance)) + { + return (null, LicenseErrors.WrongInstance); + } + + return (new LicenseRecord { Source = LicenseSource.ActivationCode, Payload = text.ToUpperInvariant(), Modules = code.Module, ExpiresAt = code.ExpiresAt }, "ok"); + } + + var verification = verifier.Verify(text); + if (verification.Document is not { } document) + { + return (null, verification.Error!); + } + + if (document.InstanceId is not null && !string.Equals(document.InstanceId, gate.InstanceId, StringComparison.OrdinalIgnoreCase)) + { + return (null, LicenseErrors.WrongInstance); + } + + if (document.ExpiresAt is { } expires && expires.AddDays(document.GracePeriodDays) <= now) + { + return (null, LicenseErrors.Expired); + } + + return (new LicenseRecord + { + Source = LicenseSource.File, + Payload = text, + Licensee = document.Licensee.Length > 200 ? document.Licensee[..200] : document.Licensee, + Modules = string.Join(',', document.Modules), + MaxConcurrentUsers = document.MaxConcurrentUsers, + MaxCompanies = document.MaxCompanies, + IssuedAt = document.IssuedAt, + ExpiresAt = document.ExpiresAt, + GracePeriodDays = document.GracePeriodDays, + }, "ok"); + } + + private static LicenseSource SourceOf(string text) => + TestLicenseCatalog.LooksLikeTestCode(text) ? LicenseSource.TestCode + : text.StartsWith(ModuleActivationCode.Prefix + "-", StringComparison.OrdinalIgnoreCase) ? LicenseSource.ActivationCode + : LicenseSource.File; + + private static void RequireSuperUser(Actor actor) + { + if (!actor.IsSuperUser) + { + throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user activates licences and modules."); + } + } +} diff --git a/src/Khaemhat.Application/Licensing/LicenseState.cs b/src/Khaemhat.Application/Licensing/LicenseState.cs new file mode 100644 index 0000000..68fbc05 --- /dev/null +++ b/src/Khaemhat.Application/Licensing/LicenseState.cs @@ -0,0 +1,136 @@ +using Khaemhat.Application.Modules; + +namespace Khaemhat.Application.Licensing; + +/// Where the instance stands with its licence. +public enum LicenseStatus +{ + /// Valid. + Valid = 0, + + /// Expired but within the grace period: everything works, with a banner. + Grace = 1, + + /// Expired beyond the grace period: read-only with a banner (SPEC §8.2). + Expired = 2, +} + +/// What kind of licence is in force. +public enum LicenseKind +{ + /// No licence: CORE and ACCT, 3 users, 60 days. + Trial = 0, + + /// A signed licence. + Licensed = 1, +} + +/// The licence in force, computed by . Immutable. +public sealed record LicenseState +{ + /// The trial modules (SPEC §6). + public static readonly IReadOnlyList TrialModules = [ModuleCodes.Core, ModuleCodes.Accounting]; + + /// The trial users. + public const int TrialUsers = 3; + + /// The trial length. + public static readonly TimeSpan TrialLength = TimeSpan.FromDays(60); + + /// The licence kind. + public LicenseKind Kind { get; init; } + + /// The status. + public LicenseStatus Status { get; init; } + + /// The holder. + public string? Licensee { get; init; } + + /// The active modules. + public IReadOnlySet Modules { get; init; } = new HashSet(StringComparer.Ordinal); + + /// The concurrent users allowed across all companies. + public int MaxConcurrentUsers { get; init; } + + /// The companies allowed. + public int MaxCompanies { get; init; } + + /// When the licence (or the trial) expires. + public DateTime? ExpiresAt { get; init; } + + /// When the grace period ends. + public DateTime? GraceEndsAt { get; init; } + + /// Whether the fictitious codes are accepted (KHAEMHAT_LICENSE_MODE=test): the interface shows a banner. + public bool IsTestMode { get; init; } + + /// Whether data can only be read. + public bool IsReadOnly => Status == LicenseStatus.Expired; + + /// Whether a module is active. + /// The module code. + /// if licensed. + public bool Includes(string module) => Modules.Contains(module); + + /// Days left before the expiry (0 when expired), or without expiry. + /// The current time. + /// The days. + public int? DaysLeft(DateTime now) => ExpiresAt is { } expires ? Math.Max(0, (int)Math.Ceiling((expires - now).TotalDays)) : null; +} + +/// +/// The fictitious licence codes of SPEC §8.3, valid only with KHAEMHAT_LICENSE_MODE=test. Outside test mode they +/// are refused with license_test_only. Automated tests use . +/// +public static class TestLicenseCatalog +{ + /// Every module. + public const string All = "KH-TEST-ALL-0000-9999"; + + /// 25 concurrent users. + public const string Users25 = "KH-TEST-USERS-0025-0014"; + + /// 60 more days of trial. + public const string TrialExtension = "KH-TEST-TRIAL-0060-0015"; + + private static readonly Dictionary Codes = new(StringComparer.Ordinal) + { + ["KH-TEST-CORE-0000-0001"] = Module(ModuleCodes.Core), + ["KH-TEST-ACCT-0000-0002"] = Module(ModuleCodes.Accounting), + ["KH-TEST-ASSET-0000-0003"] = Module(ModuleCodes.Assets), + ["KH-TEST-FIN-0000-0004"] = Module(ModuleCodes.Finance), + ["KH-TEST-EINV-0000-0005"] = Module(ModuleCodes.EInvoicing), + ["KH-TEST-INTRA-0000-0006"] = Module(ModuleCodes.Intrastat), + ["KH-TEST-CRM-0000-0007"] = Module(ModuleCodes.Crm), + ["KH-TEST-SVC-0000-0008"] = Module(ModuleCodes.Services), + ["KH-TEST-CHAN-0000-0009"] = Module(ModuleCodes.Channels), + ["KH-TEST-AUTO-0000-0010"] = Module(ModuleCodes.Automation), + ["KH-TEST-API-0000-0011"] = Module(ModuleCodes.Api), + ["KH-TEST-MULTI-0000-0012"] = Module(ModuleCodes.MultiCompany), + ["KH-TEST-REPORT-0000-0013"] = Module(ModuleCodes.Reports), + [All] = new TestCode([.. BuiltInModules.All.Select(m => m.Code)], 0, 0), + [Users25] = new TestCode([], 25, 0), + [TrialExtension] = new TestCode([], 0, 60), + }; + + /// Every code. + public static IReadOnlyCollection AllCodes => Codes.Keys; + + /// Whether the text looks like a fictitious code (to refuse it with the right error outside test mode). + /// The text. + /// if it starts with KH-TEST-. + public static bool LooksLikeTestCode(string? text) => text?.Trim().StartsWith("KH-TEST-", StringComparison.OrdinalIgnoreCase) == true; + + /// Finds a code. + /// The code. + /// The effect, or when unknown. + public static TestCode? Find(string code) => Codes.GetValueOrDefault(code.Trim().ToUpperInvariant()); + + private static TestCode Module(string module) => new([module], 0, 0); +} + +/// The effect of a fictitious code. +/// The modules it activates. +/// The users it grants (0 = no change). +/// The days it adds to the trial. +public sealed record TestCode(IReadOnlyList Modules, int ConcurrentUsers, int TrialExtensionDays); diff --git a/src/Khaemhat.Application/Modules/BuiltInModules.cs b/src/Khaemhat.Application/Modules/BuiltInModules.cs new file mode 100644 index 0000000..ca98c18 --- /dev/null +++ b/src/Khaemhat.Application/Modules/BuiltInModules.cs @@ -0,0 +1,152 @@ +namespace Khaemhat.Application.Modules; + +/// +/// The modules of SPEC §8.1 with their permissions. Codes follow area.entity.action; the area is functional +/// (sales, ledger...) while is the licence code. +/// +public static class BuiltInModules +{ + /// Every module, in the order of SPEC §8.1. + public static IReadOnlyList All { get; } = + [ + Module(ModuleCodes.Core, "Base", + ("company.users.manage", "Gestire utenti e ruoli dell'azienda"), + ("company.settings.read", "Vedere le impostazioni dell'azienda"), + ("company.settings.write", "Modificare le impostazioni dell'azienda"), + ("parties.party.read", "Vedere anagrafiche"), + ("parties.party.write", "Creare e modificare anagrafiche"), + ("parties.party.delete", "Eliminare anagrafiche"), + ("parties.party.export", "Esportare anagrafiche"), + ("items.item.read", "Vedere articoli e listini"), + ("items.item.write", "Creare e modificare articoli e listini"), + ("items.item.delete", "Eliminare articoli"), + ("items.cost.read", "Vedere costi e margini degli articoli"), + ("sales.quote.read", "Vedere preventivi"), + ("sales.quote.write", "Creare e modificare preventivi"), + ("sales.order.read", "Vedere ordini cliente"), + ("sales.order.write", "Creare e modificare ordini cliente"), + ("sales.delivery.read", "Vedere DDT di vendita"), + ("sales.delivery.write", "Creare e modificare DDT di vendita"), + ("sales.invoice.read", "Vedere fatture di vendita"), + ("sales.invoice.write", "Creare e modificare fatture in bozza"), + ("sales.invoice.issue", "Emettere fatture di vendita"), + ("sales.invoice.delete", "Eliminare fatture in bozza"), + ("sales.invoice.print", "Stampare fatture di vendita"), + ("sales.invoice.export", "Esportare fatture di vendita"), + ("purchases.order.read", "Vedere ordini fornitore"), + ("purchases.order.write", "Creare e modificare ordini fornitore"), + ("purchases.invoice.read", "Vedere fatture di acquisto"), + ("purchases.invoice.write", "Registrare fatture di acquisto"), + ("inventory.stock.read", "Vedere giacenze"), + ("inventory.entry.read", "Vedere movimenti di magazzino"), + ("inventory.entry.write", "Creare movimenti di magazzino in bozza"), + ("inventory.entry.post", "Confermare movimenti di magazzino"), + ("attachments.read", "Vedere e scaricare allegati"), + ("attachments.write", "Caricare e generare allegati"), + ("attachments.delete", "Eliminare allegati"), + ("reports.report.read", "Vedere i report di base")), + Module(ModuleCodes.Accounting, "Contabilità", + ("ledger.account.read", "Vedere il piano dei conti"), + ("ledger.account.write", "Modificare il piano dei conti"), + ("ledger.entry.read", "Vedere la prima nota"), + ("ledger.entry.write", "Registrare in prima nota"), + ("ledger.entry.finalize", "Rendere definitive le registrazioni"), + ("ledger.entry.reopen", "Riaprire registrazioni definitive"), + ("ledger.year.close", "Chiudere l'esercizio"), + ("vat.register.read", "Vedere i registri IVA"), + ("vat.settlement.read", "Vedere le liquidazioni IVA"), + ("vat.settlement.confirm", "Confermare le liquidazioni IVA")), + Module(ModuleCodes.Assets, "Cespiti", + ("assets.asset.read", "Vedere i cespiti"), + ("assets.asset.write", "Gestire i cespiti"), + ("assets.depreciation.post", "Registrare gli ammortamenti")), + Module(ModuleCodes.Finance, "Tesoreria", + ("finance.schedule.read", "Vedere lo scadenzario"), + ("finance.schedule.write", "Modificare lo scadenzario"), + ("finance.payment.read", "Vedere incassi e pagamenti"), + ("finance.payment.write", "Registrare incassi e pagamenti"), + ("finance.bank.reconcile", "Riconciliare i movimenti bancari")), + Module(ModuleCodes.EInvoicing, "Fatturazione elettronica", + ("einvoice.document.read", "Vedere i documenti elettronici"), + ("einvoice.document.send", "Inviare documenti allo SDI"), + ("einvoice.inbox.read", "Vedere le fatture ricevute"), + ("einvoice.inbox.import", "Importare le fatture ricevute")), + Module(ModuleCodes.Intrastat, "Intrastat", + ("intrastat.list.read", "Vedere gli elenchi Intrastat"), + ("intrastat.list.write", "Compilare gli elenchi Intrastat"), + ("intrastat.list.export", "Esportare il file per le Dogane")), + Module(ModuleCodes.Crm, "CRM", + ("crm.lead.read", "Vedere i lead"), + ("crm.lead.write", "Gestire i lead"), + ("crm.opportunity.read", "Vedere le opportunità"), + ("crm.opportunity.write", "Gestire le opportunità"), + ("crm.activity.read", "Vedere attività e agenda"), + ("crm.activity.write", "Gestire attività e agenda"), + ("crm.campaign.read", "Vedere le campagne"), + ("crm.campaign.write", "Gestire le campagne"), + ("crm.ticket.read", "Vedere i ticket"), + ("crm.ticket.write", "Gestire i ticket")), + Module(ModuleCodes.Services, "Servizi", + ("services.contract.read", "Vedere i contratti di assistenza"), + ("services.contract.write", "Gestire i contratti di assistenza"), + ("services.intervention.read", "Vedere gli interventi"), + ("services.intervention.write", "Gestire interventi e rapportini")), + Module(ModuleCodes.Channels, "Canali e-commerce", + ("channels.channel.read", "Vedere i canali"), + ("channels.channel.write", "Configurare i canali"), + ("channels.order.import", "Importare gli ordini web")), + Module(ModuleCodes.Automation, "Automazioni", + ("automation.rule.read", "Vedere le regole"), + ("automation.rule.write", "Gestire le regole"), + ("automation.procedure.run", "Eseguire le procedure")), + Module(ModuleCodes.Api, "Integrazioni", + ("api.key.manage", "Gestire le chiavi API dell'azienda"), + ("api.webhook.manage", "Gestire i webhook")), + Module(ModuleCodes.MultiCompany, "Multi-azienda"), + Module(ModuleCodes.Reports, "Report avanzati", + ("reports.advanced.read", "Vedere i report avanzati"), + ("reports.schedule.write", "Pianificare report via e-mail"), + ("reports.accountant.export", "Esportare i dati per il commercialista")), + ]; + + private static ModuleDefinition Module(string code, string name, params (string Code, string Description)[] permissions) => + new(code, name, [.. permissions.Select(p => new PermissionDefinition(p.Code, code, p.Description))]); +} + +/// A predefined role (SPEC §7.2): kept in sys_roles_templates and copied into each company. +/// The role code. +/// The name shown. +/// What the role is for. +/// The permission patterns. +public sealed record RoleTemplateDefinition(string Code, string Name, string Description, IReadOnlyList Permissions); + +/// The eight predefined roles of SPEC §7.2. +public static class PredefinedRoles +{ + /// The administration role: every permission. + public const string Administration = "ADMIN"; + + /// The read-only role. + public const string ReadOnly = "READONLY"; + + /// The roles, in display order. + public static IReadOnlyList All { get; } = + [ + new(Administration, "Amministrazione", "Tutte le funzioni dell'azienda, compresi utenti e impostazioni.", ["*"]), + new("ACCOUNTING", "Contabilità", "Contabilità, IVA, cespiti, tesoreria, fatturazione elettronica e Intrastat.", + ["ledger.*", "vat.*", "assets.*", "finance.*", "einvoice.*", "intrastat.*", "parties.party.read", "sales.invoice.read", + "purchases.invoice.*", "reports.report.read", "attachments.read", "attachments.write"]), + new("SALES", "Vendite", "Preventivi, ordini, DDT e fatture di vendita; anagrafiche clienti.", + ["sales.*", "parties.*", "items.item.read", "inventory.stock.read", "crm.lead.read", "crm.opportunity.read", + "reports.report.read", "attachments.read", "attachments.write"]), + new("PURCHASES", "Acquisti", "Ordini e fatture fornitore, anagrafiche e articoli.", + ["purchases.*", "parties.*", "items.*", "inventory.stock.read", "reports.report.read", "attachments.read", "attachments.write"]), + new("WAREHOUSE", "Magazzino", "Movimenti, giacenze e DDT.", + ["inventory.*", "items.item.read", "items.item.write", "sales.delivery.*", "purchases.order.read", "attachments.read"]), + new("CRM", "CRM", "Lead, opportunità, attività, campagne e ticket.", + ["crm.*", "parties.*", "sales.quote.*", "attachments.read", "attachments.write"]), + new("SERVICES", "Servizi", "Contratti di assistenza, interventi e ticket.", + ["services.*", "parties.party.read", "items.item.read", "crm.ticket.*", "attachments.read", "attachments.write"]), + new(ReadOnly, "Sola lettura", "Vede tutto ciò che la licenza comprende, senza modificare nulla.", ["*.read"]), + ]; +} diff --git a/src/Khaemhat.Application/Modules/ModuleRegistry.cs b/src/Khaemhat.Application/Modules/ModuleRegistry.cs new file mode 100644 index 0000000..06f5bec --- /dev/null +++ b/src/Khaemhat.Application/Modules/ModuleRegistry.cs @@ -0,0 +1,166 @@ +namespace Khaemhat.Application.Modules; + +/// The module codes of SPEC §8.1, which are also the licence codes. +public static class ModuleCodes +{ + /// Base: parties, items, documents, warehouse, administration. + public const string Core = "CORE"; + + /// Accounting and VAT. + public const string Accounting = "ACCT"; + + /// Fixed assets. + public const string Assets = "ASSET"; + + /// Treasury. + public const string Finance = "FIN"; + + /// Electronic invoicing. + public const string EInvoicing = "EINV"; + + /// Intrastat. + public const string Intrastat = "INTRA"; + + /// CRM. + public const string Crm = "CRM"; + + /// Services. + public const string Services = "SVC"; + + /// E-commerce channels. + public const string Channels = "CHAN"; + + /// Automations. + public const string Automation = "AUTO"; + + /// API, MCP and webhooks. + public const string Api = "API"; + + /// Companies beyond the first. + public const string MultiCompany = "MULTI"; + + /// Advanced reports. + public const string Reports = "REPORT"; +} + +/// A permission a module declares: a code module.entity.action (SPEC §7.2). +/// The code, for example sales.invoice.issue. +/// The licence code of the module that owns it. +/// What it allows, in Italian (shown in the permission matrix). +public sealed record PermissionDefinition(string Code, string Module, string Description); + +/// A functional module (SPEC §8.1): its licence code, its name and the permissions it declares. +public interface IModule +{ + /// The licence code. + string Code { get; } + + /// The name shown in the interface. + string Name { get; } + + /// The permissions. + IReadOnlyList Permissions { get; } +} + +/// A module declared in code. +/// The licence code. +/// The name shown. +/// The permissions. +public sealed record ModuleDefinition(string Code, string Name, IReadOnlyList Permissions) : IModule; + +/// +/// The modules of the product and their permissions. The list is static: what the licence does not include stays +/// declared but is filtered by ILicenseGate (menus hidden, permissions denied with +/// module_not_licensed). Each milestone adds the permissions of the screens it delivers. +/// +public sealed class ModuleRegistry +{ + private readonly Dictionary _modules; + private readonly Dictionary _permissions; + + /// Creates a registry. + /// The modules. + /// Two modules share a code, or two permissions share a code. + public ModuleRegistry(IEnumerable modules) + { + ArgumentNullException.ThrowIfNull(modules); + _modules = new Dictionary(StringComparer.Ordinal); + _permissions = new Dictionary(StringComparer.Ordinal); + foreach (var module in modules) + { + if (!_modules.TryAdd(module.Code, module)) + { + throw new InvalidOperationException($"Module {module.Code} is declared twice."); + } + + foreach (var permission in module.Permissions) + { + if (!PermissionPattern.IsCode(permission.Code) || permission.Module != module.Code) + { + throw new InvalidOperationException($"Permission {permission.Code} of {module.Code} is not a module.entity.action code of that module."); + } + + if (!_permissions.TryAdd(permission.Code, permission)) + { + throw new InvalidOperationException($"Permission {permission.Code} is declared twice."); + } + } + } + } + + /// The registry of the product modules. + public static ModuleRegistry Default { get; } = new(BuiltInModules.All); + + /// The modules, in the order of SPEC §8.1. + public IReadOnlyCollection Modules => _modules.Values; + + /// Every permission. + public IReadOnlyCollection Permissions => _permissions.Values; + + /// Finds a module. + /// The licence code. + /// The module, or . + public IModule? FindModule(string code) => _modules.GetValueOrDefault(code); + + /// Finds a permission. + /// The permission code. + /// The permission, or . + public PermissionDefinition? FindPermission(string code) => _permissions.GetValueOrDefault(code); + + /// The permissions a pattern grants (*, sales.*, *.read or a code). + /// The pattern. + /// The matching permissions. + public IEnumerable Expand(string pattern) => _permissions.Values.Where(p => PermissionPattern.Matches(pattern, p.Code)); +} + +/// Permission codes and the patterns used by roles: *, module.*, *.action or an exact code. +public static class PermissionPattern +{ + /// Whether has the form module.entity.action (two or three lower-case segments). + /// The code. + /// if valid. + public static bool IsCode(string? code) => + code is not null && code.Split('.') is { Length: 2 or 3 } parts + && parts.All(p => p.Length > 0 && p.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_')); + + /// Whether a pattern grants a permission code. + /// The pattern. + /// The permission code. + /// if it matches. + public static bool Matches(string pattern, string code) + { + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(code); + if (pattern == "*" || pattern == code) + { + return true; + } + + if (pattern.EndsWith(".*", StringComparison.Ordinal)) + { + return code.StartsWith(pattern[..^1], StringComparison.Ordinal); + } + + return pattern.StartsWith("*.", StringComparison.Ordinal) && code.EndsWith(pattern[1..], StringComparison.Ordinal); + } +} diff --git a/src/Khaemhat.Application/Notifications/NotificationDispatcher.cs b/src/Khaemhat.Application/Notifications/NotificationDispatcher.cs new file mode 100644 index 0000000..cad2ebe --- /dev/null +++ b/src/Khaemhat.Application/Notifications/NotificationDispatcher.cs @@ -0,0 +1,102 @@ +using Khaemhat.Core.Instance; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Notifications; + +/// A notification to deliver. +/// The area: security, jobs, system, licenses... +/// The weight. +/// The title. +/// The text. +/// A link inside the application. +public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null); + +/// +/// Delivers in-app notifications (SPEC §9; mockup 010): to instance accounts in sys_notifications, to company +/// users in the company's notifications. A notification without recipient goes to everyone in the scope. +/// Delivery never breaks the caller: a failure is logged. +/// +/// Opens the databases. +/// The log. +public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger logger) +{ + /// Notifies instance accounts. + /// The notification. + /// One account, or for all of them. + /// Cancellation. + /// A task. + public async Task NotifyInstanceAsync(NotificationMessage message, long? recipientUserId = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(message); + try + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + await unitOfWork.Repository().InsertAsync(Fill(new SystemNotification(), message, recipientUserId), cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Notification {Title} not delivered to instance accounts.", message.Title); + } + } + + /// Notifies the users of a company. + /// The company. + /// The notification. + /// One user, or for all of them. + /// Cancellation. + /// A task. + public async Task NotifyCompanyAsync(string companyCode, NotificationMessage message, long? recipientUserId = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(message); + try + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await unitOfWork.Repository().InsertAsync(Fill(new Notification(), message, recipientUserId), cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Notification {Title} not delivered to company {Company}.", message.Title, companyCode); + } + } + + /// The unread notifications of an instance account (its own and those for everyone). + /// The account. + /// Cancellation. + /// The notifications, newest first. + public async Task> UnreadForInstanceAsync(long userId, CancellationToken cancellationToken = default) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + return (await unitOfWork.Repository().ListAsync( + Query.For().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100), + cancellationToken).ConfigureAwait(false)).Items; + } + + /// The unread notifications of a company user. + /// The company. + /// The user. + /// Cancellation. + /// The notifications, newest first. + public async Task> UnreadForUserAsync(string companyCode, long userId, CancellationToken cancellationToken = default) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + return (await unitOfWork.Repository().ListAsync( + Query.For().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100), + cancellationToken).ConfigureAwait(false)).Items; + } + + private static T Fill(T notification, NotificationMessage message, long? recipient) + where T : NotificationRecord + { + notification.RecipientUserId = recipient; + notification.Category = Clip(message.Category, 40); + notification.Severity = message.Severity; + notification.Title = Clip(message.Title, 200); + notification.Body = message.Body; + notification.Link = message.Link is null ? null : Clip(message.Link, 400); + return notification; + } + + private static string Clip(string value, int length) => value.Length <= length ? value : value[..length]; +} diff --git a/src/Khaemhat.Application/Security/AccountSecurity.cs b/src/Khaemhat.Application/Security/AccountSecurity.cs new file mode 100644 index 0000000..3274c80 --- /dev/null +++ b/src/Khaemhat.Application/Security/AccountSecurity.cs @@ -0,0 +1,351 @@ +using System.Text.Json; +using Khaemhat.Core.Security; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Application.Security; + +/// The outcome of a password check at sign-in. +/// Whether the password was right and the account may go on. +/// The error code when it did not succeed (). +/// The password must be changed before entering. +public sealed record PasswordCheck(bool Succeeded, string? Error, bool MustChangePassword) +{ + /// A failure. + /// The error code. + /// The outcome. + public static PasswordCheck Fail(string error) => new(false, error, false); +} + +/// +/// The credential rules shared by instance accounts and company users (SPEC §7.3): password check with lockout, +/// password change with policy and history, temporary passwords, recovery tokens, TOTP and recovery codes. +/// The methods change the account in memory; the caller saves it. +/// +public sealed class AccountSecurity +{ + private const string SecretPurpose = "account:totp"; + private readonly PasswordPolicy _policy; + private readonly ISecretProtector _protector; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The password policy. + /// Encrypts TOTP secrets. + /// The clock. + public AccountSecurity(PasswordPolicy policy, ISecretProtector protector, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(policy); + ArgumentNullException.ThrowIfNull(protector); + ArgumentNullException.ThrowIfNull(clock); + _policy = policy; + _protector = protector; + _clock = clock; + } + + /// The policy settings. + public SecurityPolicyOptions Options => _policy.Options; + + private DateTime Now => _clock.GetUtcNow().UtcDateTime; + + /// Checks the password typed at sign-in, counting failures and locking the account after too many. + /// The account. + /// The password typed. + /// The outcome. + public PasswordCheck CheckPassword(IAccount account, string password) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(password); + var now = Now; + if (!account.IsActive) + { + return PasswordCheck.Fail(SecurityErrors.AccountDisabled); + } + + if (account.LockedUntil is { } locked && locked > now) + { + return PasswordCheck.Fail(SecurityErrors.AccountLocked); + } + + var verification = PasswordHasher.Verify(account.PasswordHash, password); + if (verification == PasswordVerification.Failed) + { + account.FailedLoginCount++; + if (account.FailedLoginCount >= Options.MaxFailedAttempts) + { + account.LockedUntil = now + Options.LockoutDuration; + account.FailedLoginCount = 0; + return PasswordCheck.Fail(SecurityErrors.AccountLocked); + } + + return PasswordCheck.Fail(SecurityErrors.InvalidCredentials); + } + + account.FailedLoginCount = 0; + account.LockedUntil = null; + if (account.TemporaryPasswordExpiresAt is { } expires && expires <= now) + { + return PasswordCheck.Fail(SecurityErrors.TemporaryPasswordExpired); + } + + if (verification == PasswordVerification.SucceededRehashNeeded) + { + account.PasswordHash = PasswordHasher.Hash(password, Options.HashIterations); + } + + var expired = Options.ExpiryDays is { } days && account.PasswordChangedAt is { } changed && changed.AddDays(days) <= now; + return new PasswordCheck(true, null, account.MustChangePassword || expired); + } + + /// Records a completed sign-in. + /// The account. + public void RecordSignIn(IAccount account) + { + ArgumentNullException.ThrowIfNull(account); + account.LastLoginAt = Now; + } + + /// Sets a new password chosen by the user, after checking policy and history. + /// The account. + /// The new password. + /// The error codes; empty when the password was set. + public IReadOnlyList ChangePassword(IAccount account, string newPassword) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(newPassword); + var errors = new List(_policy.Check(newPassword, account.UserName)); + if (errors.Count == 0 && IsReused(account, newPassword)) + { + errors.Add(SecurityErrors.PasswordReused); + } + + if (errors.Count == 0) + { + Store(account, newPassword, temporary: false); + } + + return errors; + } + + /// + /// Sets a password without the history check: the first password of the super user, or a temporary password made by + /// an administrator. Both must be changed at the next sign-in. + /// + /// The account. + /// The password. + /// Whether it expires after . + /// The policy error codes; empty when the password was set. + public IReadOnlyList SetInitialPassword(IAccount account, string password, bool temporary) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(password); + var errors = _policy.Check(password, account.UserName); + if (errors.Count == 0) + { + Store(account, password, temporary); + account.MustChangePassword = true; + } + + return errors; + } + + /// Creates a temporary password that satisfies the policy and sets it. + /// The account. + /// The password to give to the user, once. + public string IssueTemporaryPassword(IAccount account) + { + ArgumentNullException.ThrowIfNull(account); + + // Two readable groups plus a lower-case suffix and a symbol: four classes, 14 characters. + var password = SecureTokenGenerator.CreateReadableCode(2) + "-" + SecureTokenGenerator.CreateReadableCode(1).ToLowerInvariant(); + Store(account, password, temporary: true); + account.MustChangePassword = true; + return password; + } + + /// Creates a single-use recovery token, valid for . + /// The account. + /// The token to send by e-mail; only its hash is stored. + public string IssueRecoveryToken(IAccount account) + { + ArgumentNullException.ThrowIfNull(account); + var token = SecureTokenGenerator.Create(); + account.RecoveryTokenHash = SecureTokenGenerator.Hash(token); + account.RecoveryTokenExpiresAt = Now + Options.RecoveryTokenLifetime; + return token; + } + + /// Uses a recovery token to set a new password. The token stops working whatever the outcome of the policy. + /// The account. + /// The token from the e-mail. + /// The new password. + /// The error codes; empty when the password was set. + public IReadOnlyList RedeemRecoveryToken(IAccount account, string token, string newPassword) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(token); + var valid = account.RecoveryTokenExpiresAt is { } expires && expires > Now + && SecureTokenGenerator.HashesEqual(account.RecoveryTokenHash, SecureTokenGenerator.Hash(token)); + if (!valid) + { + return [SecurityErrors.RecoveryTokenInvalid]; + } + + var errors = ChangePassword(account, newPassword); + if (errors.Count == 0) + { + account.RecoveryTokenHash = null; + account.RecoveryTokenExpiresAt = null; + account.LockedUntil = null; + account.FailedLoginCount = 0; + } + + return errors; + } + + /// Starts the TOTP setup: a new secret, stored encrypted and not yet active. + /// The account. + /// The secret in base32, to show once with . + public string BeginTotpSetup(IAccount account) + { + ArgumentNullException.ThrowIfNull(account); + var secret = TotpGenerator.CreateSecret(); + account.TotpSecret = _protector.Protect(secret, SecretPurpose); + account.TotpEnabled = false; + account.TotpLastStep = null; + return secret; + } + + /// The secret of a setup started and not yet confirmed, so that reloading the page shows the same one. + /// The account. + /// The secret in base32, or when no setup is pending. + public string? PendingTotpSecret(IAccount account) + { + ArgumentNullException.ThrowIfNull(account); + return account is { TotpEnabled: false, TotpSecret: { } secret } ? _protector.Unprotect(secret, SecretPurpose) : null; + } + + /// Completes the TOTP setup with a first code from the app, and creates the recovery codes. + /// The account. + /// The code shown by the app. + /// The ten recovery codes to show once; if the code is wrong. + public IReadOnlyList? ConfirmTotpSetup(IAccount account, string code) + { + ArgumentNullException.ThrowIfNull(account); + if (account.TotpSecret is null || !VerifyCode(account, code)) + { + return null; + } + + account.TotpEnabled = true; + var codes = Enumerable.Range(0, 10).Select(_ => SecureTokenGenerator.CreateReadableCode(2)).ToList(); + account.TotpRecoveryCodes = JsonSerializer.Serialize(codes.Select(c => SecureTokenGenerator.Hash(c)).ToList()); + return codes; + } + + /// Checks a TOTP code at sign-in. A code is never accepted twice. + /// The account. + /// The code. + /// Whether the code is valid. + public bool VerifyTotp(IAccount account, string code) + { + ArgumentNullException.ThrowIfNull(account); + return account.TotpEnabled && account.TotpSecret is not null && VerifyCode(account, code); + } + + /// Uses one of the recovery codes in place of a TOTP code. Each code works once. + /// The account. + /// The recovery code. + /// Whether the code was valid. + public static bool UseRecoveryCode(IAccount account, string code) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(code); + var hashes = Deserialize(account.TotpRecoveryCodes); + var hash = SecureTokenGenerator.Hash(code.Trim().ToUpperInvariant()); + var index = hashes.FindIndex(h => SecureTokenGenerator.HashesEqual(h, hash)); + if (!account.TotpEnabled || index < 0) + { + return false; + } + + hashes.RemoveAt(index); + account.TotpRecoveryCodes = JsonSerializer.Serialize(hashes); + return true; + } + + /// Turns the two-step verification off (an administrator resetting a lost phone). + /// The account. + public static void ResetTotp(IAccount account) + { + ArgumentNullException.ThrowIfNull(account); + account.TotpEnabled = false; + account.TotpSecret = null; + account.TotpLastStep = null; + account.TotpRecoveryCodes = null; + } + + private bool VerifyCode(IAccount account, string code) + { + string secret; + try + { + secret = _protector.Unprotect(account.TotpSecret!, SecretPurpose); + } + catch (SecretProtectionException) + { + return false; + } + + var step = TotpGenerator.Verify(secret, code, _clock.GetUtcNow(), account.TotpLastStep); + if (step is null) + { + return false; + } + + account.TotpLastStep = step; + return true; + } + + private bool IsReused(IAccount account, string password) + { + if (PasswordHasher.Verify(account.PasswordHash, password) != PasswordVerification.Failed) + { + return true; + } + + return Deserialize(account.PasswordHistory).Take(Options.HistorySize) + .Any(h => PasswordHasher.Verify(h, password) != PasswordVerification.Failed); + } + + private void Store(IAccount account, string password, bool temporary) + { + if (account.PasswordHash is not null) + { + var history = Deserialize(account.PasswordHistory); + history.Insert(0, account.PasswordHash); + account.PasswordHistory = JsonSerializer.Serialize(history.Take(Math.Max(Options.HistorySize - 1, 0)).ToList()); + } + + account.PasswordHash = PasswordHasher.Hash(password, Options.HashIterations); + account.PasswordChangedAt = Now; + account.MustChangePassword = false; + account.TemporaryPasswordExpiresAt = temporary ? Now + Options.TemporaryPasswordLifetime : null; + } + + private static List Deserialize(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return []; + } + + try + { + return JsonSerializer.Deserialize>(json) ?? []; + } + catch (JsonException) + { + return []; + } + } +} diff --git a/src/Khaemhat.Application/Security/Actor.cs b/src/Khaemhat.Application/Security/Actor.cs new file mode 100644 index 0000000..d6731ab --- /dev/null +++ b/src/Khaemhat.Application/Security/Actor.cs @@ -0,0 +1,85 @@ +using Khaemhat.Core.Security; + +namespace Khaemhat.Application.Security; + +/// +/// Who performs an action: an instance account (super user or administrator) or a company user. Services check the +/// actor; the interface only hides what the actor cannot do. +/// +/// The user name, written in the audit columns and logs. +/// The level. +/// The instance account, for super user and administrators. +/// The company user (or the user an administrator is linked to). +/// The company the actor works in. +public sealed record Actor(string UserName, UserLevel Level, long? SystemUserId, long? CompanyUserId, string? CompanyCode) +{ + /// The instance itself: bootstrap, scheduled jobs. + public static Actor System { get; } = new("system", UserLevel.SuperUser, null, null, null); + + /// Whether the actor is an instance account. + public bool IsInstanceAccount => Level >= UserLevel.Administrator; + + /// Whether the actor is the super user. + public bool IsSuperUser => Level == UserLevel.SuperUser; +} + +/// An action the actor may not perform. is one of . +public sealed class AccessDeniedException : Exception +{ + /// Creates the exception. + public AccessDeniedException() + : this(SecurityErrors.PermissionDenied, "Access denied.") + { + } + + /// Creates the exception. + /// The message. + public AccessDeniedException(string message) + : this(SecurityErrors.PermissionDenied, message) + { + } + + /// Creates the exception. + /// The message. + /// The cause. + public AccessDeniedException(string message, Exception innerException) + : base(message, innerException) => Code = SecurityErrors.PermissionDenied; + + /// Creates the exception. + /// The error code. + /// The message. + public AccessDeniedException(string code, string message) + : base(message) => Code = code; + + /// The error code. + public string Code { get; } +} + +/// A request the rules refuse (policy, duplicates); holds error codes for the interface. +public sealed class ValidationFailedException : Exception +{ + /// Creates the exception. + public ValidationFailedException() + : this([]) + { + } + + /// Creates the exception. + /// The message. + public ValidationFailedException(string message) + : base(message) => Errors = [message]; + + /// Creates the exception. + /// The message. + /// The cause. + public ValidationFailedException(string message, Exception innerException) + : base(message, innerException) => Errors = [message]; + + /// Creates the exception. + /// The error codes. + public ValidationFailedException(IReadOnlyList errors) + : base("The request is not valid: " + string.Join(", ", errors ?? [])) => Errors = errors ?? []; + + /// The error codes. + public IReadOnlyList Errors { get; } +} diff --git a/src/Khaemhat.Application/Security/PasswordPolicy.cs b/src/Khaemhat.Application/Security/PasswordPolicy.cs new file mode 100644 index 0000000..2faa7f7 --- /dev/null +++ b/src/Khaemhat.Application/Security/PasswordPolicy.cs @@ -0,0 +1,165 @@ +using System.Text.RegularExpressions; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Application.Security; + +/// Sign-in names: 3 to 50 characters, letters, digits, dot, dash and underscore; compared in lower case. +public static partial class UserNames +{ + /// Whether a name has the allowed form. + /// The name. + /// if valid. + public static bool IsValid(string? name) => name is not null && Pattern().IsMatch(name.Trim()); + + /// The stored form: trimmed, lower case. + /// The name. + /// The normalized name. + /// The name is not valid. + public static string Normalize(string name) + { + ArgumentNullException.ThrowIfNull(name); + return IsValid(name) + ? name.Trim().ToLowerInvariant() + : throw new ArgumentException("A user name has 3 to 50 characters: letters, digits, dot, dash or underscore.", nameof(name)); + } + + [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9._\-]{2,49}$", RegexOptions.CultureInvariant)] + private static partial Regex Pattern(); +} + +/// The security settings of accounts (SPEC §7.3). The defaults are those of the specification. +public sealed record SecurityPolicyOptions +{ + /// Minimum password length. + public int MinimumLength { get; init; } = 10; + + /// Minimum character classes among lower case, upper case, digits and symbols. + public int MinimumClasses { get; init; } = 3; + + /// How many previous passwords cannot be reused. + public int HistorySize { get; init; } = 5; + + /// Days after which a password must be changed; for no expiry. + public int? ExpiryDays { get; init; } + + /// Failed sign-ins before the account is locked. + public int MaxFailedAttempts { get; init; } = 5; + + /// How long a locked account stays locked. + public TimeSpan LockoutDuration { get; init; } = TimeSpan.FromMinutes(15); + + /// How long a temporary password works. + public TimeSpan TemporaryPasswordLifetime { get; init; } = TimeSpan.FromHours(72); + + /// How long a password-recovery link works. + public TimeSpan RecoveryTokenLifetime { get; init; } = TimeSpan.FromMinutes(30); + + /// The sliding lifetime of a session. + public TimeSpan SessionLifetime { get; init; } = TimeSpan.FromMinutes(480); + + /// The lifetime of a session with "remember me on this device". + public TimeSpan PersistentSessionLifetime { get; init; } = TimeSpan.FromDays(14); + + /// The time to complete a pending sign-in step (TOTP, password change). + public TimeSpan PendingStepLifetime { get; init; } = TimeSpan.FromMinutes(10); + + /// Whether company users must use the two-step verification. + public bool TotpRequiredForUsers { get; init; } + + /// PBKDF2 iterations; lowered only by tests. + public int HashIterations { get; init; } = PasswordHasher.Iterations; +} + +/// Checks new passwords against the policy. +/// The policy. +public sealed class PasswordPolicy(SecurityPolicyOptions options) +{ + /// The policy settings. + public SecurityPolicyOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options)); + + /// Checks the form of a password. + /// The new password. + /// The user name, which the password must not contain. + /// Error codes: password_too_short, password_too_simple, password_contains_user_name. + public IReadOnlyList Check(string password, string? userName) + { + ArgumentNullException.ThrowIfNull(password); + var errors = new List(); + if (password.Length < Options.MinimumLength) + { + errors.Add(SecurityErrors.PasswordTooShort); + } + + var classes = (password.Any(char.IsLower) ? 1 : 0) + (password.Any(char.IsUpper) ? 1 : 0) + + (password.Any(char.IsDigit) ? 1 : 0) + (password.Any(c => !char.IsLetterOrDigit(c)) ? 1 : 0); + if (classes < Options.MinimumClasses) + { + errors.Add(SecurityErrors.PasswordTooSimple); + } + + if (userName is { Length: >= 3 } && password.Contains(userName, StringComparison.OrdinalIgnoreCase)) + { + errors.Add(SecurityErrors.PasswordContainsUserName); + } + + return errors; + } +} + +/// The error codes of the security services; the interface turns them into Italian messages. +public static class SecurityErrors +{ + /// Wrong user, company or password (never says which). + public const string InvalidCredentials = "invalid_credentials"; + + /// Too many failed attempts: the account is locked for a while. + public const string AccountLocked = "account_locked"; + + /// The account is disabled. + public const string AccountDisabled = "account_disabled"; + + /// The temporary password has expired. + public const string TemporaryPasswordExpired = "temporary_password_expired"; + + /// The password is shorter than the policy. + public const string PasswordTooShort = "password_too_short"; + + /// The password uses too few character classes. + public const string PasswordTooSimple = "password_too_simple"; + + /// The password contains the user name. + public const string PasswordContainsUserName = "password_contains_user_name"; + + /// The password was used recently. + public const string PasswordReused = "password_reused"; + + /// The current password is wrong. + public const string CurrentPasswordWrong = "current_password_wrong"; + + /// The TOTP code is wrong or already used. + public const string TotpInvalid = "totp_invalid"; + + /// The recovery token is wrong, used or expired. + public const string RecoveryTokenInvalid = "recovery_token_invalid"; + + /// Too many attempts from this address. + public const string RateLimited = "rate_limited"; + + /// The licence allows no more concurrent users. + public const string ConcurrentUsersExceeded = "concurrent_users_exceeded"; + + /// The level of the account does not allow the action. + public const string LevelTooLow = "level_too_low"; + + /// The permission is missing. + public const string PermissionDenied = "permission_denied"; + + /// The module is not in the licence. + public const string ModuleNotLicensed = "module_not_licensed"; + + /// The company is in maintenance or disabled. + public const string CompanyUnavailable = "company_unavailable"; + + /// The licence allows no more of something (companies, users). + public const string LicenseLimitReached = "license_limit_reached"; +} diff --git a/src/Khaemhat.Application/Security/PermissionService.cs b/src/Khaemhat.Application/Security/PermissionService.cs new file mode 100644 index 0000000..2bf34c8 --- /dev/null +++ b/src/Khaemhat.Application/Security/PermissionService.cs @@ -0,0 +1,175 @@ +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Core.Caching; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Security; + +/// The per-user flags of SPEC §7.2. +/// Sees only the customers assigned to the user. +/// Sees costs and margins. +/// Can export. +/// Can use the API. +public sealed record UserFlags(bool OwnCustomersOnly, bool CanSeeCosts, bool CanExport, bool CanUseApi) +{ + /// Everything allowed: instance accounts. + public static UserFlags Unrestricted { get; } = new(false, true, true, true); +} + +/// What a user may do in a company, before the licence is applied. Cached per user. +/// Instance accounts: every permission. +/// The patterns granted by roles and overrides. +/// The patterns denied by overrides (they win). +/// The per-user flags. +public sealed record EffectivePermissions(bool AllAccess, IReadOnlyList Granted, IReadOnlyList Denied, UserFlags Flags) +{ + /// Every permission. + public static EffectivePermissions All { get; } = new(true, ["*"], [], UserFlags.Unrestricted); + + /// No permission. + public static EffectivePermissions None { get; } = new(false, [], [], new UserFlags(true, false, false, false)); + + /// Whether the roles and overrides allow a code (the licence is checked by ). + /// The permission code. + /// if allowed. + public bool Allows(string code) => + AllAccess || (!Denied.Any(d => PermissionPattern.Matches(d, code)) && Granted.Any(g => PermissionPattern.Matches(g, code))); +} + +/// The outcome of a permission check: is permission_denied, module_not_licensed or license_read_only. +/// Whether the action is allowed. +/// The reason otherwise. +public sealed record PermissionCheck(bool Allowed, string? Error) +{ + /// Allowed. + public static PermissionCheck Ok { get; } = new(true, null); +} + +/// +/// Resolves permissions (SPEC §7.2): instance accounts have every permission; company users have the union of their +/// roles plus granted overrides, minus denied overrides. A module outside the licence is denied with +/// module_not_licensed; past the licence grace only .read permissions remain. Results are cached per user +/// under kh:{company}:permissions: and invalidated when roles or users change. +/// +public sealed class PermissionService(IUnitOfWorkFactory factory, ICacheProvider cache, ILicenseGate licenses, ModuleRegistry modules) +{ + /// The error when the licence is expired beyond the grace period. + public const string LicenseReadOnly = "license_read_only"; + + private const string Area = "permissions"; + private static readonly TimeSpan CacheTime = TimeSpan.FromMinutes(10); + + /// The permissions of an actor in its company. + /// The actor. + /// Cancellation. + /// The permissions. + public async Task GetAsync(Actor actor, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + if (actor.IsInstanceAccount) + { + return EffectivePermissions.All; + } + + if (actor.CompanyCode is not { } company || actor.CompanyUserId is not { } userId) + { + return EffectivePermissions.None; + } + + return await cache.GetOrCreateAsync( + CacheKeys.For(company, Area, userId.ToString(System.Globalization.CultureInfo.InvariantCulture)), + ct => new ValueTask(LoadAsync(company, userId, ct)), + CacheTime, + cancellationToken).ConfigureAwait(false); + } + + /// Checks one permission, licence included. + /// The actor. + /// The permission code. + /// Cancellation. + /// The outcome. + public async Task CheckAsync(Actor actor, string code, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(code); + if (modules.FindPermission(code) is not { } definition) + { + return new PermissionCheck(false, SecurityErrors.PermissionDenied); + } + + if (!licenses.IsModuleActive(definition.Module)) + { + return new PermissionCheck(false, SecurityErrors.ModuleNotLicensed); + } + + if (licenses.Current.IsReadOnly && !code.EndsWith(".read", StringComparison.Ordinal)) + { + return new PermissionCheck(false, LicenseReadOnly); + } + + var permissions = await GetAsync(actor, cancellationToken).ConfigureAwait(false); + return permissions.Allows(code) ? PermissionCheck.Ok : new PermissionCheck(false, SecurityErrors.PermissionDenied); + } + + /// Throws when the actor may not perform the action. + /// The actor. + /// The permission code. + /// Cancellation. + /// A task. + /// The permission is missing or the module is not licensed. + public async Task DemandAsync(Actor actor, string code, CancellationToken cancellationToken = default) + { + var check = await CheckAsync(actor, code, cancellationToken).ConfigureAwait(false); + if (!check.Allowed) + { + throw new AccessDeniedException(check.Error!, $"Permission {code} is not granted."); + } + } + + /// Whether the actor holds every permission a set of patterns would grant (roles are never above one's own). + /// The actor. + /// The patterns. + /// Cancellation. + /// when nothing in the patterns exceeds the actor. + public async Task CoversAsync(Actor actor, IEnumerable patterns, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(patterns); + var own = await GetAsync(actor, cancellationToken).ConfigureAwait(false); + return own.AllAccess || patterns.SelectMany(modules.Expand).All(p => own.Allows(p.Code)); + } + + /// Forgets the cached permissions of a company, here and on the other instances. + /// The company. + /// Cancellation. + /// A task. + public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) => + cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), Area), cancellationToken); + + private async Task LoadAsync(string company, long userId, CancellationToken cancellationToken) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var user = await unitOfWork.Repository().GetAsync(userId, cancellationToken).ConfigureAwait(false); + if (user is not { IsActive: true }) + { + return EffectivePermissions.None; + } + + var roleIds = (await unitOfWork.Repository() + .ListAsync(Query.For().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items.Select(r => r.RoleId).ToArray(); + var granted = roleIds.Length == 0 + ? [] + : (await unitOfWork.Repository() + .ListAsync(Query.For().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items + .Select(g => g.Permission).ToList(); + var overrides = (await unitOfWork.Repository() + .ListAsync(Query.For().Where(o => o.UserId == userId), cancellationToken).ConfigureAwait(false)).Items; + granted.AddRange(overrides.Where(o => o.Allowed).Select(o => o.Permission)); + var denied = overrides.Where(o => !o.Allowed).Select(o => o.Permission).ToList(); + return new EffectivePermissions( + false, + [.. granted.Distinct(StringComparer.Ordinal)], + denied, + new UserFlags(user.OwnCustomersOnly, user.CanSeeCosts, user.CanExport, user.CanUseApi)); + } +} diff --git a/src/Khaemhat.Application/Security/RoleService.cs b/src/Khaemhat.Application/Security/RoleService.cs new file mode 100644 index 0000000..a9e178e --- /dev/null +++ b/src/Khaemhat.Application/Security/RoleService.cs @@ -0,0 +1,238 @@ +using System.Text.Json; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Modules; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Security; + +/// A role with its permission patterns. +/// The role. +/// The patterns. +public sealed record RoleWithPermissions(Role Role, IReadOnlyList Permissions); + +/// +/// Roles (SPEC §7.2): the eight predefined roles live as templates in sys_roles_templates and are copied into each +/// company, where they can be cloned but not changed. Users with company.users.manage manage roles never above +/// their own permissions. +/// +public sealed class RoleService(IUnitOfWorkFactory factory, PermissionService permissions, ISecurityAuditLog audit) +{ + /// Writes or updates the predefined templates in the system database (bootstrap and every start). + /// Cancellation. + /// A task. + public async Task SeedTemplatesAsync(CancellationToken cancellationToken = default) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var templates = unitOfWork.Repository(); + var existing = (await templates.ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(t => t.Code, StringComparer.Ordinal); + await unitOfWork.InTransactionAsync( + async ct => + { + var order = 0; + foreach (var definition in PredefinedRoles.All) + { + var json = JsonSerializer.Serialize(definition.Permissions); + order += 10; + if (!existing.TryGetValue(definition.Code, out var template)) + { + await templates.InsertAsync( + new RoleTemplate { Code = definition.Code, Name = definition.Name, Description = definition.Description, Permissions = json, SortOrder = order }, + ct).ConfigureAwait(false); + } + else if (template.Permissions != json || template.Name != definition.Name || template.Description != definition.Description) + { + template.Name = definition.Name; + template.Description = definition.Description; + template.Permissions = json; + template.SortOrder = order; + await templates.UpdateAsync(template, ct).ConfigureAwait(false); + } + } + }, + cancellationToken).ConfigureAwait(false); + } + + /// + /// Copies the templates into a company: missing predefined roles are created, existing ones are brought in line + /// with their template (they are not modifiable, so the template wins). + /// + /// The company. + /// Cancellation. + /// A task. + public async Task SyncPredefinedRolesAsync(string companyCode, CancellationToken cancellationToken = default) + { + IReadOnlyList templates; + await using (var system = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) + { + templates = (await system.Repository().ListAsync(Query.For().OrderBy(t => t.SortOrder), cancellationToken) + .ConfigureAwait(false)).Items; + } + + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var roles = unitOfWork.Repository(); + var grants = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + foreach (var template in templates) + { + var code = template.Code; + var role = await roles.FindAsync(Query.For().Where(r => r.Code == code), ct).ConfigureAwait(false); + if (role is null) + { + role = new Role { Code = code, Name = template.Name, Description = template.Description, IsPredefined = true, TemplateCode = code }; + role.Id = await roles.InsertAsync(role, ct).ConfigureAwait(false); + } + else if (!role.IsPredefined) + { + continue; + } + + var wanted = JsonSerializer.Deserialize>(template.Permissions) ?? []; + await ReplaceGrantsAsync(grants, role.Id, wanted, ct).ConfigureAwait(false); + } + }, + cancellationToken).ConfigureAwait(false); + await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false); + } + + /// The roles of a company with their permissions. + /// The company. + /// Cancellation. + /// The roles, predefined first. + public async Task> ListAsync(string companyCode, CancellationToken cancellationToken = default) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var roles = (await unitOfWork.Repository().ListAsync(Query.For().OrderByDescending(r => r.IsPredefined).OrderBy(r => r.Name), cancellationToken) + .ConfigureAwait(false)).Items; + var grants = (await unitOfWork.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToLookup(g => g.RoleId); + return [.. roles.Select(r => new RoleWithPermissions(r, [.. grants[r.Id].Select(g => g.Permission).Order(StringComparer.Ordinal)]))]; + } + + /// Clones a role into a new, modifiable one. + /// Who acts. + /// The company. + /// The role to clone. + /// The new code. + /// The new name. + /// Cancellation. + /// The new role. + public async Task CloneAsync(Actor actor, string companyCode, string sourceCode, string newCode, string newName, CancellationToken cancellationToken = default) + { + await DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + ArgumentException.ThrowIfNullOrWhiteSpace(newName); + var code = NormalizeCode(newCode); + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var roles = unitOfWork.Repository(); + var grants = unitOfWork.Repository(); + var source = await roles.FindAsync(Query.For().Where(r => r.Code == sourceCode), cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"No role has code {sourceCode}."); + var sourceId = source.Id; + var patterns = (await grants.ListAsync(Query.For().Where(g => g.RoleId == sourceId), cancellationToken).ConfigureAwait(false)).Items + .Select(g => g.Permission).ToList(); + if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A role cannot grant more than the permissions of who creates it."); + } + + var role = new Role { Code = code, Name = newName.Trim(), Description = source.Description, IsPredefined = false, TemplateCode = source.Code }; + await unitOfWork.InTransactionAsync( + async ct => + { + if (await roles.CountAsync(Query.For().Where(r => r.Code == code), ct).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException(["role_code_taken"]); + } + + role.Id = await roles.InsertAsync(role, ct).ConfigureAwait(false); + await ReplaceGrantsAsync(grants, role.Id, patterns, ct).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); + await audit.WriteAsync(new SecurityEvent("role.cloned", actor.UserName, companyCode, code, new { from = source.Code }), cancellationToken).ConfigureAwait(false); + return role; + } + + /// Sets the permissions of a cloned role. Predefined roles are refused. + /// Who acts. + /// The company. + /// The role. + /// The new permission patterns. + /// Cancellation. + /// A task. + public async Task SetPermissionsAsync(Actor actor, string companyCode, string roleCode, IReadOnlyList patterns, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(patterns); + await DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + if (patterns.Any(p => p != "*" && !PermissionPattern.IsCode(p.Replace("*", "x", StringComparison.Ordinal)))) + { + throw new ValidationFailedException(["permission_invalid"]); + } + + if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A role cannot grant more than the permissions of who changes it."); + } + + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var role = await unitOfWork.Repository().FindAsync(Query.For().Where(r => r.Code == roleCode), cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"No role has code {roleCode}."); + if (role.IsPredefined) + { + throw new ValidationFailedException(["role_predefined"]); + } + + await unitOfWork.InTransactionAsync(ct => ReplaceGrantsAsync(unitOfWork.Repository(), role.Id, patterns, ct), cancellationToken).ConfigureAwait(false); + await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false); + await audit.WriteAsync(new SecurityEvent("role.permissions-changed", actor.UserName, companyCode, roleCode, new { patterns }), cancellationToken).ConfigureAwait(false); + } + + /// Checks that the actor may manage users and roles of a company. + /// The actor. + /// The company. + /// Cancellation. + /// A task. + /// The actor may not. + internal async Task DemandManageAsync(Actor actor, string companyCode, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(actor); + if (actor.IsInstanceAccount) + { + return; + } + + if (!string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); + } + + await permissions.DemandAsync(actor, "company.users.manage", cancellationToken).ConfigureAwait(false); + } + + private static string NormalizeCode(string code) + { + ArgumentNullException.ThrowIfNull(code); + var normalized = code.Trim().ToUpperInvariant(); + return normalized.Length is >= 2 and <= 50 && normalized.All(c => char.IsAsciiLetterOrDigit(c) || c == '_') + ? normalized + : throw new ValidationFailedException(["role_code_invalid"]); + } + + private static async Task ReplaceGrantsAsync(IRepository grants, long roleId, IEnumerable patterns, CancellationToken cancellationToken) + { + var current = (await grants.ListAsync(Query.For().Where(g => g.RoleId == roleId), cancellationToken).ConfigureAwait(false)).Items; + var wanted = patterns.Distinct(StringComparer.Ordinal).ToHashSet(StringComparer.Ordinal); + foreach (var grant in current.Where(g => !wanted.Contains(g.Permission))) + { + await grants.DeleteAsync(grant.Id, cancellationToken).ConfigureAwait(false); + } + + foreach (var pattern in wanted.Except(current.Select(g => g.Permission))) + { + await grants.InsertAsync(new RoleGrant { RoleId = roleId, Permission = pattern }, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Khaemhat.Application/Security/SessionStore.cs b/src/Khaemhat.Application/Security/SessionStore.cs new file mode 100644 index 0000000..e7379fc --- /dev/null +++ b/src/Khaemhat.Application/Security/SessionStore.cs @@ -0,0 +1,468 @@ +using Khaemhat.Core.Caching; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Querying; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Application.Security; + +/// +/// Who a session belongs to: an instance account (sys_sessions) or a user of a company (user_sessions in +/// that company's database). +/// +/// The company whose database holds the user; for instance accounts. +/// The account. +public sealed record SessionOwner(string? CompanyDatabase, long UserId) +{ + /// Whether the owner is an instance account. + public bool IsInstanceAccount => CompanyDatabase is null; +} + +/// What a valid session says about its user, resolved at each request and cached briefly. +/// The session row. +/// The owner. +/// The sign-in state. +/// The user name. +/// The name shown. +/// The level. +/// The company the session works in. +/// For administrators linked to a user of : that user. +/// When the session expires unless used. +/// Whether the cookie survives the browser. +public sealed record SessionIdentity( + long SessionId, SessionOwner Owner, SessionState State, string UserName, string DisplayName, UserLevel Level, + string? CompanyCode, long? LinkedUserId, DateTime ExpiresAt, bool Persistent) +{ + /// The actor for the services. + /// The actor. + public Actor ToActor() => Owner.IsInstanceAccount + ? new Actor(UserName, Level, Owner.UserId, LinkedUserId, CompanyCode) + : new Actor(UserName, UserLevel.Standard, null, Owner.UserId, CompanyCode); +} + +/// A session as listed to its user or to administrators. +/// The session row. +/// The sign-in time. +/// The last request. +/// The client address. +/// The browser. +/// The company. +public sealed record SessionSummary(long Id, DateTime CreatedAt, DateTime LastSeenAt, string? IpAddress, string? UserAgent, string? CompanyCode); + +/// +/// Sign-in sessions (SPEC §7.3). The cookie value is <scope>.<token>: the scope says which database +/// holds the row (_ for the system database, otherwise the company code) and the token is 256 random bits, of which +/// only the SHA-256 hash is stored. Expiry is sliding; revocation takes effect at the next request. +/// +public sealed class SessionStore +{ + private const string SystemScope = "_"; + private const string CacheArea = "sessions"; + private static readonly TimeSpan TouchInterval = TimeSpan.FromMinutes(1); + private static readonly TimeSpan CacheTime = TimeSpan.FromSeconds(30); + + private readonly IUnitOfWorkFactory _factory; + private readonly ICompanyRegistry _companies; + private readonly ICacheProvider _cache; + private readonly SecurityPolicyOptions _policy; + private readonly TimeProvider _clock; + + /// Creates the store. + /// Opens the databases. + /// The company registry. + /// The cache of resolved sessions. + /// Session lifetimes. + /// The clock. + public SessionStore(IUnitOfWorkFactory factory, ICompanyRegistry companies, ICacheProvider cache, SecurityPolicyOptions policy, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(companies); + ArgumentNullException.ThrowIfNull(cache); + ArgumentNullException.ThrowIfNull(policy); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _companies = companies; + _cache = cache; + _policy = policy; + _clock = clock; + } + + private DateTime Now => DateTime.SpecifyKind(Data.Execution.DataAccessContext.Truncate(_clock.GetUtcNow().UtcDateTime), DateTimeKind.Utc); + + /// Creates a session. + /// The owner. + /// The sign-in state. + /// The company the session works in. + /// The client address. + /// The browser. + /// "Remember me on this device". + /// Cancellation. + /// The cookie value. + public async Task CreateAsync( + SessionOwner owner, SessionState state, string? companyCode, string? ipAddress, string? userAgent, bool persistent, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + var token = SecureTokenGenerator.Create(); + var now = Now; + SessionRecord session = owner.IsInstanceAccount ? new SystemSession() : new UserSession(); + session.TokenHash = SecureTokenGenerator.Hash(token); + session.UserId = owner.UserId; + session.State = state; + session.CompanyCode = companyCode; + session.IpAddress = Clip(ipAddress, 64); + session.UserAgent = Clip(userAgent, 400); + session.Persistent = persistent; + session.LastSeenAt = now; + session.ExpiresAt = now + Lifetime(state, persistent); + + await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); + if (session is SystemSession system) + { + await unitOfWork.Repository().InsertAsync(system, cancellationToken).ConfigureAwait(false); + } + else + { + await unitOfWork.Repository().InsertAsync((UserSession)session, cancellationToken).ConfigureAwait(false); + } + + return (owner.CompanyDatabase ?? SystemScope) + "." + token; + } + + /// Finds the valid session of a cookie (not revoked, not expired) and slides its expiry. + /// The cookie value. + /// Cancellation. + /// The session row and owner, or . + public async Task<(SessionRecord Session, SessionOwner Owner)?> FindAsync(string? cookie, CancellationToken cancellationToken = default) + { + if (!TryParse(cookie, out var owner, out var hash)) + { + return null; + } + + await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); + var session = owner.IsInstanceAccount + ? await unitOfWork.Repository().FindAsync(Query.For().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false) + : (SessionRecord?)await unitOfWork.Repository().FindAsync(Query.For().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false); + var now = Now; + if (session is null || session.RevokedAt is not null || session.ExpiresAt <= now) + { + return null; + } + + if (now - session.LastSeenAt >= TouchInterval) + { + session.LastSeenAt = now; + session.ExpiresAt = now + Lifetime(session.State, session.Persistent); + await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false); + } + + return (session, owner with { UserId = session.UserId }); + } + + /// Moves a session to another sign-in state and gives it a new token (the old cookie stops working). + /// The current cookie value. + /// The new state. + /// Cancellation. + /// The new cookie value, or when the session is not valid. + public async Task AdvanceAsync(string cookie, SessionState state, CancellationToken cancellationToken = default) + { + if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner)) + { + return null; + } + + var token = SecureTokenGenerator.Create(); + var now = Now; + session.TokenHash = SecureTokenGenerator.Hash(token); + session.State = state; + session.LastSeenAt = now; + session.ExpiresAt = now + Lifetime(state, session.Persistent); + await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); + await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false); + await ForgetAsync(cookie, cancellationToken).ConfigureAwait(false); + return (owner.CompanyDatabase ?? SystemScope) + "." + token; + } + + /// Changes the company a session of an instance account works in. + /// The cookie value. + /// The company, or . + /// Cancellation. + /// A task. + public async Task SetCompanyAsync(string cookie, string? companyCode, CancellationToken cancellationToken = default) + { + if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner) || !owner.IsInstanceAccount) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "Only instance accounts choose the company."); + } + + session.CompanyCode = companyCode is null ? null : CompanyCodes.Normalize(companyCode); + await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); + await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false); + await ForgetAsync(cookie, cancellationToken).ConfigureAwait(false); + } + + /// Revokes the session of a cookie (sign-out). + /// The cookie value. + /// Why. + /// Cancellation. + /// The owner of the revoked session, or . + public async Task RevokeAsync(string? cookie, string reason, CancellationToken cancellationToken = default) + { + if (await FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner)) + { + return null; + } + + await RevokeAsync(owner, session.Id, reason, cancellationToken).ConfigureAwait(false); + await ForgetAsync(cookie!, cancellationToken).ConfigureAwait(false); + return owner; + } + + /// Revokes one session of an owner (from the list of sessions). + /// The owner. + /// The session row. + /// Why. + /// Cancellation. + /// Whether a session was revoked. + public async Task RevokeAsync(SessionOwner owner, long sessionId, string reason, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + var revoked = await RevokeWhereAsync(owner, s => s.Id == sessionId && s.UserId == owner.UserId, reason, cancellationToken).ConfigureAwait(false); + return revoked > 0; + } + + /// Revokes every session of an owner, except one (password change, administrator action). + /// The owner. + /// Why. + /// The session to keep. + /// Cancellation. + /// The number of sessions revoked. + public Task RevokeAllAsync(SessionOwner owner, string reason, long? exceptSessionId = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + var keep = exceptSessionId ?? 0; + return RevokeWhereAsync(owner, s => s.UserId == owner.UserId && s.Id != keep, reason, cancellationToken); + } + + /// + /// Revokes every session of the users of a company (maintenance, disabling): instance accounts keep theirs, also when + /// they work in that company. + /// + /// The company. + /// Why. + /// Cancellation. + /// The number of sessions revoked. + public async Task RevokeCompanyAsync(string companyCode, string reason, CancellationToken cancellationToken = default) + { + var now = Now; + var why = Clip(reason, 100); + int count; + await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false)) + { + count = await unitOfWork.ExecuteAsync( + SqlFragment.Of($"UPDATE {SqlFragment.Identifier("user_sessions")} SET revoked_at = {now}, revoked_reason = {why} WHERE revoked_at IS NULL"), + cancellationToken).ConfigureAwait(false); + } + + if (count > 0) + { + await _cache.PublishInvalidationAsync(CacheKeys.Prefix(null, CacheArea), cancellationToken).ConfigureAwait(false); + } + + return count; + } + + /// Whether a signed-in session is still valid (the periodic check of open Blazor circuits). + /// The owner. + /// The session row. + /// Cancellation. + /// while the session is active, not revoked and not expired. + public async Task IsActiveAsync(SessionOwner owner, long sessionId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + var now = Now; + await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); + var userId = owner.UserId; + return owner.IsInstanceAccount + ? await unitOfWork.Repository().CountAsync( + Query.For().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active), + cancellationToken).ConfigureAwait(false) > 0 + : await unitOfWork.Repository().CountAsync( + Query.For().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active), + cancellationToken).ConfigureAwait(false) > 0; + } + + /// The active sessions of an owner. + /// The owner. + /// Cancellation. + /// The sessions, most recent first. + public async Task> ListAsync(SessionOwner owner, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + var now = Now; + var userId = owner.UserId; + await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); + IEnumerable sessions = owner.IsInstanceAccount + ? (await unitOfWork.Repository().ListAsync( + Query.For().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken) + .ConfigureAwait(false)).Items + : (await unitOfWork.Repository().ListAsync( + Query.For().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken) + .ConfigureAwait(false)).Items; + return [.. sessions.Select(s => new SessionSummary(s.Id, s.CreatedAt, s.LastSeenAt, s.IpAddress, s.UserAgent, s.CompanyCode))]; + } + + /// Whether an owner has signed in before from the same browser (to warn about new devices). + /// The owner. + /// The browser. + /// The session just created. + /// Cancellation. + /// if a previous session used the same browser. + public async Task IsKnownDeviceAsync(SessionOwner owner, string? userAgent, long exceptSessionId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + var agent = Clip(userAgent, 400); + var userId = owner.UserId; + await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); + return owner.IsInstanceAccount + ? await unitOfWork.Repository().CountAsync( + Query.For().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken) + .ConfigureAwait(false) > 0 + : await unitOfWork.Repository().CountAsync( + Query.For().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken) + .ConfigureAwait(false) > 0; + } + + /// + /// The users with an active session across the system database and every company (the concurrent-user limit of the + /// licence, SPEC §7.3). + /// + /// Cancellation. + /// The owners with at least one active session. + public async Task> ActiveOwnersAsync(CancellationToken cancellationToken = default) + { + var now = Now; + var owners = new HashSet(); + await using (var system = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) + { + var rows = await system.QueryAsync( + SqlFragment.Of($"SELECT DISTINCT user_id FROM {SqlFragment.Identifier("sys_sessions")} WHERE revoked_at IS NULL AND expires_at > {now} AND state = {nameof(SessionState.Active)}"), + cancellationToken).ConfigureAwait(false); + owners.UnionWith(rows.Select(id => new SessionOwner(null, id))); + } + + foreach (var company in await _companies.ListAsync(cancellationToken).ConfigureAwait(false)) + { + if (company.Status is Core.Instance.CompanyStatus.Disabled) + { + continue; + } + + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false); + var rows = await unitOfWork.QueryAsync( + SqlFragment.Of($"SELECT DISTINCT user_id FROM {SqlFragment.Identifier("user_sessions")} WHERE revoked_at IS NULL AND expires_at > {now} AND state = {nameof(SessionState.Active)}"), + cancellationToken).ConfigureAwait(false); + owners.UnionWith(rows.Select(id => new SessionOwner(company.Code, id))); + } + + return owners; + } + + /// Deletes sessions expired or revoked more than ago (the cleanup job). + /// The database. + /// How long to keep them for the history. + /// Cancellation. + /// The rows deleted. + public async Task PurgeAsync(DatabaseScope scope, TimeSpan age, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(scope); + var limit = Now - age; + var table = scope.IsSystem ? "sys_sessions" : "user_sessions"; + await using var unitOfWork = await _factory.CreateAsync(scope, cancellationToken).ConfigureAwait(false); + return await unitOfWork.ExecuteAsync( + SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier(table)} WHERE expires_at < {limit} OR revoked_at < {limit}"), cancellationToken).ConfigureAwait(false); + } + + /// The cache key of a cookie's resolved identity. + /// The cookie value. + /// The key. + public static string CacheKey(string cookie) => CacheKeys.For(null, CacheArea, SecureTokenGenerator.Hash(cookie ?? string.Empty)); + + /// Forgets the cached identity of a cookie. + /// The cookie value. + /// Cancellation. + /// A task. + public ValueTask ForgetAsync(string cookie, CancellationToken cancellationToken = default) => _cache.RemoveAsync(CacheKey(cookie), cancellationToken); + + /// How long a resolved identity may stay cached (revocations by id also clear the whole area). + public static TimeSpan IdentityCacheTime => CacheTime; + + private async Task RevokeWhereAsync(SessionOwner owner, System.Linq.Expressions.Expression> filter, string reason, CancellationToken cancellationToken) + { + var now = Now; + var predicate = filter.Compile(); + await using var unitOfWork = await OpenAsync(owner, cancellationToken).ConfigureAwait(false); + var userId = owner.UserId; + IEnumerable sessions = owner.IsInstanceAccount + ? (await unitOfWork.Repository().ListAsync(Query.For().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items + : (await unitOfWork.Repository().ListAsync(Query.For().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items; + var count = 0; + foreach (var session in sessions.Where(predicate)) + { + session.RevokedAt = now; + session.RevokedReason = Clip(reason, 100); + await SaveAsync(unitOfWork, session, cancellationToken).ConfigureAwait(false); + count++; + } + + if (count > 0) + { + // The identity cache is keyed by cookie, which is unknown here: drop the whole area (entries live 30 seconds). + await _cache.PublishInvalidationAsync(CacheKeys.Prefix(null, CacheArea), cancellationToken).ConfigureAwait(false); + } + + return count; + } + + private static async Task SaveAsync(IUnitOfWork unitOfWork, SessionRecord session, CancellationToken cancellationToken) + { + if (session is SystemSession system) + { + await unitOfWork.Repository().UpdateAsync(system, cancellationToken).ConfigureAwait(false); + } + else + { + await unitOfWork.Repository().UpdateAsync((UserSession)session, cancellationToken).ConfigureAwait(false); + } + } + + private TimeSpan Lifetime(SessionState state, bool persistent) => + state != SessionState.Active ? _policy.PendingStepLifetime : persistent ? _policy.PersistentSessionLifetime : _policy.SessionLifetime; + + private Task OpenAsync(SessionOwner owner, CancellationToken cancellationToken) => + _factory.CreateAsync(owner.IsInstanceAccount ? DatabaseScope.System : DatabaseScope.Company(owner.CompanyDatabase!), cancellationToken); + + private static bool TryParse(string? cookie, out SessionOwner owner, out string hash) + { + owner = new SessionOwner(null, 0); + hash = string.Empty; + var dot = cookie?.IndexOf('.', StringComparison.Ordinal) ?? -1; + if (dot <= 0 || cookie!.Length - dot < 40) + { + return false; + } + + var scope = cookie[..dot]; + if (scope != SystemScope && !CompanyCodes.IsValid(scope)) + { + return false; + } + + owner = new SessionOwner(scope == SystemScope ? null : scope, 0); + hash = SecureTokenGenerator.Hash(cookie[(dot + 1)..]); + return true; + } + + private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length]; +} diff --git a/src/Khaemhat.Application/Security/SignInService.cs b/src/Khaemhat.Application/Security/SignInService.cs new file mode 100644 index 0000000..8a092a6 --- /dev/null +++ b/src/Khaemhat.Application/Security/SignInService.cs @@ -0,0 +1,416 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Notifications; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Infrastructure.Security; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.Security; + +/// A sign-in attempt from the login page (mockup 001). +/// The company chosen; instance accounts may leave it empty. +/// The user name. +/// The password. +/// "Remember me on this device". +/// The client address. +/// The browser. +public sealed record SignInRequest(string? CompanyCode, string UserName, string Password, bool Persistent, string? IpAddress, string? UserAgent); + +/// The outcome of a sign-in step. +/// Whether the step succeeded. +/// The error code otherwise (). +/// The new cookie value to set. +/// The state reached: the page to show next. +public sealed record SignInResult(bool Succeeded, string? Error, string? Cookie, SessionState? State) +{ + /// A failure. + /// The error code. + /// The outcome. + public static SignInResult Fail(string error) => new(false, error, null, null); +} + +/// The data of a TOTP setup, shown once. +/// The secret in base32, for manual entry. +/// The otpauth:// address. +public sealed record TotpSetup(string Secret, string ProvisioningUri); + +/// +/// The sign-in flow (SPEC §7.3; mockups 001-003): password with lockout, then the two-step verification (mandatory for +/// instance accounts), then the forced password change, each step on a session in a pending state whose token is +/// renewed at every step. Instance accounts are found in the system database first; otherwise the company user. +/// Every outcome is recorded in sys_security_audit; the error never says whether the user exists. +/// +public sealed class SignInService( + SystemUserService systemUsers, + UserService companyUsers, + ICompanyRegistry companies, + AccountSecurity security, + SessionStore sessions, + ILicenseGate licenses, + NotificationDispatcher notifications, + ISecurityAuditLog audit, + ILogger logger) +{ + /// Checks company, user and password and opens a session in the first state. + /// The attempt. + /// Cancellation. + /// The outcome and the cookie. + public async Task SignInAsync(SignInRequest request, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + var companyCode = string.IsNullOrWhiteSpace(request.CompanyCode) ? null : request.CompanyCode.Trim().ToUpperInvariant(); + if (companyCode is not null && !CompanyCodes.IsValid(companyCode)) + { + return SignInResult.Fail(SecurityErrors.InvalidCredentials); + } + + var company = companyCode is null ? null : await companies.FindAsync(companyCode, cancellationToken).ConfigureAwait(false); + if (companyCode is not null && company is null) + { + await AuditAsync("login.failed", request.UserName, companyCode, request, new { reason = "company_unknown" }, cancellationToken).ConfigureAwait(false); + return SignInResult.Fail(SecurityErrors.InvalidCredentials); + } + + var instanceAccount = await systemUsers.FindByNameAsync(request.UserName, cancellationToken).ConfigureAwait(false); + if (instanceAccount is not null) + { + return await CompleteAsync(instanceAccount, new SessionOwner(null, instanceAccount.Id), company?.Code, request, + ct => systemUsers.SaveAsync(instanceAccount, ct), cancellationToken).ConfigureAwait(false); + } + + if (company is null) + { + await AuditAsync("login.failed", request.UserName, null, request, new { reason = "company_missing" }, cancellationToken).ConfigureAwait(false); + return SignInResult.Fail(SecurityErrors.InvalidCredentials); + } + + if (company.Status is CompanyStatus.Maintenance or CompanyStatus.Disabled) + { + return SignInResult.Fail(SecurityErrors.CompanyUnavailable); + } + + var user = await companyUsers.FindByNameAsync(company.Code, request.UserName, cancellationToken).ConfigureAwait(false); + if (user is null || user.Kind == UserKind.Technical) + { + // Hash anyway, so that an unknown user takes as long as a wrong password. + _ = PasswordHasher.Verify(DummyHash.Value, request.Password); + await AuditAsync("login.failed", request.UserName, company.Code, request, new { reason = "user_unknown" }, cancellationToken).ConfigureAwait(false); + return SignInResult.Fail(SecurityErrors.InvalidCredentials); + } + + return await CompleteAsync(user, new SessionOwner(company.Code, user.Id), company.Code, request, + ct => companyUsers.SaveAsync(company.Code, user, ct), cancellationToken).ConfigureAwait(false); + } + + /// Checks the TOTP code (or a recovery code) of a session waiting for it. + /// The cookie value. + /// The code. + /// Cancellation. + /// The outcome and the new cookie. + public async Task VerifyTotpAsync(string cookie, string code, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(code); + var pending = await LoadPendingAsync(cookie, SessionState.PendingTotp, cancellationToken).ConfigureAwait(false); + if (pending is null) + { + return SignInResult.Fail(SecurityErrors.InvalidCredentials); + } + + var (account, owner, save, company) = pending.Value; + var valid = code.Contains('-', StringComparison.Ordinal) ? AccountSecurity.UseRecoveryCode(account, code) : security.VerifyTotp(account, code); + if (!valid) + { + account.FailedLoginCount++; + var locked = account.FailedLoginCount >= security.Options.MaxFailedAttempts; + if (locked) + { + account.LockedUntil = DateTime.UtcNow + security.Options.LockoutDuration; + account.FailedLoginCount = 0; + await sessions.RevokeAsync(cookie, "totp_locked", cancellationToken).ConfigureAwait(false); + } + + await save(cancellationToken).ConfigureAwait(false); + await AuditAsync("login.totp-failed", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false); + return SignInResult.Fail(locked ? SecurityErrors.AccountLocked : SecurityErrors.TotpInvalid); + } + + account.FailedLoginCount = 0; + await save(cancellationToken).ConfigureAwait(false); + var next = account.MustChangePassword ? SessionState.PendingPasswordChange : SessionState.Active; + return await AdvanceAsync(cookie, next, account, owner, company, cancellationToken).ConfigureAwait(false); + } + + /// Starts the TOTP setup of a session waiting for it, or of a complete session (profile). + /// The cookie value. + /// Cancellation. + /// The secret to show, or when the session is not valid. + public async Task BeginTotpSetupAsync(string cookie, CancellationToken cancellationToken = default) + { + var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false); + if (pending is null || pending.Value.Account.TotpEnabled) + { + return null; + } + + var (account, _, save, company) = pending.Value; + var secret = security.PendingTotpSecret(account); + if (secret is null) + { + secret = security.BeginTotpSetup(account); + await save(cancellationToken).ConfigureAwait(false); + } + + return new TotpSetup(secret, TotpGenerator.ProvisioningUri(secret, company is null ? account.UserName : account.UserName + "@" + company)); + } + + /// Completes the TOTP setup with the first code from the app. + /// The cookie value. + /// The code. + /// Cancellation. + /// The outcome, the new cookie and the recovery codes to show once. + public async Task<(SignInResult Result, IReadOnlyList? RecoveryCodes)> ConfirmTotpSetupAsync(string cookie, string code, CancellationToken cancellationToken = default) + { + var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false); + if (pending is null) + { + return (SignInResult.Fail(SecurityErrors.InvalidCredentials), null); + } + + var (account, owner, save, company) = pending.Value; + var codes = security.ConfirmTotpSetup(account, code); + if (codes is null) + { + return (SignInResult.Fail(SecurityErrors.TotpInvalid), null); + } + + await save(cancellationToken).ConfigureAwait(false); + await AuditAsync("user.totp-enabled", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false); + var session = await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false); + if (session?.Session.State != SessionState.PendingTotpSetup) + { + return (new SignInResult(true, null, cookie, session?.Session.State), codes); + } + + return (await AdvanceAsync(cookie, SessionState.Active, account, owner, company, cancellationToken).ConfigureAwait(false), codes); + } + + /// Changes the password: the forced change of mockup 003, or a change from the profile. + /// The cookie value. + /// The current (or temporary) password. + /// The new password. + /// Cancellation. + /// The outcome, with every policy error code joined in . + public async Task ChangePasswordAsync(string cookie, string currentPassword, string newPassword, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(currentPassword); + ArgumentNullException.ThrowIfNull(newPassword); + var pending = await LoadPendingAsync(cookie, null, cancellationToken).ConfigureAwait(false); + if (pending is null) + { + return SignInResult.Fail(SecurityErrors.InvalidCredentials); + } + + var (account, owner, save, company) = pending.Value; + if (PasswordHasher.Verify(account.PasswordHash, currentPassword) == PasswordVerification.Failed) + { + return SignInResult.Fail(SecurityErrors.CurrentPasswordWrong); + } + + var errors = security.ChangePassword(account, newPassword); + if (errors.Count > 0) + { + return SignInResult.Fail(string.Join(',', errors)); + } + + await save(cancellationToken).ConfigureAwait(false); + var current = await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false); + await sessions.RevokeAllAsync(owner, "password_changed", current?.Session.Id, cancellationToken).ConfigureAwait(false); + await AuditAsync("user.password-changed", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false); + if (current?.Session.State != SessionState.PendingPasswordChange) + { + return new SignInResult(true, null, cookie, current?.Session.State); + } + + var next = NeedsTotpSetup(account, owner) ? SessionState.PendingTotpSetup : SessionState.Active; + return await AdvanceAsync(cookie, next, account, owner, company, cancellationToken).ConfigureAwait(false); + } + + /// Signs out: the session is revoked. + /// The cookie value. + /// Cancellation. + /// A task. + public async Task SignOutAsync(string? cookie, CancellationToken cancellationToken = default) + { + var identity = await ResolveAsync(cookie, cancellationToken).ConfigureAwait(false); + var owner = await sessions.RevokeAsync(cookie, "sign_out", cancellationToken).ConfigureAwait(false); + if (owner is not null) + { + var userName = identity?.UserName ?? owner.UserId.ToString(System.Globalization.CultureInfo.InvariantCulture); + await AuditAsync("logout", userName, identity?.CompanyCode ?? owner.CompanyDatabase, null, null, cancellationToken).ConfigureAwait(false); + } + } + + /// Resolves the identity of a cookie for the authentication handler. + /// The cookie value. + /// Cancellation. + /// The identity, or when the session is not valid or the account cannot sign in anymore. + public async Task ResolveAsync(string? cookie, CancellationToken cancellationToken = default) + { + if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner)) + { + return null; + } + + if (owner.IsInstanceAccount) + { + var account = await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false); + if (account is not { IsActive: true }) + { + return null; + } + + var linked = account.LinkedCompanyCode is not null && account.LinkedCompanyCode == session.CompanyCode ? account.LinkedUserId : null; + return new SessionIdentity(session.Id, owner, session.State, account.UserName, account.DisplayName, account.Level, session.CompanyCode, linked, session.ExpiresAt, session.Persistent); + } + + var company = await companies.FindAsync(owner.CompanyDatabase!, cancellationToken).ConfigureAwait(false); + if (company is null || company.Status is CompanyStatus.Maintenance or CompanyStatus.Disabled) + { + return null; + } + + var user = await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false); + return user is { IsActive: true } + ? new SessionIdentity(session.Id, owner, session.State, user.UserName, user.DisplayName, UserLevel.Standard, company.Code, null, session.ExpiresAt, session.Persistent) + : null; + } + + private async Task CompleteAsync( + IAccount account, SessionOwner owner, string? companyCode, SignInRequest request, Func save, CancellationToken cancellationToken) + { + var check = security.CheckPassword(account, request.Password); + await save(cancellationToken).ConfigureAwait(false); + if (!check.Succeeded) + { + await AuditAsync("login.failed", account.UserName, companyCode, request, new { reason = check.Error }, cancellationToken).ConfigureAwait(false); + return SignInResult.Fail(check.Error!); + } + + await licenses.RefreshAsync(cancellationToken).ConfigureAwait(false); + var isSuperUser = account is SystemUser { Level: UserLevel.SuperUser }; + if (!isSuperUser) + { + var active = await sessions.ActiveOwnersAsync(cancellationToken).ConfigureAwait(false); + if (!active.Contains(owner) && active.Count >= licenses.Current.MaxConcurrentUsers) + { + await AuditAsync("login.refused", account.UserName, companyCode, request, new { reason = SecurityErrors.ConcurrentUsersExceeded }, cancellationToken).ConfigureAwait(false); + return SignInResult.Fail(SecurityErrors.ConcurrentUsersExceeded); + } + } + + var state = account.TotpEnabled ? SessionState.PendingTotp + : check.MustChangePassword ? SessionState.PendingPasswordChange + : NeedsTotpSetup(account, owner) ? SessionState.PendingTotpSetup + : SessionState.Active; + var cookie = await sessions.CreateAsync(owner, state, companyCode, request.IpAddress, request.UserAgent, request.Persistent, cancellationToken).ConfigureAwait(false); + await AuditAsync("login.password-accepted", account.UserName, companyCode, request, new { next = state.ToString() }, cancellationToken).ConfigureAwait(false); + if (state == SessionState.Active) + { + await OnActiveAsync(cookie, account, owner, companyCode, save, cancellationToken).ConfigureAwait(false); + } + + return new SignInResult(true, null, cookie, state); + } + + private async Task AdvanceAsync(string cookie, SessionState next, IAccount account, SessionOwner owner, string? company, CancellationToken cancellationToken) + { + var newCookie = await sessions.AdvanceAsync(cookie, next, cancellationToken).ConfigureAwait(false); + if (newCookie is null) + { + return SignInResult.Fail(SecurityErrors.InvalidCredentials); + } + + if (next == SessionState.Active) + { + await OnActiveAsync(newCookie, account, owner, company, SaveFor(account, owner), cancellationToken).ConfigureAwait(false); + } + + return new SignInResult(true, null, newCookie, next); + } + + private async Task OnActiveAsync(string cookie, IAccount account, SessionOwner owner, string? company, Func save, CancellationToken cancellationToken) + { + security.RecordSignIn(account); + await save(cancellationToken).ConfigureAwait(false); + await AuditAsync("login.succeeded", account.UserName, company, null, null, cancellationToken).ConfigureAwait(false); + if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is var (session, _) + && !await sessions.IsKnownDeviceAsync(owner, session.UserAgent, session.Id, cancellationToken).ConfigureAwait(false)) + { + var message = new NotificationMessage( + "security", + NotificationSeverity.Warning, + "Nuovo accesso da un dispositivo non riconosciuto", + $"Accesso da {session.IpAddress ?? "indirizzo sconosciuto"} con {session.UserAgent ?? "browser sconosciuto"}. Se non sei stato tu, cambia la password e chiudi le sessioni dal profilo.", + "/profilo/sessioni"); + if (owner.IsInstanceAccount) + { + await notifications.NotifyInstanceAsync(message, owner.UserId, cancellationToken).ConfigureAwait(false); + } + else + { + await notifications.NotifyCompanyAsync(owner.CompanyDatabase!, message, owner.UserId, cancellationToken).ConfigureAwait(false); + } + } + } + + private bool NeedsTotpSetup(IAccount account, SessionOwner owner) => + !account.TotpEnabled && (owner.IsInstanceAccount || account is CompanyUser { TotpRequired: true } || security.Options.TotpRequiredForUsers); + + private Func SaveFor(IAccount account, SessionOwner owner) => account switch + { + SystemUser system => ct => systemUsers.SaveAsync(system, ct), + CompanyUser user => ct => companyUsers.SaveAsync(owner.CompanyDatabase!, user, ct), + _ => throw new InvalidOperationException("Unknown account type."), + }; + + private async Task<(IAccount Account, SessionOwner Owner, Func Save, string? Company)?> LoadPendingAsync( + string? cookie, SessionState? expected, CancellationToken cancellationToken) + { + if (await sessions.FindAsync(cookie, cancellationToken).ConfigureAwait(false) is not var (session, owner) + || (expected is not null && session.State != expected)) + { + return null; + } + + IAccount? account = owner.IsInstanceAccount + ? await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false) + : await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false); + if (account is not { IsActive: true }) + { + return null; + } + + return (account, owner, SaveFor(account, owner), session.CompanyCode); + } + + private async Task AuditAsync(string action, string? userName, string? company, SignInRequest? request, object? details, CancellationToken cancellationToken) + { + try + { + await audit.WriteAsync(new SecurityEvent(action, userName, company, null, details, request?.IpAddress), cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Security audit {Action} not written.", action); + } + } + + /// A hash of a random password, compared when the user does not exist so the timing stays the same. + private static class DummyHash + { + public static readonly string Value = PasswordHasher.Hash(SecureTokenGenerator.Create()); + } +} diff --git a/src/Khaemhat.Application/Security/SystemUserService.cs b/src/Khaemhat.Application/Security/SystemUserService.cs new file mode 100644 index 0000000..333e2ca --- /dev/null +++ b/src/Khaemhat.Application/Security/SystemUserService.cs @@ -0,0 +1,297 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Security; + +/// A new instance account. +/// The sign-in name. +/// The name shown. +/// The e-mail address. +public sealed record NewSystemUser(string UserName, string DisplayName, string? Email); + +/// +/// Instance accounts (sys_users, SPEC §7.1): one super user, created at first start and never deleted or +/// demoted; administrators, created and managed only by the super user. An administrator manages only its own profile. +/// +public sealed class SystemUserService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly AccountSecurity _security; + private readonly ISecurityAuditLog _audit; + + /// Creates the service. + /// Opens the system database. + /// The credential rules. + /// The security audit. + public SystemUserService(IUnitOfWorkFactory factory, AccountSecurity security, ISecurityAuditLog audit) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(security); + ArgumentNullException.ThrowIfNull(audit); + _factory = factory; + _security = security; + _audit = audit; + } + + /// Whether any instance account exists (the bootstrap reads the variables only when none does). + /// Cancellation. + /// when sys_users has rows. + public async Task AnyAsync(CancellationToken cancellationToken = default) + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + return await unitOfWork.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0; + } + + /// Lists the instance accounts. + /// Cancellation. + /// The accounts, super user first. + public async Task> ListAsync(CancellationToken cancellationToken = default) + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var page = await unitOfWork.Repository() + .ListAsync(Query.For().OrderByDescending(u => u.Level).OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false); + return page.Items; + } + + /// Finds an account by sign-in name. + /// The name, in any case. + /// Cancellation. + /// The account, or . + public async Task FindByNameAsync(string userName, CancellationToken cancellationToken = default) + { + if (!UserNames.IsValid(userName)) + { + return null; + } + + var name = UserNames.Normalize(userName); + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + return await unitOfWork.Repository().FindAsync(Query.For().Where(u => u.UserName == name), cancellationToken) + .ConfigureAwait(false); + } + + /// Finds an account. + /// The identifier. + /// Cancellation. + /// The account, or . + public async Task GetAsync(long id, CancellationToken cancellationToken = default) + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + return await unitOfWork.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates the super user at first start, from KHAEMHAT_SUPERUSER*. Refused when a super user exists. + /// The password must be changed at the first access and the two-step verification set up. + /// + /// The account. + /// The first password. + /// Cancellation. + /// The account. + /// The password does not satisfy the policy. + public async Task CreateSuperUserAsync(NewSystemUser account, string password, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(account); + var user = NewAccount(account, UserLevel.SuperUser); + var errors = _security.SetInitialPassword(user, password, temporary: false); + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var users = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + await unitOfWork.AcquireLockAsync("sys-users", ct).ConfigureAwait(false); + if (await users.CountAsync(Query.For().Where(u => u.Level == UserLevel.SuperUser), ct).ConfigureAwait(false) > 0) + { + throw new InvalidOperationException("The super user already exists."); + } + + await users.InsertAsync(user, ct).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); + + await _audit.WriteAsync(new SecurityEvent("user.superuser-created", Actor.System.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false); + return user; + } + + /// Creates an administrator with a temporary password. Only the super user may. + /// Who acts. + /// The account. + /// Cancellation. + /// The account and its temporary password, to give once. + public async Task<(SystemUser User, string TemporaryPassword)> CreateAdministratorAsync( + Actor actor, NewSystemUser account, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(account); + RequireSuperUser(actor); + var user = NewAccount(account, UserLevel.Administrator); + var password = _security.IssueTemporaryPassword(user); + + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var users = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + if (await users.CountAsync(Query.For().Where(u => u.UserName == user.UserName), ct).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException(["user_name_taken"]); + } + + await users.InsertAsync(user, ct).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); + + await _audit.WriteAsync(new SecurityEvent("user.administrator-created", actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false); + return (user, password); + } + + /// Changes name, e-mail and state of an account. + /// Who acts: the super user, or an administrator on its own profile. + /// The account. + /// The new name. + /// The new e-mail. + /// The new state; the super user cannot be disabled. + /// Cancellation. + /// A task. + public async Task UpdateAsync(Actor actor, long id, string displayName, string? email, bool isActive, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentException.ThrowIfNullOrWhiteSpace(displayName); + await ChangeAsync( + actor, + id, + "user.updated", + user => + { + if (user.Level == UserLevel.SuperUser && !isActive) + { + throw new AccessDeniedException(SecurityErrors.LevelTooLow, "The super user cannot be disabled."); + } + + if (!actor.IsSuperUser && user.IsActive != isActive) + { + throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user enables or disables administrators."); + } + + user.DisplayName = displayName.Trim(); + user.Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim(); + user.IsActive = isActive; + }, + allowSelf: true, + cancellationToken).ConfigureAwait(false); + } + + /// Gives an administrator a new temporary password. Only the super user may. + /// Who acts. + /// The account. + /// Cancellation. + /// The temporary password. + public async Task ResetPasswordAsync(Actor actor, long id, CancellationToken cancellationToken = default) + { + string? password = null; + await ChangeAsync(actor, id, "user.password-reset", user => password = _security.IssueTemporaryPassword(user), allowSelf: false, cancellationToken) + .ConfigureAwait(false); + return password!; + } + + /// Turns off the two-step verification of an administrator who lost the phone. Only the super user may. + /// Who acts. + /// The account. + /// Cancellation. + /// A task. + public Task ResetTotpAsync(Actor actor, long id, CancellationToken cancellationToken = default) => + ChangeAsync(actor, id, "user.totp-reset", AccountSecurity.ResetTotp, allowSelf: false, cancellationToken); + + /// Links an administrator to a company user, to work as that user without a second sign-in. + /// Who acts: the super user, or the administrator itself. + /// The administrator. + /// The company, or to remove the link. + /// The company user. + /// Cancellation. + /// A task. + public Task LinkAsync(Actor actor, long id, string? companyCode, long? companyUserId, CancellationToken cancellationToken = default) => + ChangeAsync( + actor, + id, + "user.linked", + user => + { + user.LinkedCompanyCode = companyCode is null ? null : CompanyCodes.Normalize(companyCode); + user.LinkedUserId = companyCode is null ? null : companyUserId; + }, + allowSelf: true, + cancellationToken); + + /// Deletes an administrator. Only the super user may; the super user itself cannot be deleted. + /// Who acts. + /// The account. + /// Cancellation. + /// A task. + public async Task DeleteAsync(Actor actor, long id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + RequireSuperUser(actor); + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var users = unitOfWork.Repository(); + var user = await users.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No instance account has this identifier."); + if (user.Level == UserLevel.SuperUser) + { + throw new AccessDeniedException(SecurityErrors.LevelTooLow, "The super user cannot be deleted."); + } + + await users.DeleteAsync(id, cancellationToken).ConfigureAwait(false); + await _audit.WriteAsync(new SecurityEvent("user.deleted", actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false); + } + + /// Saves an account changed by the sign-in flow (failures, lockout, TOTP step, password). + /// The account. + /// Cancellation. + /// A task. + public async Task SaveAsync(SystemUser user, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(user); + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + await unitOfWork.Repository().UpdateAsync(user, cancellationToken).ConfigureAwait(false); + } + + private static SystemUser NewAccount(NewSystemUser account, UserLevel level) => new() + { + UserName = UserNames.Normalize(account.UserName), + DisplayName = string.IsNullOrWhiteSpace(account.DisplayName) ? account.UserName.Trim() : account.DisplayName.Trim(), + Email = string.IsNullOrWhiteSpace(account.Email) ? null : account.Email.Trim(), + Level = level, + IsActive = true, + }; + + private static void RequireSuperUser(Actor actor) + { + if (!actor.IsSuperUser) + { + throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user manages administrators."); + } + } + + private async Task ChangeAsync(Actor actor, long id, string action, Action change, bool allowSelf, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(actor); + var self = actor.SystemUserId == id; + if (!actor.IsSuperUser && !(allowSelf && self)) + { + throw new AccessDeniedException(SecurityErrors.LevelTooLow, "Only the super user manages other instance accounts."); + } + + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var users = unitOfWork.Repository(); + var user = await users.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No instance account has this identifier."); + change(user); + await users.UpdateAsync(user, cancellationToken).ConfigureAwait(false); + await _audit.WriteAsync(new SecurityEvent(action, actor.UserName, Target: user.UserName), cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Application/Security/UserService.cs b/src/Khaemhat.Application/Security/UserService.cs new file mode 100644 index 0000000..9dc1f9b --- /dev/null +++ b/src/Khaemhat.Application/Security/UserService.cs @@ -0,0 +1,274 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; + +namespace Khaemhat.Application.Security; + +/// A new company user. +/// The sign-in name. +/// The name shown. +/// The e-mail address. +/// A person or a technical user for the API. +/// The role codes. +/// The per-user flags. +public sealed record NewCompanyUser(string UserName, string DisplayName, string? Email, UserKind Kind, IReadOnlyList Roles, UserFlags Flags); + +/// +/// Company users (users, SPEC §7.1): created by instance accounts or by company users holding +/// company.users.manage, who can never give roles above their own permissions. +/// +public sealed class UserService(IUnitOfWorkFactory factory, AccountSecurity security, PermissionService permissions, RoleService roles, ISecurityAuditLog audit) +{ + /// Lists the users of a company. + /// The company. + /// Cancellation. + /// The users by name. + public async Task> ListAsync(string companyCode, CancellationToken cancellationToken = default) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + return (await unitOfWork.Repository().ListAsync(Query.For().OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false)).Items; + } + + /// Finds a user by sign-in name. + /// The company. + /// The name, in any case. + /// Cancellation. + /// The user, or . + public async Task FindByNameAsync(string companyCode, string userName, CancellationToken cancellationToken = default) + { + if (!UserNames.IsValid(userName)) + { + return null; + } + + var name = UserNames.Normalize(userName); + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + return await unitOfWork.Repository().FindAsync(Query.For().Where(u => u.UserName == name), cancellationToken).ConfigureAwait(false); + } + + /// Finds a user. + /// The company. + /// The identifier. + /// Cancellation. + /// The user, or . + public async Task GetAsync(string companyCode, long id, CancellationToken cancellationToken = default) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + return await unitOfWork.Repository().GetAsync(id, cancellationToken).ConfigureAwait(false); + } + + /// Creates a user with a temporary password (people) or none (technical users). + /// Who acts. + /// The company. + /// The user. + /// Cancellation. + /// The user and its temporary password ( for technical users). + public async Task<(CompanyUser User, string? TemporaryPassword)> CreateAsync( + Actor actor, string companyCode, NewCompanyUser request, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(request); + await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + var user = new CompanyUser + { + UserName = UserNames.Normalize(request.UserName), + DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? request.UserName.Trim() : request.DisplayName.Trim(), + Email = string.IsNullOrWhiteSpace(request.Email) ? null : request.Email.Trim(), + Kind = request.Kind, + IsActive = true, + OwnCustomersOnly = request.Flags.OwnCustomersOnly, + CanSeeCosts = request.Flags.CanSeeCosts, + CanExport = request.Flags.CanExport, + CanUseApi = request.Kind == UserKind.Technical || request.Flags.CanUseApi, + TotpRequired = security.Options.TotpRequiredForUsers, + }; + var password = request.Kind == UserKind.Human ? security.IssueTemporaryPassword(user) : null; + + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var users = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + if (await users.CountAsync(Query.For().Where(u => u.UserName == user.UserName), ct).ConfigureAwait(false) > 0) + { + throw new ValidationFailedException(["user_name_taken"]); + } + + user.Id = await users.InsertAsync(user, ct).ConfigureAwait(false); + await AssignRolesAsync(unitOfWork, actor, user.Id, request.Roles, ct).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); + + await audit.WriteAsync(new SecurityEvent("user.created", actor.UserName, companyCode, user.UserName, new { roles = request.Roles, kind = request.Kind.ToString() }), cancellationToken) + .ConfigureAwait(false); + return (user, password); + } + + /// Replaces the roles of a user. + /// Who acts. + /// The company. + /// The user. + /// The role codes. + /// Cancellation. + /// A task. + public async Task SetRolesAsync(Actor actor, string companyCode, long userId, IReadOnlyList roleCodes, CancellationToken cancellationToken = default) + { + await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await unitOfWork.InTransactionAsync(ct => AssignRolesAsync(unitOfWork, actor, userId, roleCodes, ct), cancellationToken).ConfigureAwait(false); + await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false); + await audit.WriteAsync(new SecurityEvent("user.roles-changed", actor.UserName, companyCode, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), new { roles = roleCodes }), cancellationToken) + .ConfigureAwait(false); + } + + /// Grants or denies single permissions to a user over its roles. Denials win. + /// Who acts. + /// The company. + /// The user. + /// Permission code and whether it is allowed. + /// Cancellation. + /// A task. + public async Task SetOverridesAsync(Actor actor, string companyCode, long userId, IReadOnlyDictionary overrides, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(overrides); + await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + if (!await permissions.CoversAsync(actor, overrides.Where(o => o.Value).Select(o => o.Key), cancellationToken).ConfigureAwait(false)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A user cannot grant permissions it does not hold."); + } + + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var repository = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + foreach (var old in (await repository.ListAsync(Query.For().Where(o => o.UserId == userId), ct).ConfigureAwait(false)).Items) + { + await repository.DeleteAsync(old.Id, ct).ConfigureAwait(false); + } + + foreach (var (code, allowed) in overrides) + { + await repository.InsertAsync(new UserPermissionOverride { UserId = userId, Permission = code, Allowed = allowed }, ct).ConfigureAwait(false); + } + }, + cancellationToken).ConfigureAwait(false); + await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false); + await audit.WriteAsync(new SecurityEvent("user.overrides-changed", actor.UserName, companyCode, userId.ToString(System.Globalization.CultureInfo.InvariantCulture), overrides), cancellationToken) + .ConfigureAwait(false); + } + + /// Changes name, e-mail, flags and state of a user. + /// Who acts. + /// The company. + /// The user. + /// The name. + /// The e-mail. + /// The flags. + /// Whether it can sign in. + /// Cancellation. + /// A task. + public async Task UpdateAsync( + Actor actor, string companyCode, long userId, string displayName, string? email, UserFlags flags, bool isActive, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(flags); + ArgumentException.ThrowIfNullOrWhiteSpace(displayName); + await ChangeAsync(actor, companyCode, userId, "user.updated", user => + { + user.DisplayName = displayName.Trim(); + user.Email = string.IsNullOrWhiteSpace(email) ? null : email.Trim(); + user.OwnCustomersOnly = flags.OwnCustomersOnly; + user.CanSeeCosts = flags.CanSeeCosts; + user.CanExport = flags.CanExport; + user.CanUseApi = user.Kind == UserKind.Technical || flags.CanUseApi; + user.IsActive = isActive; + }, cancellationToken).ConfigureAwait(false); + } + + /// Gives a user a new temporary password. + /// Who acts. + /// The company. + /// The user. + /// Cancellation. + /// The temporary password. + public async Task ResetPasswordAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default) + { + string? password = null; + await ChangeAsync(actor, companyCode, userId, "user.password-reset", user => + { + if (user.Kind == UserKind.Technical) + { + throw new ValidationFailedException(["technical_user_has_no_password"]); + } + + password = security.IssueTemporaryPassword(user); + }, cancellationToken).ConfigureAwait(false); + return password!; + } + + /// Turns off the two-step verification of a user who lost the phone. + /// Who acts. + /// The company. + /// The user. + /// Cancellation. + /// A task. + public Task ResetTotpAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default) => + ChangeAsync(actor, companyCode, userId, "user.totp-reset", AccountSecurity.ResetTotp, cancellationToken); + + /// Saves a user changed by the sign-in flow. + /// The company. + /// The user. + /// Cancellation. + /// A task. + public async Task SaveAsync(string companyCode, CompanyUser user, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(user); + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await unitOfWork.Repository().UpdateAsync(user, cancellationToken).ConfigureAwait(false); + } + + private async Task ChangeAsync(Actor actor, string companyCode, long userId, string action, Action change, CancellationToken cancellationToken) + { + await roles.DemandManageAsync(actor, companyCode, cancellationToken).ConfigureAwait(false); + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var users = unitOfWork.Repository(); + var user = await users.GetAsync(userId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException("No user has this identifier."); + change(user); + await users.UpdateAsync(user, cancellationToken).ConfigureAwait(false); + await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false); + await audit.WriteAsync(new SecurityEvent(action, actor.UserName, companyCode, user.UserName), cancellationToken).ConfigureAwait(false); + } + + private async Task AssignRolesAsync(IUnitOfWork unitOfWork, Actor actor, long userId, IReadOnlyList roleCodes, CancellationToken cancellationToken) + { + var codes = roleCodes.Select(r => r.Trim().ToUpperInvariant()).Distinct(StringComparer.Ordinal).ToArray(); + var found = codes.Length == 0 + ? [] + : (await unitOfWork.Repository().ListAsync(Query.For().Where(r => codes.Contains(r.Code)), cancellationToken).ConfigureAwait(false)).Items; + if (found.Count != codes.Length) + { + throw new ValidationFailedException(["role_unknown"]); + } + + var roleIds = found.Select(r => r.Id).ToArray(); + var patterns = roleIds.Length == 0 + ? [] + : (await unitOfWork.Repository().ListAsync(Query.For().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items + .Select(g => g.Permission); + if (!await permissions.CoversAsync(actor, patterns, cancellationToken).ConfigureAwait(false)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A user cannot assign roles above its own permissions."); + } + + var userRoles = unitOfWork.Repository(); + foreach (var old in (await userRoles.ListAsync(Query.For().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items) + { + await userRoles.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false); + } + + foreach (var roleId in roleIds) + { + await userRoles.InsertAsync(new UserRole { UserId = userId, RoleId = roleId }, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Khaemhat.Core/Caching/ICacheProvider.cs b/src/Khaemhat.Core/Caching/ICacheProvider.cs new file mode 100644 index 0000000..dc289e7 --- /dev/null +++ b/src/Khaemhat.Core/Caching/ICacheProvider.cs @@ -0,0 +1,80 @@ +namespace Khaemhat.Core.Caching; + +/// +/// The application cache (SPEC §9): in memory, or Redis when KHAEMHAT_REDIS is set. Values are stored as JSON +/// in both cases, so the behaviour is the same with and without Redis. Keys follow . +/// +public interface ICacheProvider +{ + /// Whether the cache is shared between instances (Redis reachable). + bool IsDistributed { get; } + + /// Reads a value. + /// The value type. + /// The key. + /// Cancellation. + /// The value, or when missing or expired. + ValueTask GetAsync(string key, CancellationToken cancellationToken = default); + + /// Stores a value. + /// The value type. + /// The key. + /// The value. + /// How long it stays. + /// Cancellation. + /// A task. + ValueTask SetAsync(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default); + + /// Removes a value. + /// The key. + /// Cancellation. + /// A task. + ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default); + + /// Removes every key that starts with . + /// The prefix, for example kh:DEMO:permissions:. + /// Cancellation. + /// A task. + ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default); + + /// Reads a value, or creates and stores it. + /// The value type. + /// The key. + /// Creates the value when missing. + /// How long it stays. + /// Cancellation. + /// The value. + ValueTask GetOrCreateAsync(string key, Func> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default); + + /// + /// Removes the keys with here and tells the other instances to do the same (Redis pub/sub). + /// + /// The prefix. + /// Cancellation. + /// A task. + ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default); +} + +/// Cache keys: kh:{company}:{area}:{key}, with _ for the instance (SPEC §9). +public static class CacheKeys +{ + /// The instance scope. + public const string Instance = "_"; + + /// A key. + /// The company code, or for the instance. + /// The area, for example permissions. + /// The key inside the area. + /// The full key. + public static string For(string? company, string area, string key) => Prefix(company, area) + key; + + /// The prefix of an area, for . + /// The company code, or for the instance. + /// The area. + /// The prefix, ending with a colon. + public static string Prefix(string? company, string area) + { + ArgumentException.ThrowIfNullOrWhiteSpace(area); + return "kh:" + (string.IsNullOrEmpty(company) ? Instance : company) + ":" + area + ":"; + } +} diff --git a/src/Khaemhat.Core/Instance/InstanceRecords.cs b/src/Khaemhat.Core/Instance/InstanceRecords.cs new file mode 100644 index 0000000..84c5518 --- /dev/null +++ b/src/Khaemhat.Core/Instance/InstanceRecords.cs @@ -0,0 +1,349 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Instance; + +/// Where an installed licence comes from. +public enum LicenseSource +{ + /// A signed .khl instance licence. + File = 0, + + /// A signed activation code for one module. + ActivationCode = 1, + + /// A fictitious code of SPEC §8.3, accepted only in test mode. + TestCode = 2, +} + +/// An installed licence or activation code (sys_licenses). +public sealed class LicenseRecord : Entity +{ + /// Where the licence comes from. + public LicenseSource Source { get; set; } + + /// The licence text (.khl content or code), as installed. + public string Payload { get; set; } = string.Empty; + + /// The licence holder. + public string? Licensee { get; set; } + + /// The module codes, comma separated. + public string Modules { get; set; } = string.Empty; + + /// Concurrent users granted (0 = not stated by this licence). + public int MaxConcurrentUsers { get; set; } + + /// Companies granted (0 = not stated by this licence). + public int MaxCompanies { get; set; } + + /// When the licence was issued. + public DateTime? IssuedAt { get; set; } + + /// When the licence expires; for no expiry. + public DateTime? ExpiresAt { get; set; } + + /// Days of full use after the expiry. + public int GracePeriodDays { get; set; } + + /// Whether the licence counts (a removed licence stays for the history). + public bool IsActive { get; set; } = true; +} + +/// One step in the history of licences (sys_license_activations). +public sealed class LicenseActivation : Entity +{ + /// What happened: activated, deactivated, rejected, verified, expired. + public string Action { get; set; } = string.Empty; + + /// The licence source. + public LicenseSource Source { get; set; } + + /// The modules concerned, comma separated. + public string? Modules { get; set; } + + /// The outcome code, for example ok, license_test_only, signature_invalid. + public string Outcome { get; set; } = string.Empty; + + /// A short explanation. + public string? Message { get; set; } +} + +/// An ASP.NET Core DataProtection key kept in the system database (sys_data_protection_keys). +public sealed class DataProtectionKey : Entity +{ + /// The key name given by DataProtection. + public string FriendlyName { get; set; } = string.Empty; + + /// The key XML. The key material inside is encrypted with the instance key. + public string Xml { get; set; } = string.Empty; +} + +/// One event of the application log (sys_log, SPEC §9.5). +public sealed class LogEntry : IEntity +{ + /// + public long Id { get; set; } + + /// When the event happened (UTC). + public DateTime At { get; set; } + + /// The level: Trace, Debug, Information, Warning, Error, Critical. + public string Level { get; set; } = string.Empty; + + /// The section (SPEC §9.5), for example Authentication. + public string Section { get; set; } = string.Empty; + + /// The logger category. + public string Source { get; set; } = string.Empty; + + /// The message. + public string Message { get; set; } = string.Empty; + + /// The exception with its stack, if any. + public string? Exception { get; set; } + + /// The user name. + public string? UserName { get; set; } + + /// The company code. + public string? CompanyCode { get; set; } + + /// The trace identifier shown to the user as the error code. + public string? TraceId { get; set; } + + /// The request (method and path). + public string? Request { get; set; } + + /// The entity concerned. + public string? Entity { get; set; } + + /// The identifier of the entity concerned. + public string? EntityId { get; set; } + + /// Further structured data as JSON. + public string? Data { get; set; } +} + +/// +/// A security or instance action (sys_security_audit): sign-ins, permissions, licences, databases, maintenance. +/// Rows are never updated; each one carries the hash of the previous row, so a removed or changed row breaks the chain. +/// +public sealed class SecurityAuditEntry : IEntity +{ + /// + public long Id { get; set; } + + /// When it happened (UTC). + public DateTime At { get; set; } + + /// The action code, for example login.succeeded. + public string Action { get; set; } = string.Empty; + + /// Who acted. + public string? UserName { get; set; } + + /// The company concerned. + public string? CompanyCode { get; set; } + + /// The client address. + public string? IpAddress { get; set; } + + /// What the action was about (a user, a module, a database...). + public string? Target { get; set; } + + /// Details as JSON (never secrets). + public string? Details { get; set; } + + /// The hash of the previous row (empty for the first). + public string PreviousHash { get; set; } = string.Empty; + + /// SHA-256 of this row's content and . + public string Hash { get; set; } = string.Empty; +} + +/// A change to company data (audit_log, SPEC §7.3), shown in the "Storico" of a record. +public sealed class AuditEntry : IEntity +{ + /// + public long Id { get; set; } + + /// When it happened (UTC). + public DateTime At { get; set; } + + /// The entity (table) changed. + public string Entity { get; set; } = string.Empty; + + /// The identifier of the record. + public string EntityId { get; set; } = string.Empty; + + /// insert, update or delete. + public string Action { get; set; } = string.Empty; + + /// Who changed it. + public string? UserName { get; set; } + + /// The changed fields as JSON: {"field": {"old": ..., "new": ...}}. + public string? Diff { get; set; } + + /// The trace of the request that made the change. + public string? TraceId { get; set; } +} + +/// The outcome of a job run. +public enum JobOutcome +{ + /// Still running. + Running = 0, + + /// Completed. + Succeeded = 1, + + /// Failed after the retries. + Failed = 2, + + /// Stopped by the timeout. + TimedOut = 3, + + /// Not started because another run held the lock. + Skipped = 4, +} + +/// A scheduled task (sys_scheduled_tasks): a system job or an activity set up by administrators. +public sealed class ScheduledTask : Entity +{ + /// The task code, unique, for example system.log-retention. + public string Code { get; set; } = string.Empty; + + /// The name shown in the interface. + public string Name { get; set; } = string.Empty; + + /// The job type that runs it. + public string JobType { get; set; } = string.Empty; + + /// The company it works on; for the instance. + public string? CompanyCode { get; set; } + + /// The cron expression (five fields). + public string Cron { get; set; } = string.Empty; + + /// The time zone of the cron expression (IANA name). + public string TimeZone { get; set; } = "Europe/Rome"; + + /// The longest a run may last, in seconds. + public int TimeoutSeconds { get; set; } = 600; + + /// How many times a failed run is retried. + public int MaxRetries { get; set; } + + /// Whether the task runs. + public bool IsEnabled { get; set; } = true; + + /// A system job, which administrators can suspend but not delete. + public bool IsSystem { get; set; } + + /// The parameters as JSON. + public string? Parameters { get; set; } + + /// The last start. + public DateTime? LastRunAt { get; set; } + + /// The next planned start. + public DateTime? NextRunAt { get; set; } + + /// The outcome of the last run. + public JobOutcome? LastOutcome { get; set; } +} + +/// One run of a scheduled task (sys_job_runs). +public sealed class JobRun : IEntity +{ + /// + public long Id { get; set; } + + /// The task code. + public string TaskCode { get; set; } = string.Empty; + + /// When the run started (UTC). + public DateTime StartedAt { get; set; } + + /// When the run ended. + public DateTime? FinishedAt { get; set; } + + /// The outcome. + public JobOutcome Outcome { get; set; } + + /// The attempt number, from 1. + public int Attempt { get; set; } = 1; + + /// A short result or error message. + public string? Message { get; set; } + + /// The trace identifier of the run, to find its log. + public string? TraceId { get; set; } +} + +/// +/// A lock held by a job run (sys_job_locks): a row per running task, with an expiry so that a process that died +/// does not block the task for ever. +/// +public sealed class JobLock : IEntity +{ + /// The lock key (the task code). + public string Id { get; set; } = string.Empty; + + /// The process that holds the lock. + public string Owner { get; set; } = string.Empty; + + /// When the lock was taken. + public DateTime AcquiredAt { get; set; } + + /// When the lock lapses. + public DateTime ExpiresAt { get; set; } +} + +/// The weight of a notification. +public enum NotificationSeverity +{ + /// Information. + Info = 0, + + /// Something completed. + Success = 1, + + /// Needs attention. + Warning = 2, + + /// Something failed. + Error = 3, +} + +/// An in-app notification (SPEC §9; mockup 010). +public abstract class NotificationRecord : Entity +{ + /// The recipient; for every user of the scope (all administrators, all users). + public long? RecipientUserId { get; set; } + + /// The area: security, jobs, system, licenses... + public string Category { get; set; } = string.Empty; + + /// The weight. + public NotificationSeverity Severity { get; set; } + + /// The title. + public string Title { get; set; } = string.Empty; + + /// The text. + public string? Body { get; set; } + + /// A link inside the application. + public string? Link { get; set; } + + /// When the recipient read it. + public DateTime? ReadAt { get; set; } +} + +/// A notification for instance accounts (sys_notifications). +public sealed class SystemNotification : NotificationRecord; + +/// A notification for company users (notifications). +public sealed class Notification : NotificationRecord; diff --git a/src/Khaemhat.Core/Logging/LogSection.cs b/src/Khaemhat.Core/Logging/LogSection.cs new file mode 100644 index 0000000..106b465 --- /dev/null +++ b/src/Khaemhat.Core/Logging/LogSection.cs @@ -0,0 +1,131 @@ +namespace Khaemhat.Core.Logging; + +/// The sections of the application log (SPEC §9.5; mockup 084). Each module writes to its own. +public enum LogSection +{ + /// Sistema. + System = 0, + + /// Autenticazione. + Authentication = 1, + + /// Database. + Database = 2, + + /// Migrazioni. + Migrations = 3, + + /// Documenti. + Documents = 4, + + /// Contabilità. + Accounting = 5, + + /// Magazzino. + Inventory = 6, + + /// SDI/e-invoicing. + EInvoicing = 7, + + /// CRM. + Crm = 8, + + /// Automazioni. + Automation = 9, + + /// Attività programmate. + ScheduledJobs = 10, + + /// Backup. + Backup = 11, + + /// API/MCP. + Api = 12, + + /// E-mail/PEC. + Email = 13, + + /// Integrazioni (VIES, BCE, intermediari). + Integrations = 14, + + /// UI/circuiti. + Ui = 15, + + /// Prestazioni. + Performance = 16, +} + +/// Names, labels and the scope key of . +public static class LogSections +{ + /// The scope key that carries the section (using (logger.BeginScope(LogSections.Scope(...)))). + public const string ScopeKey = "Section"; + + /// The scope key of the trace identifier. + public const string TraceIdKey = "TraceId"; + + /// The scope key of the user name. + public const string UserKey = "UserName"; + + /// The scope key of the company code. + public const string CompanyKey = "CompanyCode"; + + /// The scope key of the request (method and path). + public const string RequestKey = "Request"; + + /// The scope key of the entity concerned. + public const string EntityKey = "Entity"; + + /// The scope key of the entity identifier. + public const string EntityIdKey = "EntityId"; + + /// The Italian label shown in the log page. + /// The section. + /// The label. + public static string Label(LogSection section) => section switch + { + LogSection.System => "Sistema", + LogSection.Authentication => "Autenticazione", + LogSection.Database => "Database", + LogSection.Migrations => "Migrazioni", + LogSection.Documents => "Documenti", + LogSection.Accounting => "Contabilità", + LogSection.Inventory => "Magazzino", + LogSection.EInvoicing => "SDI/e-invoicing", + LogSection.Crm => "CRM", + LogSection.Automation => "Automazioni", + LogSection.ScheduledJobs => "Attività programmate", + LogSection.Backup => "Backup", + LogSection.Api => "API/MCP", + LogSection.Email => "E-mail/PEC", + LogSection.Integrations => "Integrazioni", + LogSection.Ui => "UI/circuiti", + LogSection.Performance => "Prestazioni", + _ => section.ToString(), + }; + + /// A scope state that sets the section of the events logged inside it. + /// The section. + /// The scope state. + public static IReadOnlyList> Scope(LogSection section) => + [new(ScopeKey, section.ToString())]; + + /// + /// The section of a logger category when no scope sets one: by namespace, so that the framework's own events land in + /// a sensible place. + /// + /// The logger category. + /// The section. + public static LogSection FromCategory(string? category) => category switch + { + null => LogSection.System, + _ when category.Contains(".Security", StringComparison.Ordinal) || category.Contains("Authentication", StringComparison.Ordinal) + || category.Contains("Authorization", StringComparison.Ordinal) || category.Contains("Antiforgery", StringComparison.Ordinal) => LogSection.Authentication, + _ when category.Contains("Migration", StringComparison.Ordinal) => LogSection.Migrations, + _ when category.StartsWith("Khaemhat.Data", StringComparison.Ordinal) => LogSection.Database, + _ when category.Contains(".Jobs", StringComparison.Ordinal) => LogSection.ScheduledJobs, + _ when category.StartsWith("Microsoft.AspNetCore.Components", StringComparison.Ordinal) => LogSection.Ui, + _ when category.Contains("SlowQuer", StringComparison.Ordinal) || category.Contains("Performance", StringComparison.Ordinal) => LogSection.Performance, + _ => LogSection.System, + }; +} diff --git a/src/Khaemhat.Core/Scheduling/CronExpression.cs b/src/Khaemhat.Core/Scheduling/CronExpression.cs new file mode 100644 index 0000000..95709c6 --- /dev/null +++ b/src/Khaemhat.Core/Scheduling/CronExpression.cs @@ -0,0 +1,203 @@ +using System.Globalization; + +namespace Khaemhat.Core.Scheduling; + +/// +/// A five-field cron expression (minute hour day-of-month month day-of-week) for scheduled tasks (SPEC §9.4): +/// *, lists (1,15), ranges (1-5), steps (*/10, 8-18/2); day of week 0-7 with 0 and 7 +/// for Sunday. As in classic cron, when both day fields are restricted a day matches either. Times are computed in the +/// task's time zone, so "every day at 02:30" stays at 02:30 across daylight saving changes (a skipped local time is +/// skipped that day). +/// +public sealed class CronExpression +{ + private readonly bool[] _minutes = new bool[60]; + private readonly bool[] _hours = new bool[24]; + private readonly bool[] _days = new bool[32]; + private readonly bool[] _months = new bool[13]; + private readonly bool[] _weekDays = new bool[7]; + private readonly bool _anyDay; + private readonly bool _anyWeekDay; + + private CronExpression(string text, string[] fields) + { + Text = text; + Fill(fields[0], 0, 59, _minutes); + Fill(fields[1], 0, 23, _hours); + _anyDay = Fill(fields[2], 1, 31, _days); + Fill(fields[3], 1, 12, _months); + var weekDays = new bool[8]; + _anyWeekDay = Fill(fields[4], 0, 7, weekDays); + for (var i = 0; i < 7; i++) + { + _weekDays[i] = weekDays[i] || (i == 0 && weekDays[7]); + } + } + + /// The expression as written. + public string Text { get; } + + /// Parses an expression. + /// The expression. + /// The parsed expression. + /// The expression is not valid. + public static CronExpression Parse(string text) => + TryParse(text, out var result, out var error) ? result : throw new FormatException(error); + + /// Tries to parse an expression. + /// The expression. + /// The parsed expression. + /// Why it is not valid. + /// when valid. + public static bool TryParse(string? text, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out CronExpression? result, out string? error) + { + result = null; + var fields = (text ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (fields.Length != 5) + { + error = "A cron expression has five fields: minute hour day-of-month month day-of-week."; + return false; + } + + try + { + result = new CronExpression(string.Join(' ', fields), fields); + error = null; + return true; + } + catch (FormatException ex) + { + error = ex.Message; + return false; + } + } + + /// The first occurrence strictly after a moment. + /// The moment (UTC). + /// The time zone of the schedule. + /// The next occurrence in UTC, or when none exists in the next five years. + public DateTime? NextAfter(DateTime afterUtc, TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(zone); + var utc = DateTime.SpecifyKind(afterUtc, DateTimeKind.Utc); + var local = TimeZoneInfo.ConvertTimeFromUtc(utc, zone); + var candidate = new DateTime(local.Year, local.Month, local.Day, local.Hour, local.Minute, 0, DateTimeKind.Unspecified).AddMinutes(1); + var limit = candidate.AddYears(5); + while (candidate < limit) + { + if (!_months[candidate.Month]) + { + candidate = new DateTime(candidate.Year, candidate.Month, 1, 0, 0, 0, DateTimeKind.Unspecified).AddMonths(1); + continue; + } + + if (!DayMatches(candidate)) + { + candidate = candidate.Date.AddDays(1); + continue; + } + + if (!_hours[candidate.Hour]) + { + candidate = candidate.Date.AddHours(candidate.Hour + 1); + continue; + } + + if (!_minutes[candidate.Minute]) + { + candidate = candidate.AddMinutes(1); + continue; + } + + if (zone.IsInvalidTime(candidate)) + { + candidate = candidate.AddMinutes(1); + continue; + } + + var result = TimeZoneInfo.ConvertTimeToUtc(candidate, zone); + if (result > utc) + { + return result; + } + + candidate = candidate.AddMinutes(1); + } + + return null; + } + + /// + public override string ToString() => Text; + + private bool DayMatches(DateTime date) + { + var day = _days[date.Day]; + var weekDay = _weekDays[(int)date.DayOfWeek]; + return (_anyDay, _anyWeekDay) switch + { + (true, true) => true, + (true, false) => weekDay, + (false, true) => day, + _ => day || weekDay, + }; + } + + // Fills the allowed values of a field; returns true when the field is "*". + private static bool Fill(string field, int min, int max, bool[] allowed) + { + if (field == "*") + { + for (var i = min; i <= max; i++) + { + allowed[i] = true; + } + + return true; + } + + foreach (var part in field.Split(',')) + { + var step = 1; + var range = part; + var slash = part.IndexOf('/', StringComparison.Ordinal); + if (slash >= 0) + { + step = Number(part[(slash + 1)..], 1, max, part); + range = part[..slash]; + } + + int from, to; + if (range == "*") + { + (from, to) = (min, max); + } + else if (range.IndexOf('-', StringComparison.Ordinal) is var dash and > 0) + { + from = Number(range[..dash], min, max, part); + to = Number(range[(dash + 1)..], min, max, part); + if (to < from) + { + throw new FormatException($"The range '{part}' goes backwards."); + } + } + else + { + from = Number(range, min, max, part); + to = slash >= 0 ? max : from; + } + + for (var i = from; i <= to; i += step) + { + allowed[i] = true; + } + } + + return false; + } + + private static int Number(string text, int min, int max, string part) => + int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value >= min && value <= max + ? value + : throw new FormatException($"'{part}' is not valid: values go from {min} to {max}."); +} diff --git a/src/Khaemhat.Core/Security/Accounts.cs b/src/Khaemhat.Core/Security/Accounts.cs new file mode 100644 index 0000000..21a8964 --- /dev/null +++ b/src/Khaemhat.Core/Security/Accounts.cs @@ -0,0 +1,237 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Security; + +/// +/// The three access levels of SPEC §7.1, ordered: a higher value can do everything a lower one can. +/// rows hold or ; company users are +/// . +/// +public enum UserLevel +{ + /// A company user, limited by the permissions of the roles. + Standard = 0, + + /// An instance administrator, created by the super user. + Administrator = 1, + + /// The only super user, created from the container variables at first start. + SuperUser = 2, +} + +/// The kind of a company user. +public enum UserKind +{ + /// A person who signs in with a password. + Human = 0, + + /// A technical user for the API: no password, used only through API keys. + Technical = 1, +} + +/// +/// The credential fields shared by instance accounts (sys_users) and company users (users), so that +/// password, lockout, TOTP and recovery rules are written once. +/// +public interface IAccount +{ + /// The identifier. + long Id { get; } + + /// The sign-in name, unique in its database (compared case-insensitively, stored lower-case). + string UserName { get; set; } + + /// The name shown in the interface. + string DisplayName { get; set; } + + /// The e-mail address for recovery and notifications. + string? Email { get; set; } + + /// The password hash (pbkdf2-sha256$...); for technical users. + string? PasswordHash { get; set; } + + /// The previous password hashes, newest first, as a JSON array (policy: no reuse of the last five). + string? PasswordHistory { get; set; } + + /// When the password was last set. + DateTime? PasswordChangedAt { get; set; } + + /// Whether the next sign-in must change the password (first access, temporary password, expiry). + bool MustChangePassword { get; set; } + + /// When a temporary password stops working; for a normal password. + DateTime? TemporaryPasswordExpiresAt { get; set; } + + /// Consecutive failed sign-ins since the last success. + int FailedLoginCount { get; set; } + + /// The account is locked until this moment after too many failures. + DateTime? LockedUntil { get; set; } + + /// The TOTP secret, encrypted with the instance key. + string? TotpSecret { get; set; } + + /// Whether the two-step verification is active. + bool TotpEnabled { get; set; } + + /// The last accepted TOTP time step: a code is never accepted twice. + long? TotpLastStep { get; set; } + + /// The SHA-256 hashes of the unused recovery codes, as a JSON array. + string? TotpRecoveryCodes { get; set; } + + /// The SHA-256 hash of the pending password-recovery token. + string? RecoveryTokenHash { get; set; } + + /// When the recovery token expires. + DateTime? RecoveryTokenExpiresAt { get; set; } + + /// Whether the account can sign in. + bool IsActive { get; set; } + + /// The last successful sign-in. + DateTime? LastLoginAt { get; set; } +} + +/// An instance account (sys_users): the super user or an administrator (SPEC §7.1). +public sealed class SystemUser : Entity, IAccount +{ + /// + public string UserName { get; set; } = string.Empty; + + /// + public string DisplayName { get; set; } = string.Empty; + + /// + public string? Email { get; set; } + + /// or . + public UserLevel Level { get; set; } + + /// + public string? PasswordHash { get; set; } + + /// + public string? PasswordHistory { get; set; } + + /// + public DateTime? PasswordChangedAt { get; set; } + + /// + public bool MustChangePassword { get; set; } + + /// + public DateTime? TemporaryPasswordExpiresAt { get; set; } + + /// + public int FailedLoginCount { get; set; } + + /// + public DateTime? LockedUntil { get; set; } + + /// + public string? TotpSecret { get; set; } + + /// + public bool TotpEnabled { get; set; } + + /// + public long? TotpLastStep { get; set; } + + /// + public string? TotpRecoveryCodes { get; set; } + + /// + public string? RecoveryTokenHash { get; set; } + + /// + public DateTime? RecoveryTokenExpiresAt { get; set; } + + /// + public bool IsActive { get; set; } = true; + + /// + public DateTime? LastLoginAt { get; set; } + + /// The company of the linked user, for an administrator who works as a company user without a second sign-in. + public string? LinkedCompanyCode { get; set; } + + /// The linked company user. + public long? LinkedUserId { get; set; } +} + +/// A company user (users in the company database). +public sealed class CompanyUser : Entity, IAccount +{ + /// + public string UserName { get; set; } = string.Empty; + + /// + public string DisplayName { get; set; } = string.Empty; + + /// + public string? Email { get; set; } + + /// A person or a technical user for the API. + public UserKind Kind { get; set; } + + /// + public string? PasswordHash { get; set; } + + /// + public string? PasswordHistory { get; set; } + + /// + public DateTime? PasswordChangedAt { get; set; } + + /// + public bool MustChangePassword { get; set; } + + /// + public DateTime? TemporaryPasswordExpiresAt { get; set; } + + /// + public int FailedLoginCount { get; set; } + + /// + public DateTime? LockedUntil { get; set; } + + /// + public string? TotpSecret { get; set; } + + /// + public bool TotpEnabled { get; set; } + + /// Whether this user must set up the two-step verification (configurable per user). + public bool TotpRequired { get; set; } + + /// + public long? TotpLastStep { get; set; } + + /// + public string? TotpRecoveryCodes { get; set; } + + /// + public string? RecoveryTokenHash { get; set; } + + /// + public DateTime? RecoveryTokenExpiresAt { get; set; } + + /// + public bool IsActive { get; set; } = true; + + /// + public DateTime? LastLoginAt { get; set; } + + /// Sees only the customers assigned to the user (agents). + public bool OwnCustomersOnly { get; set; } + + /// Sees costs and margins. + public bool CanSeeCosts { get; set; } + + /// Can export lists and reports. + public bool CanExport { get; set; } + + /// Can use the API. + public bool CanUseApi { get; set; } +} diff --git a/src/Khaemhat.Core/Security/Sessions.cs b/src/Khaemhat.Core/Security/Sessions.cs new file mode 100644 index 0000000..f5abe6a --- /dev/null +++ b/src/Khaemhat.Core/Security/Sessions.cs @@ -0,0 +1,136 @@ +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.Security; + +/// How far a sign-in has gone. Only sessions open the application. +public enum SessionState +{ + /// The password was right; the TOTP code is still missing. + PendingTotp = 0, + + /// The two-step verification must be set up before going on (mandatory for instance accounts). + PendingTotpSetup = 1, + + /// The password must be changed before going on. + PendingPasswordChange = 2, + + /// A complete session. + Active = 3, +} + +/// +/// A sign-in session (SPEC §7.3). The cookie carries a random 256-bit token; the table stores only its SHA-256 hash, +/// so a copy of the database does not let anyone in. +/// +public abstract class SessionRecord : Entity +{ + /// The SHA-256 hash of the token, in lower-case hexadecimal. + public string TokenHash { get; set; } = string.Empty; + + /// The account. + public long UserId { get; set; } + + /// The state of the sign-in. + public SessionState State { get; set; } + + /// The company the session works in (chosen at sign-in, changeable by instance accounts). + public string? CompanyCode { get; set; } + + /// The client address. + public string? IpAddress { get; set; } + + /// The browser, as sent by the client (truncated). + public string? UserAgent { get; set; } + + /// Whether the cookie survives the browser ("remember me on this device"). + public bool Persistent { get; set; } + + /// The last request seen (updated at most once a minute). + public DateTime LastSeenAt { get; set; } + + /// When the session expires unless used again (sliding expiry). + public DateTime ExpiresAt { get; set; } + + /// When the session was revoked. + public DateTime? RevokedAt { get; set; } + + /// Why the session was revoked (sign-out, administrator, password change, maintenance...). + public string? RevokedReason { get; set; } +} + +/// A session of an instance account (sys_sessions). +public sealed class SystemSession : SessionRecord; + +/// A session of a company user (user_sessions). +public sealed class UserSession : SessionRecord; + +/// A predefined role kept in the system database and copied into each company (sys_roles_templates). +public sealed class RoleTemplate : Entity +{ + /// The role code, for example ACCOUNTING. + public string Code { get; set; } = string.Empty; + + /// The name shown in the interface. + public string Name { get; set; } = string.Empty; + + /// What the role is for. + public string? Description { get; set; } + + /// The permission codes as a JSON array; * grants every permission. + public string Permissions { get; set; } = "[]"; + + /// The order in lists. + public int SortOrder { get; set; } +} + +/// A role of a company (roles). +public sealed class Role : Entity +{ + /// The role code, unique in the company. + public string Code { get; set; } = string.Empty; + + /// The name shown in the interface. + public string Name { get; set; } = string.Empty; + + /// What the role is for. + public string? Description { get; set; } + + /// A predefined role copied from a template: it can be cloned but not changed. + public bool IsPredefined { get; set; } + + /// The template the role comes from, or the role it was cloned from. + public string? TemplateCode { get; set; } +} + +/// A permission granted by a role (role_permissions). +public sealed class RoleGrant : Entity +{ + /// The role. + public long RoleId { get; set; } + + /// The permission code, or *. + public string Permission { get; set; } = string.Empty; +} + +/// A role assigned to a company user (user_roles). +public sealed class UserRole : Entity +{ + /// The user. + public long UserId { get; set; } + + /// The role. + public long RoleId { get; set; } +} + +/// A permission granted or denied to one user over the roles (user_permission_overrides). Denials win. +public sealed class UserPermissionOverride : Entity +{ + /// The user. + public long UserId { get; set; } + + /// The permission code. + public string Permission { get; set; } = string.Empty; + + /// grants, denies. + public bool Allowed { get; set; } +} diff --git a/src/Khaemhat.Data.Sqlite/SqliteProvider.cs b/src/Khaemhat.Data.Sqlite/SqliteProvider.cs index 0632fd7..ec0a2b9 100644 --- a/src/Khaemhat.Data.Sqlite/SqliteProvider.cs +++ b/src/Khaemhat.Data.Sqlite/SqliteProvider.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Data; using System.Data.Common; using System.Globalization; @@ -11,9 +12,15 @@ namespace Khaemhat.Data.Sqlite; /// foreign_keys=ON and busy_timeout=5000; file databases use journal_mode=WAL. Databases are files /// under KHAEMHAT_DATA_DIR, or in-memory databases shared by the connections of the process (tests). /// +/// +/// An in-memory database disappears with its last connection: opens one that +/// stays open for the life of the process (or until ), so the database lives as long as +/// the instance that created it. +/// public sealed class SqliteProvider : IDbProvider { private const int BusyTimeoutMilliseconds = 5000; + private static readonly ConcurrentDictionary MemoryKeepers = new(StringComparer.Ordinal); /// public DbEngine Engine => DbEngine.Sqlite; @@ -62,6 +69,17 @@ public sealed class SqliteProvider : IDbProvider { if (!IsFile(connectionString)) { + var name = new SqliteConnectionStringBuilder(connectionString).DataSource; + if (!MemoryKeepers.ContainsKey(name)) + { + var keeper = new SqliteConnection(connectionString); + await keeper.OpenAsync(cancellationToken).ConfigureAwait(false); + if (!MemoryKeepers.TryAdd(name, keeper)) + { + await keeper.DisposeAsync().ConfigureAwait(false); + } + } + return; } @@ -76,6 +94,11 @@ public sealed class SqliteProvider : IDbProvider { if (!IsFile(connectionString)) { + if (MemoryKeepers.TryRemove(new SqliteConnectionStringBuilder(connectionString).DataSource, out var keeper)) + { + keeper.Dispose(); + } + return Task.CompletedTask; } diff --git a/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs b/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs new file mode 100644 index 0000000..88cc36e --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/CompanyMaps.cs @@ -0,0 +1,97 @@ +using Khaemhat.Core.Instance; +using Khaemhat.Core.Security; +using Khaemhat.Data.Mapping; +using Khaemhat.Data.SystemDatabase; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to users. +public sealed class CompanyUserMap : EntityMap +{ + /// Creates the map. + public CompanyUserMap() + { + ToTable("users"); + AccountColumns.Configure(this); + } +} + +/// Map of to user_sessions. +public sealed class UserSessionMap : EntityMap +{ + /// Creates the map. + public UserSessionMap() + { + ToTable("user_sessions"); + SessionColumns.Configure(this); + } +} + +/// Map of to roles. +public sealed class RoleMap : EntityMap +{ + /// Creates the map. + public RoleMap() + { + ToTable("roles"); + Map(x => x.Code).MaxLength(50); + Map(x => x.Name).MaxLength(100); + Map(x => x.TemplateCode).MaxLength(50); + } +} + +/// Map of to role_permissions. +public sealed class RoleGrantMap : EntityMap +{ + /// Creates the map. + public RoleGrantMap() + { + ToTable("role_permissions"); + Map(x => x.Permission).MaxLength(100); + } +} + +/// Map of to user_roles. +public sealed class UserRoleMap : EntityMap +{ + /// Creates the map. + public UserRoleMap() => ToTable("user_roles"); +} + +/// Map of to user_permission_overrides. +public sealed class UserPermissionOverrideMap : EntityMap +{ + /// Creates the map. + public UserPermissionOverrideMap() + { + ToTable("user_permission_overrides"); + Map(x => x.Permission).MaxLength(100); + } +} + +/// Map of to audit_log. +public sealed class AuditEntryMap : EntityMap +{ + /// Creates the map. + public AuditEntryMap() + { + ToTable("audit_log"); + Map(x => x.Entity).MaxLength(100); + Map(x => x.EntityId).MaxLength(100); + Map(x => x.Action).MaxLength(20); + Map(x => x.UserName).MaxLength(100); + Map(x => x.Diff).Json(); + Map(x => x.TraceId).MaxLength(64); + } +} + +/// Map of to notifications. +public sealed class NotificationMap : EntityMap +{ + /// Creates the map. + public NotificationMap() + { + ToTable("notifications"); + NotificationColumns.Configure(this); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_001_CreateUsers.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_001_CreateUsers.cs new file mode 100644 index 0000000..de28311 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_001_CreateUsers.cs @@ -0,0 +1,45 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The company users (SPEC §7.1). +[Migration(20261111_001, "create_users")] +public sealed class M20261111_001_CreateUsers : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("users", t => + { + t.Id(); + t.String("user_name", 100).NotNull(); + t.String("display_name", 200).NotNull(); + t.String("email", 254); + t.String("kind", 40).NotNull(); + t.String("password_hash", 200); + t.Json("password_history"); + t.DateTimeUtc("password_changed_at"); + t.Bool("must_change_password").NotNull().Default(false); + t.DateTimeUtc("temporary_password_expires_at"); + t.Int32("failed_login_count").NotNull().Default(0); + t.DateTimeUtc("locked_until"); + t.Text("totp_secret"); + t.Bool("totp_enabled").NotNull().Default(false); + t.Bool("totp_required").NotNull().Default(false); + t.Int64("totp_last_step"); + t.Json("totp_recovery_codes"); + t.String("recovery_token_hash", 64); + t.DateTimeUtc("recovery_token_expires_at"); + t.Bool("is_active").NotNull().Default(true); + t.DateTimeUtc("last_login_at"); + t.Bool("own_customers_only").NotNull().Default(false); + t.Bool("can_see_costs").NotNull().Default(false); + t.Bool("can_export").NotNull().Default(false); + t.Bool("can_use_api").NotNull().Default(false); + t.AuditColumns(); + t.Unique("ux_users_user_name", "user_name"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_002_CreateUserSessions.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_002_CreateUserSessions.cs new file mode 100644 index 0000000..ee79061 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_002_CreateUserSessions.cs @@ -0,0 +1,34 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The sessions of the company users (SPEC §7.3). +[Migration(20261111_002, "create_user_sessions")] +public sealed class M20261111_002_CreateUserSessions : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("user_sessions", t => + { + t.Id(); + t.String("token_hash", 64).NotNull(); + t.Int64("user_id").NotNull(); + t.String("state", 40).NotNull(); + t.String("company_code", 20); + t.String("ip_address", 64); + t.String("user_agent", 400); + t.Bool("persistent").NotNull().Default(false); + t.DateTimeUtc("last_seen_at").NotNull(); + t.DateTimeUtc("expires_at").NotNull(); + t.DateTimeUtc("revoked_at"); + t.String("revoked_reason", 100); + t.AuditColumns(); + t.Unique("ux_user_sessions_token_hash", "token_hash"); + t.Index("ix_user_sessions_user_id", "user_id"); + t.ForeignKey("fk_user_sessions_user", "user_id", "users", ReferentialAction.Cascade); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_003_CreateRoles.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_003_CreateRoles.cs new file mode 100644 index 0000000..e7d245d --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_003_CreateRoles.cs @@ -0,0 +1,58 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// Roles, their permissions, the roles of each user and the per-user overrides (SPEC §7.2). +[Migration(20261111_003, "create_roles")] +public sealed class M20261111_003_CreateRoles : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("roles", t => + { + t.Id(); + t.String("code", 50).NotNull(); + t.String("name", 100).NotNull(); + t.Text("description"); + t.Bool("is_predefined").NotNull().Default(false); + t.String("template_code", 50); + t.AuditColumns(); + t.Unique("ux_roles_code", "code"); + }); + + schema.CreateTable("role_permissions", t => + { + t.Id(); + t.Int64("role_id").NotNull(); + t.String("permission", 100).NotNull(); + t.AuditColumns(); + t.Unique("ux_role_permissions_role_id_permission", "role_id", "permission"); + t.ForeignKey("fk_role_permissions_role", "role_id", "roles", ReferentialAction.Cascade); + }); + + schema.CreateTable("user_roles", t => + { + t.Id(); + t.Int64("user_id").NotNull(); + t.Int64("role_id").NotNull(); + t.AuditColumns(); + t.Unique("ux_user_roles_user_id_role_id", "user_id", "role_id"); + t.ForeignKey("fk_user_roles_user", "user_id", "users", ReferentialAction.Cascade); + t.ForeignKey("fk_user_roles_role", "role_id", "roles", ReferentialAction.Cascade); + }); + + schema.CreateTable("user_permission_overrides", t => + { + t.Id(); + t.Int64("user_id").NotNull(); + t.String("permission", 100).NotNull(); + t.Bool("allowed").NotNull(); + t.AuditColumns(); + t.Unique("ux_user_permission_overrides_user_id_permission", "user_id", "permission"); + t.ForeignKey("fk_user_permission_overrides_user", "user_id", "users", ReferentialAction.Cascade); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_004_CreateAuditLog.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_004_CreateAuditLog.cs new file mode 100644 index 0000000..60c40d1 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_004_CreateAuditLog.cs @@ -0,0 +1,28 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The history of changes to company data (SPEC §7.3). +[Migration(20261111_004, "create_audit_log")] +public sealed class M20261111_004_CreateAuditLog : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("audit_log", t => + { + t.Id(); + t.DateTimeUtc("at").NotNull(); + t.String("entity", 100).NotNull(); + t.String("entity_id", 100).NotNull(); + t.String("action", 20).NotNull(); + t.String("user_name", 100); + t.Json("diff"); + t.String("trace_id", 64); + t.Index("ix_audit_log_entity_entity_id", "entity", "entity_id"); + t.Index("ix_audit_log_at", "at"); + }); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_005_CreateNotifications.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_005_CreateNotifications.cs new file mode 100644 index 0000000..d7b1891 --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261111_005_CreateNotifications.cs @@ -0,0 +1,28 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// The notifications of the company users (SPEC §9). +[Migration(20261111_005, "create_notifications")] +public sealed class M20261111_005_CreateNotifications : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("notifications", t => + { + t.Id(); + t.Int64("recipient_user_id"); + t.String("category", 40).NotNull(); + t.String("severity", 40).NotNull(); + t.String("title", 200).NotNull(); + t.Text("body"); + t.String("link", 400); + t.DateTimeUtc("read_at"); + t.AuditColumns(); + t.Index("ix_notifications_recipient_user_id", "recipient_user_id"); + }); + } +} diff --git a/src/Khaemhat.Data/Execution/DataAccessContext.cs b/src/Khaemhat.Data/Execution/DataAccessContext.cs index 255a0c2..b11e6d9 100644 --- a/src/Khaemhat.Data/Execution/DataAccessContext.cs +++ b/src/Khaemhat.Data/Execution/DataAccessContext.cs @@ -33,6 +33,15 @@ public sealed class DataAccessContext /// The current user name, or . public string? CurrentUser => _currentUser(); + /// Statements slower than this are reported to (SPEC §9.5: 500 ms). + public TimeSpan SlowQueryThreshold { get; init; } = TimeSpan.FromMilliseconds(500); + + /// + /// Receives the statements slower than : the host writes them to the log section + /// Prestazioni. The SQL text carries no values: they are always parameters. + /// + public Action? SlowQueryObserver { get; init; } + /// The current UTC time, truncated to microseconds (the precision of PostgreSQL and of SQLite storage). public DateTime UtcNow => Truncate(Clock.GetUtcNow().UtcDateTime); @@ -41,3 +50,9 @@ public sealed class DataAccessContext /// The truncated timestamp. public static DateTime Truncate(DateTime value) => new(value.Ticks - (value.Ticks % 10), value.Kind); } + +/// A statement that took longer than . +/// The database name. +/// The SQL text (parameters, never values). +/// How long it took. +public sealed record SlowQuery(string Database, string Sql, TimeSpan Duration); diff --git a/src/Khaemhat.Data/Execution/UnitOfWork.cs b/src/Khaemhat.Data/Execution/UnitOfWork.cs index 2e5bedc..5079121 100644 --- a/src/Khaemhat.Data/Execution/UnitOfWork.cs +++ b/src/Khaemhat.Data/Execution/UnitOfWork.cs @@ -218,6 +218,20 @@ public sealed class UnitOfWork : IUnitOfWork string text, IEnumerable parameters, Func> run, CancellationToken cancellationToken) { ObjectDisposedException.ThrowIf(_disposed, this); + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + try + { + return await WriteCoreAsync(text, parameters, run, cancellationToken).ConfigureAwait(false); + } + finally + { + Observe(text, started); + } + } + + private async Task WriteCoreAsync( + string text, IEnumerable parameters, Func> run, CancellationToken cancellationToken) + { if (Transaction is not null) { await using var command = Executor.CreateCommand(Connection, Transaction, text, parameters); @@ -260,9 +274,34 @@ public sealed class UnitOfWork : IUnitOfWork return rows; } - return Transaction is not null - ? await Run(cancellationToken).ConfigureAwait(false) - : await Context.RetryPolicy.ExecuteAsync(Run, Provider.IsTransient, cancellationToken).ConfigureAwait(false); + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + try + { + return Transaction is not null + ? await Run(cancellationToken).ConfigureAwait(false) + : await Context.RetryPolicy.ExecuteAsync(Run, Provider.IsTransient, cancellationToken).ConfigureAwait(false); + } + finally + { + if (Context.SlowQueryObserver is not null) + { + Observe(sql.Render(Dialect).Text, started); + } + } + } + + private void Observe(string text, long started) + { + if (Context.SlowQueryObserver is not { } observer) + { + return; + } + + var elapsed = System.Diagnostics.Stopwatch.GetElapsedTime(started); + if (elapsed >= Context.SlowQueryThreshold) + { + observer(new SlowQuery(Target.DatabaseName, text, elapsed)); + } } private async Task EndTransactionAsync() diff --git a/src/Khaemhat.Data/Mapping/EntityMap.cs b/src/Khaemhat.Data/Mapping/EntityMap.cs index adcfe5b..ce3321f 100644 --- a/src/Khaemhat.Data/Mapping/EntityMap.cs +++ b/src/Khaemhat.Data/Mapping/EntityMap.cs @@ -156,7 +156,7 @@ public abstract class EntityMap : IEntityMap /// The property type. /// The property, for example x => x.Code. /// The column map to configure. - protected ColumnMap Map(Expression> property) + protected internal ColumnMap Map(Expression> property) { if (_columns is not null) { diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_003_CreateSysUsers.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_003_CreateSysUsers.cs new file mode 100644 index 0000000..0dfec5c --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_003_CreateSysUsers.cs @@ -0,0 +1,42 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// The instance accounts (SPEC §7.1): the super user and the administrators. +[Migration(20261111_003, "create_sys_users", Target = MigrationTarget.System)] +public sealed class M20261111_003_CreateSysUsers : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_users", t => + { + t.Id(); + t.String("user_name", 100).NotNull(); + t.String("display_name", 200).NotNull(); + t.String("email", 254); + t.String("level", 40).NotNull(); + t.String("password_hash", 200); + t.Json("password_history"); + t.DateTimeUtc("password_changed_at"); + t.Bool("must_change_password").NotNull().Default(false); + t.DateTimeUtc("temporary_password_expires_at"); + t.Int32("failed_login_count").NotNull().Default(0); + t.DateTimeUtc("locked_until"); + t.Text("totp_secret"); + t.Bool("totp_enabled").NotNull().Default(false); + t.Int64("totp_last_step"); + t.Json("totp_recovery_codes"); + t.String("recovery_token_hash", 64); + t.DateTimeUtc("recovery_token_expires_at"); + t.Bool("is_active").NotNull().Default(true); + t.DateTimeUtc("last_login_at"); + t.String("linked_company_code", 20); + t.Int64("linked_user_id"); + t.AuditColumns(); + t.Unique("ux_sys_users_user_name", "user_name"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_004_CreateSysSessions.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_004_CreateSysSessions.cs new file mode 100644 index 0000000..b23cee1 --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_004_CreateSysSessions.cs @@ -0,0 +1,34 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// The sessions of the instance accounts (SPEC §7.3). +[Migration(20261111_004, "create_sys_sessions", Target = MigrationTarget.System)] +public sealed class M20261111_004_CreateSysSessions : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_sessions", t => + { + t.Id(); + t.String("token_hash", 64).NotNull(); + t.Int64("user_id").NotNull(); + t.String("state", 40).NotNull(); + t.String("company_code", 20); + t.String("ip_address", 64); + t.String("user_agent", 400); + t.Bool("persistent").NotNull().Default(false); + t.DateTimeUtc("last_seen_at").NotNull(); + t.DateTimeUtc("expires_at").NotNull(); + t.DateTimeUtc("revoked_at"); + t.String("revoked_reason", 100); + t.AuditColumns(); + t.Unique("ux_sys_sessions_token_hash", "token_hash"); + t.Index("ix_sys_sessions_user_id", "user_id"); + t.ForeignKey("fk_sys_sessions_user", "user_id", "sys_users", ReferentialAction.Cascade); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_005_CreateSysRolesTemplates.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_005_CreateSysRolesTemplates.cs new file mode 100644 index 0000000..a25615c --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_005_CreateSysRolesTemplates.cs @@ -0,0 +1,26 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// The predefined roles copied into each company (SPEC §7.2). +[Migration(20261111_005, "create_sys_roles_templates", Target = MigrationTarget.System)] +public sealed class M20261111_005_CreateSysRolesTemplates : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_roles_templates", t => + { + t.Id(); + t.String("code", 50).NotNull(); + t.String("name", 100).NotNull(); + t.Text("description"); + t.Json("permissions").NotNull(); + t.Int32("sort_order").NotNull().Default(0); + t.AuditColumns(); + t.Unique("ux_sys_roles_templates_code", "code"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_006_CreateSysLicenses.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_006_CreateSysLicenses.cs new file mode 100644 index 0000000..277167c --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_006_CreateSysLicenses.cs @@ -0,0 +1,41 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// The installed licences and their history (SPEC §8.2). +[Migration(20261111_006, "create_sys_licenses", Target = MigrationTarget.System)] +public sealed class M20261111_006_CreateSysLicenses : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_licenses", t => + { + t.Id(); + t.String("source", 40).NotNull(); + t.Text("payload").NotNull(); + t.String("licensee", 200); + t.String("modules", 400).NotNull(); + t.Int32("max_concurrent_users").NotNull().Default(0); + t.Int32("max_companies").NotNull().Default(0); + t.DateTimeUtc("issued_at"); + t.DateTimeUtc("expires_at"); + t.Int32("grace_period_days").NotNull().Default(0); + t.Bool("is_active").NotNull().Default(true); + t.AuditColumns(); + }); + + schema.CreateTable("sys_license_activations", t => + { + t.Id(); + t.String("action", 40).NotNull(); + t.String("source", 40).NotNull(); + t.String("modules", 400); + t.String("outcome", 60).NotNull(); + t.Text("message"); + t.AuditColumns(); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_007_CreateSysDataProtectionKeys.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_007_CreateSysDataProtectionKeys.cs new file mode 100644 index 0000000..49e2a10 --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_007_CreateSysDataProtectionKeys.cs @@ -0,0 +1,23 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// The DataProtection keys of the cookies and antiforgery tokens (SPEC §5.4). +[Migration(20261111_007, "create_sys_data_protection_keys", Target = MigrationTarget.System)] +public sealed class M20261111_007_CreateSysDataProtectionKeys : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_data_protection_keys", t => + { + t.Id(); + t.String("friendly_name", 200).NotNull(); + t.Text("xml").NotNull(); + t.AuditColumns(); + t.Unique("ux_sys_data_protection_keys_friendly_name", "friendly_name"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_008_CreateSysLog.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_008_CreateSysLog.cs new file mode 100644 index 0000000..67b9ceb --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_008_CreateSysLog.cs @@ -0,0 +1,35 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// The application log by section (SPEC §9.5). +[Migration(20261111_008, "create_sys_log", Target = MigrationTarget.System)] +public sealed class M20261111_008_CreateSysLog : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_log", t => + { + t.Id(); + t.DateTimeUtc("at").NotNull(); + t.String("level", 20).NotNull(); + t.String("section", 40).NotNull(); + t.String("source", 200).NotNull(); + t.Text("message").NotNull(); + t.Text("exception"); + t.String("user_name", 100); + t.String("company_code", 20); + t.String("trace_id", 64); + t.String("request", 400); + t.String("entity", 100); + t.String("entity_id", 100); + t.Json("data"); + t.Index("ix_sys_log_at", "at"); + t.Index("ix_sys_log_section_at", "section", "at"); + t.Index("ix_sys_log_trace_id", "trace_id"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_009_CreateSysSecurityAudit.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_009_CreateSysSecurityAudit.cs new file mode 100644 index 0000000..b74c5ff --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_009_CreateSysSecurityAudit.cs @@ -0,0 +1,29 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// The immutable, hash-chained audit of security and instance actions (SPEC §7.3). +[Migration(20261111_009, "create_sys_security_audit", Target = MigrationTarget.System)] +public sealed class M20261111_009_CreateSysSecurityAudit : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_security_audit", t => + { + t.Id(); + t.DateTimeUtc("at").NotNull(); + t.String("action", 100).NotNull(); + t.String("user_name", 100); + t.String("company_code", 20); + t.String("ip_address", 64); + t.String("target", 200); + t.Json("details"); + t.String("previous_hash", 64).NotNull(); + t.String("hash", 64).NotNull(); + t.Index("ix_sys_security_audit_at", "at"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_010_CreateSysScheduler.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_010_CreateSysScheduler.cs new file mode 100644 index 0000000..ce721c0 --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_010_CreateSysScheduler.cs @@ -0,0 +1,57 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// Scheduled tasks, their runs and the locks that keep a task from running twice (SPEC §9). +[Migration(20261111_010, "create_sys_scheduler", Target = MigrationTarget.System)] +public sealed class M20261111_010_CreateSysScheduler : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_scheduled_tasks", t => + { + t.Id(); + t.String("code", 100).NotNull(); + t.String("name", 200).NotNull(); + t.String("job_type", 100).NotNull(); + t.String("company_code", 20); + t.String("cron", 100).NotNull(); + t.String("time_zone", 64).NotNull(); + t.Int32("timeout_seconds").NotNull().Default(600); + t.Int32("max_retries").NotNull().Default(0); + t.Bool("is_enabled").NotNull().Default(true); + t.Bool("is_system").NotNull().Default(false); + t.Json("parameters"); + t.DateTimeUtc("last_run_at"); + t.DateTimeUtc("next_run_at"); + t.String("last_outcome", 40); + t.AuditColumns(); + t.Unique("ux_sys_scheduled_tasks_code", "code"); + }); + + schema.CreateTable("sys_job_runs", t => + { + t.Id(); + t.String("task_code", 100).NotNull(); + t.DateTimeUtc("started_at").NotNull(); + t.DateTimeUtc("finished_at"); + t.String("outcome", 40).NotNull(); + t.Int32("attempt").NotNull().Default(1); + t.Text("message"); + t.String("trace_id", 64); + t.Index("ix_sys_job_runs_task_code_started_at", "task_code", "started_at"); + }); + + schema.CreateTable("sys_job_locks", t => + { + t.String("id", 100).NotNull(); + t.String("owner", 100).NotNull(); + t.DateTimeUtc("acquired_at").NotNull(); + t.DateTimeUtc("expires_at").NotNull(); + t.PrimaryKey("id"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_011_CreateSysNotifications.cs b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_011_CreateSysNotifications.cs new file mode 100644 index 0000000..b691a70 --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/Migrations/M20261111_011_CreateSysNotifications.cs @@ -0,0 +1,28 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.SystemDatabase.Migrations; + +/// The notifications of the instance accounts (SPEC §9). +[Migration(20261111_011, "create_sys_notifications", Target = MigrationTarget.System)] +public sealed class M20261111_011_CreateSysNotifications : IMigration +{ + /// + public void Up(ISchemaBuilder schema) + { + ArgumentNullException.ThrowIfNull(schema); + schema.CreateTable("sys_notifications", t => + { + t.Id(); + t.Int64("recipient_user_id"); + t.String("category", 40).NotNull(); + t.String("severity", 40).NotNull(); + t.String("title", 200).NotNull(); + t.Text("body"); + t.String("link", 400); + t.DateTimeUtc("read_at"); + t.AuditColumns(); + t.Index("ix_sys_notifications_recipient_user_id", "recipient_user_id"); + }); + } +} diff --git a/src/Khaemhat.Data/SystemDatabase/SecurityMaps.cs b/src/Khaemhat.Data/SystemDatabase/SecurityMaps.cs new file mode 100644 index 0000000..4f80b64 --- /dev/null +++ b/src/Khaemhat.Data/SystemDatabase/SecurityMaps.cs @@ -0,0 +1,210 @@ +using Khaemhat.Core.Instance; +using Khaemhat.Core.Security; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.SystemDatabase; + +/// The account columns shared by sys_users and users. +internal static class AccountColumns +{ + public static void Configure(EntityMap map) + where T : class, IAccount, new() + { + map.Map(x => x.UserName).MaxLength(100); + map.Map(x => x.DisplayName).MaxLength(200); + map.Map(x => x.Email).MaxLength(254); + map.Map(x => x.PasswordHash).MaxLength(200); + map.Map(x => x.PasswordHistory).Json(); + map.Map(x => x.TotpRecoveryCodes).Json(); + map.Map(x => x.RecoveryTokenHash).MaxLength(64); + } +} + +/// Map of to sys_users. +public sealed class SystemUserMap : EntityMap +{ + /// Creates the map. + public SystemUserMap() + { + ToTable("sys_users"); + AccountColumns.Configure(this); + Map(x => x.LinkedCompanyCode).MaxLength(20); + } +} + +/// Map of to sys_sessions. +public sealed class SystemSessionMap : EntityMap +{ + /// Creates the map. + public SystemSessionMap() + { + ToTable("sys_sessions"); + SessionColumns.Configure(this); + } +} + +/// The session columns shared by sys_sessions and user_sessions. +internal static class SessionColumns +{ + public static void Configure(EntityMap map) + where T : SessionRecord, new() + { + map.Map(x => x.TokenHash).MaxLength(64); + map.Map(x => x.CompanyCode).MaxLength(20); + map.Map(x => x.IpAddress).MaxLength(64); + map.Map(x => x.UserAgent).MaxLength(400); + map.Map(x => x.RevokedReason).MaxLength(100); + } +} + +/// Map of to sys_roles_templates. +public sealed class RoleTemplateMap : EntityMap +{ + /// Creates the map. + public RoleTemplateMap() + { + ToTable("sys_roles_templates"); + Map(x => x.Code).MaxLength(50); + Map(x => x.Name).MaxLength(100); + Map(x => x.Permissions).Json(); + } +} + +/// Map of to sys_licenses. +public sealed class LicenseRecordMap : EntityMap +{ + /// Creates the map. + public LicenseRecordMap() + { + ToTable("sys_licenses"); + Map(x => x.Licensee).MaxLength(200); + Map(x => x.Modules).MaxLength(400); + } +} + +/// Map of to sys_license_activations. +public sealed class LicenseActivationMap : EntityMap +{ + /// Creates the map. + public LicenseActivationMap() + { + ToTable("sys_license_activations"); + Map(x => x.Action).MaxLength(40); + Map(x => x.Modules).MaxLength(400); + Map(x => x.Outcome).MaxLength(60); + } +} + +/// Map of to sys_data_protection_keys. +public sealed class DataProtectionKeyMap : EntityMap +{ + /// Creates the map. + public DataProtectionKeyMap() + { + ToTable("sys_data_protection_keys"); + Map(x => x.FriendlyName).MaxLength(200); + } +} + +/// Map of to sys_log. +public sealed class LogEntryMap : EntityMap +{ + /// Creates the map. + public LogEntryMap() + { + ToTable("sys_log"); + Map(x => x.Level).MaxLength(20); + Map(x => x.Section).MaxLength(40); + Map(x => x.Source).MaxLength(200); + Map(x => x.UserName).MaxLength(100); + Map(x => x.CompanyCode).MaxLength(20); + Map(x => x.TraceId).MaxLength(64); + Map(x => x.Request).MaxLength(400); + Map(x => x.Entity).MaxLength(100); + Map(x => x.EntityId).MaxLength(100); + Map(x => x.Data).Json(); + } +} + +/// Map of to sys_security_audit. +public sealed class SecurityAuditEntryMap : EntityMap +{ + /// Creates the map. + public SecurityAuditEntryMap() + { + ToTable("sys_security_audit"); + Map(x => x.Action).MaxLength(100); + Map(x => x.UserName).MaxLength(100); + Map(x => x.CompanyCode).MaxLength(20); + Map(x => x.IpAddress).MaxLength(64); + Map(x => x.Target).MaxLength(200); + Map(x => x.Details).Json(); + Map(x => x.PreviousHash).MaxLength(64); + Map(x => x.Hash).MaxLength(64); + } +} + +/// Map of to sys_scheduled_tasks. +public sealed class ScheduledTaskMap : EntityMap +{ + /// Creates the map. + public ScheduledTaskMap() + { + ToTable("sys_scheduled_tasks"); + Map(x => x.Code).MaxLength(100); + Map(x => x.Name).MaxLength(200); + Map(x => x.JobType).MaxLength(100); + Map(x => x.CompanyCode).MaxLength(20); + Map(x => x.Cron).MaxLength(100); + Map(x => x.TimeZone).MaxLength(64); + Map(x => x.Parameters).Json(); + } +} + +/// Map of to sys_job_runs. +public sealed class JobRunMap : EntityMap +{ + /// Creates the map. + public JobRunMap() + { + ToTable("sys_job_runs"); + Map(x => x.TaskCode).MaxLength(100); + Map(x => x.TraceId).MaxLength(64); + } +} + +/// Map of to sys_job_locks. +public sealed class JobLockMap : EntityMap +{ + /// Creates the map. + public JobLockMap() + { + ToTable("sys_job_locks"); + HasKey(x => x.Id, identity: false); + Map(x => x.Id).MaxLength(100); + Map(x => x.Owner).MaxLength(100); + } +} + +/// Map of to sys_notifications. +public sealed class SystemNotificationMap : EntityMap +{ + /// Creates the map. + public SystemNotificationMap() + { + ToTable("sys_notifications"); + NotificationColumns.Configure(this); + } +} + +/// The notification columns shared by sys_notifications and notifications. +internal static class NotificationColumns +{ + public static void Configure(EntityMap map) + where T : NotificationRecord, new() + { + map.Map(x => x.Category).MaxLength(40); + map.Map(x => x.Title).MaxLength(200); + map.Map(x => x.Link).MaxLength(400); + } +} diff --git a/src/Khaemhat.Infrastructure/Caching/MemoryCacheProvider.cs b/src/Khaemhat.Infrastructure/Caching/MemoryCacheProvider.cs new file mode 100644 index 0000000..c2287fb --- /dev/null +++ b/src/Khaemhat.Infrastructure/Caching/MemoryCacheProvider.cs @@ -0,0 +1,128 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using Khaemhat.Core.Caching; + +namespace Khaemhat.Infrastructure.Caching; + +/// +/// The in-memory cache of a single instance. Values are kept as JSON, like in Redis, so a cached object is never shared +/// by reference between callers. Expired entries are removed when read and by a sweep every few hundred writes. +/// +/// The clock. +public sealed class MemoryCacheProvider(TimeProvider clock) : ICacheProvider +{ + private const int SweepEvery = 512; + private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); + private int _writes; + + /// Creates a cache on the system clock. + public MemoryCacheProvider() + : this(TimeProvider.System) + { + } + + /// + public bool IsDistributed => false; + + /// The number of entries, expired ones included until swept. + public int Count => _entries.Count; + + /// + public ValueTask GetAsync(string key, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(key); + if (_entries.TryGetValue(key, out var entry)) + { + if (entry.ExpiresAt > clock.GetUtcNow()) + { + return ValueTask.FromResult(JsonSerializer.Deserialize(entry.Json)); + } + + _entries.TryRemove(new KeyValuePair(key, entry)); + } + + return ValueTask.FromResult(default(T)); + } + + /// Reads the raw JSON of a value (the Redis fallback uses it). + /// The key. + /// The JSON, or . + public byte[]? GetRaw(string key) => + _entries.TryGetValue(key, out var entry) && entry.ExpiresAt > clock.GetUtcNow() ? entry.Json : null; + + /// + public ValueTask SetAsync(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default) + { + SetRaw(key, JsonSerializer.SerializeToUtf8Bytes(value), timeToLive); + return ValueTask.CompletedTask; + } + + /// Stores raw JSON. + /// The key. + /// The JSON. + /// How long it stays. + public void SetRaw(string key, byte[] json, TimeSpan timeToLive) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(json); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(timeToLive, TimeSpan.Zero); + _entries[key] = new Entry(json, clock.GetUtcNow() + timeToLive); + if (Interlocked.Increment(ref _writes) % SweepEvery == 0) + { + Sweep(); + } + } + + /// + public ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(key); + _entries.TryRemove(key, out _); + return ValueTask.CompletedTask; + } + + /// + public ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(prefix); + foreach (var key in _entries.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal))) + { + _entries.TryRemove(key, out _); + } + + return ValueTask.CompletedTask; + } + + /// + public async ValueTask GetOrCreateAsync( + string key, Func> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(factory); + if (GetRaw(key) is { } json) + { + return JsonSerializer.Deserialize(json)!; + } + + var value = await factory(cancellationToken).ConfigureAwait(false); + await SetAsync(key, value, timeToLive, cancellationToken).ConfigureAwait(false); + return value; + } + + /// + public ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default) => + RemoveByPrefixAsync(prefix, cancellationToken); + + /// Removes everything (used when Redis comes back, so stale local values are not served). + public void Clear() => _entries.Clear(); + + private void Sweep() + { + var now = clock.GetUtcNow(); + foreach (var pair in _entries.Where(p => p.Value.ExpiresAt <= now)) + { + _entries.TryRemove(pair); + } + } + + private sealed record Entry(byte[] Json, DateTimeOffset ExpiresAt); +} diff --git a/src/Khaemhat.Infrastructure/Caching/RedisClient.cs b/src/Khaemhat.Infrastructure/Caching/RedisClient.cs new file mode 100644 index 0000000..d618a69 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Caching/RedisClient.cs @@ -0,0 +1,382 @@ +using System.Globalization; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Text.Json; +using Khaemhat.Core.Caching; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Infrastructure.Caching; + +/// +/// Where Redis is (KHAEMHAT_REDIS, SPEC §6): redis://[[user]:password@]host[:6379][/db], or +/// rediss:// for TLS. The password never appears in . +/// +public sealed class RedisEndpoint +{ + private RedisEndpoint(string host, int port, bool tls, string? user, string? password, int database) + { + Host = host; + Port = port; + UseTls = tls; + User = user; + Password = password; + Database = database; + } + + /// The host. + public string Host { get; } + + /// The port. + public int Port { get; } + + /// Whether to use TLS. + public bool UseTls { get; } + + /// The ACL user, if any. + public string? User { get; } + + /// The password, if any. + public string? Password { get; } + + /// The database number. + public int Database { get; } + + /// Parses the URL. + /// The URL. + /// The endpoint. + /// The URL is not valid (the message does not repeat it). + public static RedisEndpoint Parse(string url) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("redis" or "rediss") || string.IsNullOrEmpty(uri.Host)) + { + throw new FormatException("KHAEMHAT_REDIS must be redis://[:password@]host:6379/0 or rediss://."); + } + + string? user = null, password = null; + if (uri.UserInfo.Length > 0) + { + var colon = uri.UserInfo.IndexOf(':', StringComparison.Ordinal); + user = colon < 0 ? null : Uri.UnescapeDataString(uri.UserInfo[..colon]); + password = Uri.UnescapeDataString(colon < 0 ? uri.UserInfo : uri.UserInfo[(colon + 1)..]); + user = string.IsNullOrEmpty(user) ? null : user; + } + + var path = uri.AbsolutePath.Trim('/'); + var database = path.Length == 0 ? 0 : int.TryParse(path, NumberStyles.None, CultureInfo.InvariantCulture, out var db) ? db : throw new FormatException("The Redis database must be a number."); + return new RedisEndpoint(uri.Host, uri.IsDefaultPort ? 6379 : uri.Port, uri.Scheme == "rediss", user, password, database); + } + + /// + public override string ToString() => (UseTls ? "rediss://" : "redis://") + (Password is null ? string.Empty : "***@") + Host + ":" + Port.ToString(CultureInfo.InvariantCulture) + "/" + Database.ToString(CultureInfo.InvariantCulture); +} + +/// +/// A minimal Redis client written in house (SPEC §1.2: no external libraries): one connection, one command at a time, +/// reconnecting after an error. Enough for the cache; pipelining and clustering are not needed. +/// +/// Where Redis is. +public sealed class RedisClient(RedisEndpoint endpoint) : IAsyncDisposable +{ + private readonly SemaphoreSlim _gate = new(1, 1); + private TcpClient? _tcp; + private Stream? _stream; + private BufferedReader? _reader; + + /// The endpoint. + public RedisEndpoint Endpoint { get; } = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); + + /// The time allowed to connect and for each command. + public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(2); + + /// Sends a command and reads its reply. + /// The command and its arguments. + /// The reply. + /// Redis answered with an error. + /// The connection failed. + public Task ExecuteAsync(params IReadOnlyList arguments) => ExecuteAsync(arguments, CancellationToken.None); + + /// Sends a command and reads its reply. + /// The command and its arguments. + /// Cancellation. + /// The reply. + public async Task ExecuteAsync(IReadOnlyList arguments, CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(Timeout); + await _gate.WaitAsync(timeout.Token).ConfigureAwait(false); + try + { + if (_stream is null) + { + await ConnectAsync(timeout.Token).ConfigureAwait(false); + } + + var reply = await SendAsync(arguments, timeout.Token).ConfigureAwait(false); + return reply.Kind == RespKind.Error ? throw new RedisException(reply.Text ?? "Redis error.") : reply; + } + catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException or AuthenticationException) + { + Close(); + if (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested) + { + throw new IOException("Redis did not answer in time.", ex); + } + + throw; + } + finally + { + _gate.Release(); + } + } + + /// + public ValueTask DisposeAsync() + { + Close(); + _gate.Dispose(); + return ValueTask.CompletedTask; + } + + private async Task ConnectAsync(CancellationToken cancellationToken) + { + var tcp = new TcpClient { NoDelay = true }; + try + { + await tcp.ConnectAsync(Endpoint.Host, Endpoint.Port, cancellationToken).ConfigureAwait(false); + Stream stream = tcp.GetStream(); + if (Endpoint.UseTls) + { + var ssl = new SslStream(stream, leaveInnerStreamOpen: false); + await ssl.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = Endpoint.Host }, cancellationToken).ConfigureAwait(false); + stream = ssl; + } + + _tcp = tcp; + _stream = stream; + _reader = new BufferedReader(stream); + } + catch + { + tcp.Dispose(); + throw; + } + + if (Endpoint.Password is not null) + { + var auth = await SendAsync(Endpoint.User is null ? ["AUTH", Endpoint.Password] : ["AUTH", Endpoint.User, Endpoint.Password], cancellationToken).ConfigureAwait(false); + if (auth.Kind == RespKind.Error) + { + Close(); + throw new RedisException("Redis refused the credentials."); + } + } + + if (Endpoint.Database != 0) + { + var select = await SendAsync(["SELECT", Endpoint.Database], cancellationToken).ConfigureAwait(false); + if (select.Kind == RespKind.Error) + { + Close(); + throw new RedisException(select.Text ?? "SELECT failed."); + } + } + } + + private async Task SendAsync(IReadOnlyList arguments, CancellationToken cancellationToken) + { + await _stream!.WriteAsync(Resp.Command(arguments), cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + return await Resp.ReadAsync(_reader!, cancellationToken).ConfigureAwait(false); + } + + private void Close() + { + _stream?.Dispose(); + _tcp?.Dispose(); + _stream = null; + _tcp = null; + _reader = null; + } +} + +/// +/// The shared cache on Redis (SPEC §9.3), for instances that run side by side. Values are JSON with a time to live. +/// When Redis cannot be reached the cache falls back to memory and says so in the log (once a minute): nothing fails +/// because of the cache. +/// +public sealed partial class RedisCacheProvider : ICacheProvider, IAsyncDisposable +{ + private const string InvalidationChannel = "kh:invalidate"; + private readonly RedisClient _client; + private readonly MemoryCacheProvider _fallback; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + private DateTimeOffset _lastWarning = DateTimeOffset.MinValue; + private volatile bool _healthy = true; + + /// Creates the cache. + /// The Redis client. + /// The clock. + /// The log. + public RedisCacheProvider(RedisClient client, TimeProvider clock, ILogger logger) + { + ArgumentNullException.ThrowIfNull(client); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _client = client; + _clock = clock; + _logger = logger; + _fallback = new MemoryCacheProvider(clock); + } + + /// + public bool IsDistributed => _healthy; + + /// + public async ValueTask GetAsync(string key, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(key); + var reply = await TryAsync(["GET", key], cancellationToken).ConfigureAwait(false); + if (reply is null) + { + return await _fallback.GetAsync(key, cancellationToken).ConfigureAwait(false); + } + + return reply.Bytes is { } bytes ? JsonSerializer.Deserialize(bytes) : default; + } + + /// + public async ValueTask SetAsync(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(key); + var json = JsonSerializer.SerializeToUtf8Bytes(value); + var milliseconds = Math.Max(1, (long)timeToLive.TotalMilliseconds); + if (await TryAsync(["SET", key, json, "PX", milliseconds], cancellationToken).ConfigureAwait(false) is null) + { + _fallback.SetRaw(key, json, timeToLive); + } + } + + /// + public async ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(key); + await _fallback.RemoveAsync(key, cancellationToken).ConfigureAwait(false); + await TryAsync(["DEL", key], cancellationToken).ConfigureAwait(false); + } + + /// + public async ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(prefix); + await _fallback.RemoveByPrefixAsync(prefix, cancellationToken).ConfigureAwait(false); + var cursor = "0"; + do + { + var reply = await TryAsync(["SCAN", cursor, "MATCH", EscapePattern(prefix) + "*", "COUNT", 500], cancellationToken).ConfigureAwait(false); + if (reply?.Items is not [var next, { Items: { } keys }]) + { + return; + } + + cursor = next.Text ?? "0"; + if (keys.Count > 0) + { + await TryAsync(["DEL", .. keys.Select(k => (object)k.Bytes!)], cancellationToken).ConfigureAwait(false); + } + } + while (cursor != "0"); + } + + /// + public async ValueTask GetOrCreateAsync(string key, Func> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(factory); + var reply = await TryAsync(["GET", key], cancellationToken).ConfigureAwait(false); + if (reply is null) + { + return await _fallback.GetOrCreateAsync(key, factory, timeToLive, cancellationToken).ConfigureAwait(false); + } + + if (reply.Bytes is { } bytes) + { + return JsonSerializer.Deserialize(bytes)!; + } + + var value = await factory(cancellationToken).ConfigureAwait(false); + await SetAsync(key, value, timeToLive, cancellationToken).ConfigureAwait(false); + return value; + } + + /// + /// Keys live only in Redis, so deleting them is enough; the message lets future local copies follow. + public async ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default) + { + await RemoveByPrefixAsync(prefix, cancellationToken).ConfigureAwait(false); + await TryAsync(["PUBLISH", InvalidationChannel, prefix], cancellationToken).ConfigureAwait(false); + } + + /// Checks the connection (PING), for the start log and the system page. + /// Cancellation. + /// when Redis answered. + public async Task PingAsync(CancellationToken cancellationToken = default) => + (await TryAsync(["PING"], cancellationToken).ConfigureAwait(false))?.Text == "PONG"; + + /// + public ValueTask DisposeAsync() => _client.DisposeAsync(); + + /// Escapes the glob characters of a key prefix for SCAN MATCH. + /// The prefix. + /// The escaped prefix. + public static string EscapePattern(string prefix) + { + ArgumentNullException.ThrowIfNull(prefix); + var builder = new System.Text.StringBuilder(prefix.Length + 8); + foreach (var c in prefix) + { + if (c is '*' or '?' or '[' or ']' or '\\') + { + builder.Append('\\'); + } + + builder.Append(c); + } + + return builder.ToString(); + } + + private async Task TryAsync(IReadOnlyList arguments, CancellationToken cancellationToken) + { + try + { + var reply = await _client.ExecuteAsync(arguments, cancellationToken).ConfigureAwait(false); + if (!_healthy) + { + _healthy = true; + LogRecovered(_logger, _client.Endpoint.ToString()); + } + + return reply; + } + catch (Exception ex) when (ex is IOException or SocketException or RedisException or AuthenticationException) + { + _healthy = false; + var now = _clock.GetUtcNow(); + if (now - _lastWarning > TimeSpan.FromMinutes(1)) + { + _lastWarning = now; + LogUnavailable(_logger, _client.Endpoint.ToString(), ex.Message); + } + + return null; + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Redis {Endpoint} is not available, the cache works in memory: {Reason}")] + private static partial void LogUnavailable(ILogger logger, string endpoint, string reason); + + [LoggerMessage(Level = LogLevel.Information, Message = "Redis {Endpoint} is available again.")] + private static partial void LogRecovered(ILogger logger, string endpoint); +} diff --git a/src/Khaemhat.Infrastructure/Caching/Resp.cs b/src/Khaemhat.Infrastructure/Caching/Resp.cs new file mode 100644 index 0000000..24c5f25 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Caching/Resp.cs @@ -0,0 +1,222 @@ +using System.Buffers; +using System.Globalization; +using System.Text; + +namespace Khaemhat.Infrastructure.Caching; + +/// The kinds of RESP2 replies. +public enum RespKind +{ + /// +OK. + SimpleString = 0, + + /// -ERR .... + Error = 1, + + /// :42. + Number = 2, + + /// $5 hello. + BulkString = 3, + + /// *2 .... + Array = 4, + + /// $-1 or *-1. + Null = 5, +} + +/// A reply of the Redis protocol (RESP2). +/// The kind. +/// The bytes of a string or error. +/// The value of an integer. +/// The elements of an array. +public sealed record RespValue(RespKind Kind, byte[]? Bytes = null, long Number = 0, IReadOnlyList? Items = null) +{ + /// The null reply. + public static RespValue Null { get; } = new(RespKind.Null); + + /// The text of a string or error reply. + public string? Text => Bytes is null ? null : Encoding.UTF8.GetString(Bytes); +} + +/// A Redis error reply. +public sealed class RedisException : Exception +{ + /// Creates the exception. + public RedisException() + { + } + + /// Creates the exception with a message. + /// The message. + public RedisException(string message) : base(message) + { + } + + /// Creates the exception with a message and a cause. + /// The message. + /// The cause. + public RedisException(string message, Exception innerException) : base(message, innerException) + { + } +} + +/// Encodes commands and decodes replies of RESP2 (https://redis.io/docs/reference/protocol-spec/). +public static class Resp +{ + private static readonly byte[] CrLf = "\r\n"u8.ToArray(); + + /// Encodes a command as an array of bulk strings. + /// The command and its arguments. + /// The bytes to send. + public static byte[] Command(params IReadOnlyList arguments) + { + ArgumentNullException.ThrowIfNull(arguments); + var buffer = new ArrayBufferWriter(); + Ascii(buffer, "*" + arguments.Count.ToString(CultureInfo.InvariantCulture)); + foreach (var argument in arguments) + { + var bytes = argument switch + { + byte[] raw => raw, + string text => Encoding.UTF8.GetBytes(text), + IFormattable number => Encoding.UTF8.GetBytes(number.ToString(null, CultureInfo.InvariantCulture)), + _ => throw new ArgumentException("Arguments are strings, numbers or byte arrays.", nameof(arguments)), + }; + Ascii(buffer, "$" + bytes.Length.ToString(CultureInfo.InvariantCulture)); + buffer.Write(bytes); + buffer.Write(CrLf); + } + + return buffer.WrittenSpan.ToArray(); + } + + /// Reads one reply. + /// The connection. + /// Cancellation. + /// The reply. + /// The connection closed or sent something that is not RESP. + public static async Task ReadAsync(BufferedReader stream, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(stream); + var line = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false); + if (line.Length == 0) + { + throw new IOException("Empty RESP line."); + } + + var rest = line[1..]; + switch (line[0]) + { + case '+': + return new RespValue(RespKind.SimpleString, Encoding.UTF8.GetBytes(rest)); + case '-': + return new RespValue(RespKind.Error, Encoding.UTF8.GetBytes(rest)); + case ':': + return new RespValue(RespKind.Number, Number: Parse(rest)); + case '$': + var length = Parse(rest); + if (length < 0) + { + return RespValue.Null; + } + + var bytes = await stream.ReadExactlyAsync((int)length, cancellationToken).ConfigureAwait(false); + var end = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false); + return end.Length == 0 ? new RespValue(RespKind.BulkString, bytes) : throw new IOException("Bulk string without its line end."); + case '*': + var count = Parse(rest); + if (count < 0) + { + return RespValue.Null; + } + + var items = new RespValue[count]; + for (var i = 0; i < count; i++) + { + items[i] = await ReadAsync(stream, cancellationToken).ConfigureAwait(false); + } + + return new RespValue(RespKind.Array, Items: items); + default: + throw new IOException("Unexpected RESP reply type."); + } + } + + private static long Parse(string text) => + long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var value) ? value : throw new IOException("Invalid RESP length."); + + private static void Ascii(ArrayBufferWriter buffer, string text) + { + buffer.Write(Encoding.ASCII.GetBytes(text)); + buffer.Write(CrLf); + } +} + +/// Reads lines and fixed-size blocks from a stream, with its own buffer. +/// The stream. +public sealed class BufferedReader(Stream stream) +{ + private readonly byte[] _buffer = new byte[16 * 1024]; + private int _start; + private int _end; + + /// Reads up to \r\n (not included), as ASCII. + /// Cancellation. + /// The line. + public async Task ReadLineAsync(CancellationToken cancellationToken) + { + var line = new List(); + while (true) + { + for (var i = _start; i < _end; i++) + { + if (_buffer[i] == '\n' && (i > _start ? _buffer[i - 1] == '\r' : line.Count > 0 && line[^1] == '\r')) + { + line.AddRange(_buffer.AsSpan(_start, i - _start).ToArray()); + _start = i + 1; + line.RemoveAt(line.Count - 1); + return Encoding.UTF8.GetString([.. line]); + } + } + + line.AddRange(_buffer.AsSpan(_start, _end - _start).ToArray()); + await FillAsync(cancellationToken).ConfigureAwait(false); + } + } + + /// Reads exactly bytes. + /// How many. + /// Cancellation. + /// The bytes. + public async Task ReadExactlyAsync(int count, CancellationToken cancellationToken) + { + var result = new byte[count]; + var copied = 0; + while (copied < count) + { + if (_start == _end) + { + await FillAsync(cancellationToken).ConfigureAwait(false); + } + + var take = Math.Min(count - copied, _end - _start); + _buffer.AsSpan(_start, take).CopyTo(result.AsSpan(copied)); + _start += take; + copied += take; + } + + return result; + } + + private async Task FillAsync(CancellationToken cancellationToken) + { + _start = 0; + _end = await stream.ReadAsync(_buffer, cancellationToken).ConfigureAwait(false); + if (_end == 0) + { + throw new IOException("The Redis connection was closed."); + } + } +} diff --git a/src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj b/src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj index 5617b29..9654986 100644 --- a/src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj +++ b/src/Khaemhat.Infrastructure/Khaemhat.Infrastructure.csproj @@ -4,6 +4,11 @@ Khaemhat.Infrastructure + + + + + diff --git a/src/Khaemhat.Infrastructure/Licensing/LicenseDocument.cs b/src/Khaemhat.Infrastructure/Licensing/LicenseDocument.cs new file mode 100644 index 0000000..deb41ab --- /dev/null +++ b/src/Khaemhat.Infrastructure/Licensing/LicenseDocument.cs @@ -0,0 +1,311 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Infrastructure.Licensing; + +/// +/// An instance licence (SPEC §8.2). It travels as a .khl file: a JSON object with the licence and an ECDSA +/// P-256 signature over its canonical form (). +/// +public sealed record LicenseDocument +{ + /// The licence identifier. + public string Id { get; init; } = string.Empty; + + /// The licence holder. + public string Licensee { get; init; } = string.Empty; + + /// The instance the licence is bound to; for any instance. + public string? InstanceId { get; init; } + + /// When it was issued (UTC). + public DateTime IssuedAt { get; init; } + + /// When it expires (UTC); for no expiry. + public DateTime? ExpiresAt { get; init; } + + /// Concurrent users across all companies. + public int MaxConcurrentUsers { get; init; } + + /// Companies on the instance. + public int MaxCompanies { get; init; } + + /// The module codes. + public IReadOnlyList Modules { get; init; } = []; + + /// Days of full use after the expiry, before read-only. + public int GracePeriodDays { get; init; } + + /// + /// The bytes that are signed: compact JSON with the properties in declaration order, modules upper-case and sorted, + /// times in ISO 8601 UTC to the second. Two equal licences always give the same bytes. + /// + /// The UTF-8 bytes. + public byte[] CanonicalBytes() + { + var canonical = new Canonical( + Id, + Licensee, + InstanceId, + Format(IssuedAt), + ExpiresAt is { } expires ? Format(expires) : null, + MaxConcurrentUsers, + MaxCompanies, + [.. Modules.Select(m => m.Trim().ToUpperInvariant()).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)], + GracePeriodDays); + return JsonSerializer.SerializeToUtf8Bytes(canonical, LicenseJson.Options); + } + + private static string Format(DateTime value) => + DateTime.SpecifyKind(value, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); + + private sealed record Canonical( + string Id, string Licensee, string? InstanceId, string IssuedAt, string? ExpiresAt, + int MaxConcurrentUsers, int MaxCompanies, string[] Modules, int GracePeriodDays); +} + +/// The JSON settings of licence files. +internal static class LicenseJson +{ + public static JsonSerializerOptions Options { get; } = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.Never, + WriteIndented = false, + }; + + public static JsonSerializerOptions Indented { get; } = new(Options) { WriteIndented = true }; +} + +/// The outcome of a licence check. is format_invalid or signature_invalid. +/// The licence, when valid. +/// The error code otherwise. +public sealed record LicenseVerification(LicenseDocument? Document, string? Error) +{ + /// Whether the licence is authentic. + public bool IsValid => Document is not null; +} + +/// Signs licences and activation codes. Used only by tools/Khaemhat.LicenseTool, with the private key. +public static class LicenseSigner +{ + /// The format marker of .khl files. + public const string Format = "khl1"; + + /// Creates a key pair. + /// The private key (PKCS#8 PEM) and the public key (SubjectPublicKeyInfo, base64). + public static (string PrivateKeyPem, string PublicKeyBase64) CreateKeyPair() + { + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + return (key.ExportPkcs8PrivateKeyPem(), Convert.ToBase64String(key.ExportSubjectPublicKeyInfo())); + } + + /// Signs a licence. + /// The licence. + /// The private key. + /// The .khl text. + public static string Sign(LicenseDocument document, ECDsa privateKey) + { + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(privateKey); + var signature = privateKey.SignData(document.CanonicalBytes(), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + var file = new LicenseFile(Format, document, Convert.ToBase64String(signature)); + return JsonSerializer.Serialize(file, LicenseJson.Indented); + } + + /// Creates a signed activation code for one module (see ). + /// The module code. + /// The last month of validity. + /// The instance it is bound to, or for any instance. + /// The private key. + /// The code. + public static string SignActivationCode(string module, DateOnly expiresMonth, string? instanceId, ECDsa privateKey) + { + ArgumentException.ThrowIfNullOrWhiteSpace(module); + ArgumentNullException.ThrowIfNull(privateKey); + var payload = new byte[10]; + RandomNumberGenerator.Fill(payload.AsSpan(0, 5)); + ModuleActivationCode.InstanceTag(instanceId).CopyTo(payload.AsSpan(5)); + var body = ModuleActivationCode.Body(module.Trim().ToUpperInvariant(), expiresMonth, Base32.Encode(payload)); + var signature = privateKey.SignData(Encoding.ASCII.GetBytes(body), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + return body + "-" + Base32.Encode(signature); + } + + internal sealed record LicenseFile(string Format, LicenseDocument License, string Signature); +} + +/// Checks licences and activation codes with the public key built into the product (SPEC §8.2). +public sealed class LicenseVerifier +{ + /// + /// The public key of the BalboSoft licences (SubjectPublicKeyInfo, base64). The private key never enters the repository. + /// + public const string ProductPublicKey = + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEE4ybLR3rfbtmjS7vRBg8WQOz6qNOPG8itlFy9MufvWrT/qoOfxCLwehR9DnKE77GXvqD2J+ZM0Fs6ccS84YBDw=="; + + private readonly byte[] _publicKey; + + /// Creates a verifier. + /// The public key (SubjectPublicKeyInfo, base64). + public LicenseVerifier(string publicKeyBase64) + { + ArgumentException.ThrowIfNullOrWhiteSpace(publicKeyBase64); + _publicKey = Convert.FromBase64String(publicKeyBase64); + } + + /// A verifier with . + public static LicenseVerifier Product { get; } = new(ProductPublicKey); + + /// Checks a .khl file. + /// The file content. + /// The licence when the signature is valid. + public LicenseVerification Verify(string text) + { + LicenseSigner.LicenseFile? file; + try + { + file = JsonSerializer.Deserialize(text ?? string.Empty, LicenseJson.Options); + } + catch (JsonException) + { + return new LicenseVerification(null, LicenseErrors.FormatInvalid); + } + + if (file is not { Format: LicenseSigner.Format, License: not null, Signature: not null }) + { + return new LicenseVerification(null, LicenseErrors.FormatInvalid); + } + + byte[] signature; + try + { + signature = Convert.FromBase64String(file.Signature); + } + catch (FormatException) + { + return new LicenseVerification(null, LicenseErrors.FormatInvalid); + } + + return VerifySignature(file.License.CanonicalBytes(), signature) + ? new LicenseVerification(file.License, null) + : new LicenseVerification(null, LicenseErrors.SignatureInvalid); + } + + /// Checks a module activation code. + /// The code. + /// The parsed code when the signature is valid, or the error code. + public (ModuleActivationCode? Code, string? Error) VerifyActivationCode(string code) + { + if (!ModuleActivationCode.TryParse(code, out var parsed, out var signature)) + { + return (null, LicenseErrors.FormatInvalid); + } + + return VerifySignature(Encoding.ASCII.GetBytes(parsed.SignedBody), signature) + ? (parsed, null) + : (null, LicenseErrors.SignatureInvalid); + } + + private bool VerifySignature(byte[] data, byte[] signature) + { + try + { + using var key = ECDsa.Create(); + key.ImportSubjectPublicKeyInfo(_publicKey, out _); + return key.VerifyData(data, signature, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); + } + catch (CryptographicException) + { + return false; + } + } +} + +/// +/// An activation code for one module: KH1-<MODULE>-<YYYYMM>-<payload base32>-<signature base32> +/// (SPEC §8.2). The payload holds a serial and a tag of the instance (zeros for any instance); the module stays active +/// until the end of the month YYYYMM. +/// +public sealed record ModuleActivationCode(string Module, DateOnly ExpiresMonth, string Payload) +{ + /// The format version. + public const string Prefix = "KH1"; + + /// The text that is signed (everything before the signature). + public string SignedBody => Body(Module, ExpiresMonth, Payload); + + /// The last moment of validity: the end of (UTC). + public DateTime ExpiresAt => new DateTime(ExpiresMonth.Year, ExpiresMonth.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddTicks(-10); + + /// Whether the code works on an instance. + /// The instance identifier. + /// if the code is for any instance or for this one. + public bool IsFor(string instanceId) + { + var tag = Base32.Decode(Payload).AsSpan(5); + return tag.IndexOfAnyExcept((byte)0) < 0 || tag.SequenceEqual(InstanceTag(instanceId)); + } + + internal static string Body(string module, DateOnly expiresMonth, string payload) => + string.Create(CultureInfo.InvariantCulture, $"{Prefix}-{module}-{expiresMonth.Year:D4}{expiresMonth.Month:D2}-{payload}"); + + internal static byte[] InstanceTag(string? instanceId) => + instanceId is null ? new byte[5] : SHA256.HashData(Encoding.UTF8.GetBytes(instanceId.Trim().ToUpperInvariant()))[..5]; + + internal static bool TryParse(string? text, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out ModuleActivationCode? code, out byte[] signature) + { + code = null; + signature = []; + var parts = text?.Trim().ToUpperInvariant().Split('-'); + if (parts is not { Length: 5 } || parts[0] != Prefix || parts[1].Length is < 2 or > 10 || parts[2].Length != 6 + || !int.TryParse(parts[2][..4], NumberStyles.None, CultureInfo.InvariantCulture, out var year) + || !int.TryParse(parts[2][4..], NumberStyles.None, CultureInfo.InvariantCulture, out var month) + || year < 2000 || month is < 1 or > 12) + { + return false; + } + + try + { + if (Base32.Decode(parts[3]).Length != 10) + { + return false; + } + + signature = Base32.Decode(parts[4]); + } + catch (FormatException) + { + return false; + } + + code = new ModuleActivationCode(parts[1], new DateOnly(year, month, 1), parts[3]); + return true; + } +} + +/// The error codes of licences. +public static class LicenseErrors +{ + /// The text is not a licence or a code. + public const string FormatInvalid = "format_invalid"; + + /// The signature does not match: changed or not issued by BalboSoft. + public const string SignatureInvalid = "signature_invalid"; + + /// A fictitious code outside test mode (SPEC §8.3). + public const string TestOnly = "license_test_only"; + + /// The licence or code has expired. + public const string Expired = "license_expired"; + + /// The licence or code belongs to another instance. + public const string WrongInstance = "license_wrong_instance"; + + /// The module code is unknown. + public const string UnknownModule = "module_unknown"; +} diff --git a/src/Khaemhat.Infrastructure/Logging/DbLoggerProvider.cs b/src/Khaemhat.Infrastructure/Logging/DbLoggerProvider.cs new file mode 100644 index 0000000..838381e --- /dev/null +++ b/src/Khaemhat.Infrastructure/Logging/DbLoggerProvider.cs @@ -0,0 +1,261 @@ +using System.Text; +using System.Text.Json; +using System.Threading.Channels; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Logging; +using Khaemhat.Data; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Infrastructure.Logging; + +/// +/// The database half of the single log pipeline (SPEC §9.5): every event that passes the filters goes to stdout (JSON +/// console) and here to sys_log. Events are queued and written in batches by ; until the +/// system database is ready () they wait in the queue. Section, trace, user, company and +/// request come from the logging scopes. +/// +[ProviderAlias("Database")] +public sealed class DbLoggerProvider : ILoggerProvider, ISupportExternalScope +{ + private readonly DbLogSink _sink; + private IExternalScopeProvider _scopes = new LoggerExternalScopeProvider(); + + /// Creates the provider. + /// The queue that writes the events. + public DbLoggerProvider(DbLogSink sink) + { + ArgumentNullException.ThrowIfNull(sink); + _sink = sink; + } + + /// + public ILogger CreateLogger(string categoryName) => new DbLogger(categoryName, this); + + /// + public void SetScopeProvider(IExternalScopeProvider scopeProvider) => _scopes = scopeProvider ?? new LoggerExternalScopeProvider(); + + /// + public void Dispose() + { + } + + private sealed class DbLogger(string category, DbLoggerProvider provider) : ILogger + { + public IDisposable? BeginScope(TState state) + where TState : notnull => provider._scopes.Push(state); + + public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None && !DbLogSink.IsWriting; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (!IsEnabled(logLevel) || category.StartsWith(typeof(DbLogSink).Namespace!, StringComparison.Ordinal)) + { + return; + } + + var entry = new LogEntry + { + At = DateTime.UtcNow, + Level = logLevel.ToString(), + Section = LogSections.FromCategory(category).ToString(), + Source = category.Length > 200 ? category[..200] : category, + Message = formatter(state, exception), + Exception = exception?.ToString(), + }; + + var data = new Dictionary(StringComparer.Ordinal); + if (state is IEnumerable> values) + { + foreach (var (key, value) in values) + { + if (key != "{OriginalFormat}") + { + data[key] = Simple(value); + } + } + } + + provider._scopes.ForEachScope( + static (scope, target) => + { + if (scope is not IEnumerable> pairs) + { + return; + } + + foreach (var (key, value) in pairs) + { + var text = value?.ToString(); + switch (key) + { + case LogSections.ScopeKey when text is not null: target.Entry.Section = text; break; + case LogSections.TraceIdKey: target.Entry.TraceId = Clip(text, 64); break; + case LogSections.UserKey: target.Entry.UserName = Clip(text, 100); break; + case LogSections.CompanyKey: target.Entry.CompanyCode = Clip(text, 20); break; + case LogSections.RequestKey: target.Entry.Request = Clip(text, 400); break; + case LogSections.EntityKey: target.Entry.Entity = Clip(text, 100); break; + case LogSections.EntityIdKey: target.Entry.EntityId = Clip(text, 100); break; + default: break; + } + } + }, + (Entry: entry, Data: data)); + + if (data.Count > 0) + { + try + { + entry.Data = JsonSerializer.Serialize(data); + } + catch (NotSupportedException) + { + entry.Data = null; + } + } + + provider._sink.Enqueue(entry); + } + + private static object? Simple(object? value) => value switch + { + null or string or bool or int or long or double or decimal or float or short or byte => value, + DateTime or DateTimeOffset or Guid or TimeSpan or Enum => value.ToString(), + _ => value.ToString(), + }; + + private static string? Clip(string? value, int length) => value is null || value.Length <= length ? value : value[..length]; + } +} + +/// +/// Writes queued log events to sys_log in batches (up to 200 events or every second). The queue is bounded: +/// when the database cannot keep up the oldest events are dropped, never the application. Events logged while the +/// sink itself writes are ignored, so a database error cannot loop. +/// +public sealed class DbLogSink : IAsyncDisposable +{ + private const int BatchSize = 200; + private static readonly AsyncLocal Writing = new(); + private readonly Channel _queue = Channel.CreateBounded( + new BoundedChannelOptions(20_000) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true }); + + private IUnitOfWorkFactory? _factory; + private Task? _writer; + private CancellationTokenSource? _stopping; + + /// Whether the current flow is the sink writing (its own events are not logged to the database). + public static bool IsWriting => Writing.Value; + + /// Events written since the start. + public long Written { get; private set; } + + /// Events lost because the database failed. + public long Failed { get; private set; } + + /// Queues an event. + /// The event. + public void Enqueue(LogEntry entry) => _queue.Writer.TryWrite(entry); + + /// Starts writing, once the system database is migrated. + /// Opens the system database. + public void Start(IUnitOfWorkFactory factory) + { + ArgumentNullException.ThrowIfNull(factory); + if (_writer is not null) + { + return; + } + + _factory = factory; + _stopping = new CancellationTokenSource(); + _writer = Task.Run(() => RunAsync(_stopping.Token)); + } + + /// Writes what is queued now (tests, shutdown). + /// Cancellation. + /// A task. + public async Task FlushAsync(CancellationToken cancellationToken = default) + { + var batch = new List(); + while (_queue.Reader.TryRead(out var entry)) + { + batch.Add(entry); + if (batch.Count == BatchSize) + { + await WriteAsync(batch, cancellationToken).ConfigureAwait(false); + batch.Clear(); + } + } + + if (batch.Count > 0) + { + await WriteAsync(batch, cancellationToken).ConfigureAwait(false); + } + } + + /// + public async ValueTask DisposeAsync() + { + if (_stopping is null || _writer is null) + { + return; + } + + await _stopping.CancelAsync().ConfigureAwait(false); + try + { + await _writer.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + + await FlushAsync(CancellationToken.None).ConfigureAwait(false); + _stopping.Dispose(); + } + + private async Task RunAsync(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + await _queue.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false); + await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false); + await FlushAsync(cancellationToken).ConfigureAwait(false); + } + } + + private async Task WriteAsync(List batch, CancellationToken cancellationToken) + { + if (_factory is null) + { + return; + } + + Writing.Value = true; + try + { + await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); + var repository = unitOfWork.Repository(); + await unitOfWork.InTransactionAsync( + async ct => + { + foreach (var entry in batch) + { + await repository.InsertAsync(entry, ct).ConfigureAwait(false); + } + }, + cancellationToken).ConfigureAwait(false); + Written += batch.Count; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Failed += batch.Count; + await Console.Error.WriteLineAsync(new StringBuilder("Khaemhat: log events not written to sys_log: ").Append(ex.GetType().Name).Append(' ').Append(ex.Message), CancellationToken.None) + .ConfigureAwait(false); + } + finally + { + Writing.Value = false; + } + } +} diff --git a/src/Khaemhat.Infrastructure/Security/Base32.cs b/src/Khaemhat.Infrastructure/Security/Base32.cs new file mode 100644 index 0000000..4eb2d1a --- /dev/null +++ b/src/Khaemhat.Infrastructure/Security/Base32.cs @@ -0,0 +1,69 @@ +using System.Text; + +namespace Khaemhat.Infrastructure.Security; + +/// Base32 of RFC 4648 (alphabet A-Z2-7), used by TOTP secrets and activation codes. No padding is written. +public static class Base32 +{ + private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + + /// Encodes bytes. + /// The bytes. + /// The text, without padding. + public static string Encode(ReadOnlySpan data) + { + var builder = new StringBuilder((data.Length * 8 + 4) / 5); + int buffer = 0, bits = 0; + foreach (var b in data) + { + buffer = (buffer << 8) | b; + bits += 8; + while (bits >= 5) + { + builder.Append(Alphabet[(buffer >> (bits - 5)) & 31]); + bits -= 5; + } + } + + if (bits > 0) + { + builder.Append(Alphabet[(buffer << (5 - bits)) & 31]); + } + + return builder.ToString(); + } + + /// Decodes text; spaces, dashes and padding are ignored, letters may be lower-case. + /// The text. + /// The bytes. + /// A character is not in the alphabet. + public static byte[] Decode(string text) + { + ArgumentNullException.ThrowIfNull(text); + var output = new List(text.Length * 5 / 8); + int buffer = 0, bits = 0; + foreach (var raw in text) + { + if (raw is ' ' or '-' or '=') + { + continue; + } + + var index = Alphabet.IndexOf(char.ToUpperInvariant(raw), StringComparison.Ordinal); + if (index < 0) + { + throw new FormatException("The text is not valid base32."); + } + + buffer = (buffer << 5) | index; + bits += 5; + if (bits >= 8) + { + output.Add((byte)((buffer >> (bits - 8)) & 0xFF)); + bits -= 8; + } + } + + return [.. output]; + } +} diff --git a/src/Khaemhat.Infrastructure/Security/DataProtectionKeyStore.cs b/src/Khaemhat.Infrastructure/Security/DataProtectionKeyStore.cs new file mode 100644 index 0000000..0eed91b --- /dev/null +++ b/src/Khaemhat.Infrastructure/Security/DataProtectionKeyStore.cs @@ -0,0 +1,77 @@ +using System.Xml.Linq; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Microsoft.AspNetCore.DataProtection.Repositories; +using Microsoft.AspNetCore.DataProtection.XmlEncryption; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Infrastructure.Security; + +/// +/// The ASP.NET Core DataProtection key ring in sys_data_protection_keys (SPEC §1.5: no key files on disk), so +/// that cookies, antiforgery tokens and circuits survive restarts and are shared by instances on the same system +/// database. Keys are encrypted with . +/// +/// Opens the system database. +public sealed class DataProtectionKeyStore(IUnitOfWorkFactory factory) : IXmlRepository +{ + /// + public IReadOnlyCollection GetAllElements() => + Task.Run(async () => + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System).ConfigureAwait(false); + var rows = await unitOfWork.Repository().ListAsync(Query.For().OrderBy(k => k.Id)).ConfigureAwait(false); + return (IReadOnlyCollection)[.. rows.Items.Select(k => XElement.Parse(k.Xml))]; + }).GetAwaiter().GetResult(); + + /// + public void StoreElement(XElement element, string friendlyName) + { + ArgumentNullException.ThrowIfNull(element); + Task.Run(async () => + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System).ConfigureAwait(false); + await unitOfWork.Repository().InsertAsync(new DataProtectionKey + { + FriendlyName = friendlyName.Length > 200 ? friendlyName[..200] : friendlyName, + Xml = element.ToString(SaveOptions.DisableFormatting), + }).ConfigureAwait(false); + }).GetAwaiter().GetResult(); + } +} + +/// Encrypts DataProtection keys with the instance key (KHAEMHAT_SECRET_KEY). +/// The instance key. +public sealed class SecretKeyXmlEncryptor(ISecretProtector protector) : IXmlEncryptor +{ + /// The purpose of the encryption. + public const string Purpose = "dataprotection:keys"; + + /// + public EncryptedXmlInfo Encrypt(XElement plaintextElement) + { + ArgumentNullException.ThrowIfNull(plaintextElement); + var value = protector.Protect(plaintextElement.ToString(SaveOptions.DisableFormatting), Purpose); + return new EncryptedXmlInfo(new XElement("khaemhatEncryptedKey", new XElement("value", value)), typeof(SecretKeyXmlDecryptor)); + } +} + +/// Decrypts what wrote; created by DataProtection with the service provider. +public sealed class SecretKeyXmlDecryptor : IXmlDecryptor +{ + private readonly ISecretProtector _protector; + + /// Creates the decryptor. + /// The services, holding the instance key. + public SecretKeyXmlDecryptor(IServiceProvider services) => _protector = services.GetRequiredService(); + + /// + public XElement Decrypt(XElement encryptedElement) + { + ArgumentNullException.ThrowIfNull(encryptedElement); + var value = encryptedElement.Element("value")?.Value ?? throw new SecretProtectionException("The DataProtection key has no value."); + return XElement.Parse(_protector.Unprotect(value, SecretKeyXmlEncryptor.Purpose)); + } +} diff --git a/src/Khaemhat.Infrastructure/Security/PasswordHasher.cs b/src/Khaemhat.Infrastructure/Security/PasswordHasher.cs new file mode 100644 index 0000000..efad137 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Security/PasswordHasher.cs @@ -0,0 +1,112 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; + +namespace Khaemhat.Infrastructure.Security; + +/// The result of checking a password against a stored hash. +public enum PasswordVerification +{ + /// The password does not match (or the hash is not readable). + Failed = 0, + + /// The password matches. + Succeeded = 1, + + /// The password matches, but the hash uses older parameters: store a new hash. + SucceededRehashNeeded = 2, +} + +/// +/// Password hashes with PBKDF2-HMAC-SHA256 (SPEC §7.3): 600,000 iterations, a random 16-byte salt and a 32-byte +/// result, stored as pbkdf2-sha256$600000$<salt base64>$<hash base64>. The comparison runs in +/// constant time. +/// +public static class PasswordHasher +{ + /// The algorithm prefix of the stored format. + public const string Algorithm = "pbkdf2-sha256"; + + /// The iterations of new hashes (OWASP 2023 recommendation for PBKDF2-HMAC-SHA256). + public const int Iterations = 600_000; + + private const int SaltLength = 16; + private const int HashLength = 32; + + /// Hashes a password with a new random salt. + /// The password. + /// The stored form. + public static string Hash(string password) => Hash(password, Iterations); + + /// Hashes a password with the given iterations (tests use fewer to stay fast). + /// The password. + /// The PBKDF2 iterations. + /// The stored form. + public static string Hash(string password, int iterations) + { + ArgumentNullException.ThrowIfNull(password); + ArgumentOutOfRangeException.ThrowIfLessThan(iterations, 1); + var salt = RandomNumberGenerator.GetBytes(SaltLength); + var hash = Derive(password, salt, iterations); + return string.Join('$', Algorithm, iterations.ToString(CultureInfo.InvariantCulture), Convert.ToBase64String(salt), Convert.ToBase64String(hash)); + } + + /// Checks a password against a stored hash. + /// The stored form; never matches. + /// The password typed. + /// The outcome. + public static PasswordVerification Verify(string? storedHash, string password) + { + ArgumentNullException.ThrowIfNull(password); + if (!TryParse(storedHash, out var iterations, out var salt, out var expected)) + { + return PasswordVerification.Failed; + } + + var actual = Derive(password, salt, iterations, expected.Length); + if (!CryptographicOperations.FixedTimeEquals(actual, expected)) + { + return PasswordVerification.Failed; + } + + return iterations < Iterations ? PasswordVerification.SucceededRehashNeeded : PasswordVerification.Succeeded; + } + + private static byte[] Derive(string password, byte[] salt, int iterations, int length = HashLength) + { + var bytes = Encoding.UTF8.GetBytes(password); + try + { + return Rfc2898DeriveBytes.Pbkdf2(bytes, salt, iterations, HashAlgorithmName.SHA256, length); + } + finally + { + CryptographicOperations.ZeroMemory(bytes); + } + } + + private static bool TryParse(string? stored, out int iterations, out byte[] salt, out byte[] hash) + { + iterations = 0; + salt = []; + hash = []; + var parts = stored?.Split('$'); + if (parts is not { Length: 4 } || parts[0] != Algorithm + || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out iterations) || iterations < 1) + { + return false; + } + + try + { + salt = Convert.FromBase64String(parts[2]); + hash = Convert.FromBase64String(parts[3]); + } + catch (FormatException) + { + return false; + } + + return salt.Length >= 8 && hash.Length >= 16; + } +} diff --git a/src/Khaemhat.Infrastructure/Security/SecureTokenGenerator.cs b/src/Khaemhat.Infrastructure/Security/SecureTokenGenerator.cs new file mode 100644 index 0000000..e5baf6a --- /dev/null +++ b/src/Khaemhat.Infrastructure/Security/SecureTokenGenerator.cs @@ -0,0 +1,64 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Khaemhat.Infrastructure.Security; + +/// +/// Random tokens for sessions, password recovery and recovery codes. Tokens are URL-safe base64 without padding; the +/// database stores only , so a copy of a table does not reveal a usable token. +/// +public static class SecureTokenGenerator +{ + /// A token of random bytes (32 = 256 bits). + /// The entropy in bytes. + /// The token. + public static string Create(int bytes = 32) + { + ArgumentOutOfRangeException.ThrowIfLessThan(bytes, 16); + return Base64Url(RandomNumberGenerator.GetBytes(bytes)); + } + + /// A short code for people: groups of letters and digits without look-alikes, for example K7QM-2XRP. + /// The number of groups of four characters. + /// The code. + public static string CreateReadableCode(int groups = 2) + { + const string Alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + ArgumentOutOfRangeException.ThrowIfLessThan(groups, 1); + var builder = new StringBuilder(groups * 5); + for (var g = 0; g < groups; g++) + { + if (g > 0) + { + builder.Append('-'); + } + + for (var i = 0; i < 4; i++) + { + builder.Append(Alphabet[RandomNumberGenerator.GetInt32(Alphabet.Length)]); + } + } + + return builder.ToString(); + } + + /// The SHA-256 hash of a token in lower-case hexadecimal, as stored in the database. + /// The token. + /// 64 hexadecimal digits. + public static string Hash(string token) + { + ArgumentNullException.ThrowIfNull(token); + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + } + + /// Compares two token hashes in constant time. + /// A hash. + /// Another hash. + /// Whether they are equal. + public static bool HashesEqual(string? a, string? b) => + a is not null && b is not null + && CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(a), Encoding.ASCII.GetBytes(b)); + + private static string Base64Url(byte[] data) => + Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_'); +} diff --git a/src/Khaemhat.Infrastructure/Security/TotpGenerator.cs b/src/Khaemhat.Infrastructure/Security/TotpGenerator.cs new file mode 100644 index 0000000..126c34a --- /dev/null +++ b/src/Khaemhat.Infrastructure/Security/TotpGenerator.cs @@ -0,0 +1,106 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Security.Cryptography; + +namespace Khaemhat.Infrastructure.Security; + +/// +/// Time-based one-time passwords of RFC 6238 with the parameters every authenticator app supports: HMAC-SHA1, +/// 6 digits, 30-second steps. Verification accepts one step before and after the current one (clock drift) and never +/// the same step twice. +/// +public static class TotpGenerator +{ + /// The length of a step in seconds. + public const int StepSeconds = 30; + + /// The number of digits. + public const int Digits = 6; + + /// The length of new secrets in bytes (160 bits, as RFC 4226 recommends). + public const int SecretLength = 20; + + /// A new random secret in base32, to show to the user and store encrypted. + /// The secret. + public static string CreateSecret() => Base32.Encode(RandomNumberGenerator.GetBytes(SecretLength)); + + /// The time step of a moment. + /// The moment. + /// The step number. + public static long StepOf(DateTimeOffset time) => time.ToUnixTimeSeconds() / StepSeconds; + + /// The code of a step. + /// The secret bytes. + /// The step number. + /// The code, zero-padded to six digits. + public static string Compute(ReadOnlySpan secret, long step) + { + Span counter = stackalloc byte[8]; + BinaryPrimitives.WriteInt64BigEndian(counter, step); + Span hash = stackalloc byte[20]; +#pragma warning disable CA5350 // RFC 6238 and the authenticator apps use HMAC-SHA1; it is not used here for collision resistance. + HMACSHA1.HashData(secret, counter, hash); +#pragma warning restore CA5350 + var offset = hash[^1] & 0x0F; + var binary = ((hash[offset] & 0x7F) << 24) | (hash[offset + 1] << 16) | (hash[offset + 2] << 8) | hash[offset + 3]; + return (binary % 1_000_000).ToString("D6", CultureInfo.InvariantCulture); + } + + /// Checks a code. + /// The secret in base32. + /// The code typed (spaces are ignored). + /// The current time. + /// The last step accepted for this account, or . + /// The matching step, to store as the last used one; if the code is not valid. + public static long? Verify(string secretBase32, string? code, DateTimeOffset now, long? lastUsedStep) + { + ArgumentNullException.ThrowIfNull(secretBase32); + var digits = code?.Replace(" ", string.Empty, StringComparison.Ordinal); + if (digits is not { Length: Digits } || !digits.All(char.IsAsciiDigit)) + { + return null; + } + + var secret = Base32.Decode(secretBase32); + try + { + var current = StepOf(now); + for (var step = current - 1; step <= current + 1; step++) + { + if (lastUsedStep is { } last && step <= last) + { + continue; + } + + var expected = Compute(secret, step); + if (CryptographicOperations.FixedTimeEquals( + System.Text.Encoding.ASCII.GetBytes(expected), System.Text.Encoding.ASCII.GetBytes(digits))) + { + return step; + } + } + + return null; + } + finally + { + CryptographicOperations.ZeroMemory(secret); + } + } + + /// + /// The otpauth:// address that authenticator apps read (key URI format), for the QR code or a link. + /// + /// The secret in base32. + /// The account label, for example root@DEMO. + /// The issuer shown by the app. + /// The address. + public static string ProvisioningUri(string secretBase32, string account, string issuer = "Khaemhat") + { + ArgumentNullException.ThrowIfNull(secretBase32); + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(issuer); + var label = Uri.EscapeDataString(issuer) + ":" + Uri.EscapeDataString(account); + return $"otpauth://totp/{label}?secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm=SHA1&digits={Digits}&period={StepSeconds}"; + } +} diff --git a/src/Khaemhat.Web/Components/App.razor b/src/Khaemhat.Web/Components/App.razor index 169dbcd..f5e4d85 100644 --- a/src/Khaemhat.Web/Components/App.razor +++ b/src/Khaemhat.Web/Components/App.razor @@ -12,14 +12,22 @@ - - + @* No : it is an inline script, and the content security policy allows none (no JS modules yet). *@ + - + + +@code { + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + // The sign-in pages are static server-rendered forms (they set the cookie); everything else is interactive. + private IComponentRenderMode? PageRenderMode => HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null; +} diff --git a/src/Khaemhat.Web/Components/Layout/AuthLayout.razor b/src/Khaemhat.Web/Components/Layout/AuthLayout.razor new file mode 100644 index 0000000..8409534 --- /dev/null +++ b/src/Khaemhat.Web/Components/Layout/AuthLayout.razor @@ -0,0 +1,26 @@ +@inherits LayoutComponentBase +@using Khaemhat.Core.Common +@inject ProductVersion Version + +@* Mockups 001-003: brand panel on the left, the form on the right. Texts move to the it-IT resources in M3. *@ +
+ +
+
+ @Body +
+ +
+
diff --git a/src/Khaemhat.Web/Components/Pages/AccessDenied.razor b/src/Khaemhat.Web/Components/Pages/AccessDenied.razor new file mode 100644 index 0000000..31d6e6f --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/AccessDenied.razor @@ -0,0 +1,12 @@ +@page "/accesso-negato" +@attribute [ExcludeFromInteractiveRouting] + +Khaemhat · accesso negato + +
+
+

Accesso negato

+

Il tuo profilo non ha il permesso per questa pagina, oppure il modulo non è compreso nella licenza.

+ +
+
diff --git a/src/Khaemhat.Web/Components/Pages/Home.razor b/src/Khaemhat.Web/Components/Pages/Home.razor index 644b824..f751fa8 100644 --- a/src/Khaemhat.Web/Components/Pages/Home.razor +++ b/src/Khaemhat.Web/Components/Pages/Home.razor @@ -1,21 +1,42 @@ @page "/" +@attribute [Authorize] +@using Khaemhat.Application.Licensing @using Khaemhat.Core.Common @inject ProductVersion Version +@inject ILicenseGate Licenses -@* Placeholder until the shell of M3 (SPEC §20, M0): brand, icon and version, styled after the login hero (mockup 001). - Texts move to the it-IT resources with the localization of M3. *@ -Khaemhat · in costruzione +@* Placeholder until the shell of M3 (SPEC §20): who is signed in, in which company, with which licence. Texts move to + the it-IT resources with the localization of M3. *@ +Khaemhat

Khaemhat v @Version.MajorMinor

-

Gestionale ERP + CRM per piccole e medie imprese italiane.

-

Installazione in costruzione: le funzioni arrivano milestone dopo milestone.

- + +

Benvenuto, @context.User.FindFirst(SessionCookie.DisplayNameClaim)?.Value + (@LevelLabel(context.User.FindFirst(SessionCookie.LevelClaim)?.Value)) + @if (context.User.FindFirst(SessionCookie.CompanyClaim)?.Value is { } company) + { + · azienda @company + } +

+
+

Accesso, utenti, ruoli, licenze e log sono pronti; le schermate di lavoro arrivano con l'interfaccia della milestone 3. + Licenza: @(Licenses.Current.Kind == LicenseKind.Trial ? "prova" : Licenses.Current.Licensee) · moduli @string.Join(", ", Licenses.Current.Modules.Order())

+
+ +@code { + private static string LevelLabel(string? level) => level switch + { + "SuperUser" => "super utente", + "Administrator" => "amministratore", + _ => "utente", + }; +} diff --git a/src/Khaemhat.Web/Components/Pages/Login.razor b/src/Khaemhat.Web/Components/Pages/Login.razor new file mode 100644 index 0000000..74703eb --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Login.razor @@ -0,0 +1,116 @@ +@page "/login" +@attribute [ExcludeFromInteractiveRouting] +@layout AuthLayout +@using Khaemhat.Application.Licensing +@using Khaemhat.Application.Security +@using Khaemhat.Core.Instance +@using Khaemhat.Data.Companies +@inject SignInService SignIn +@inject ICompanyRegistry Companies +@inject ILicenseGate Licenses +@inject SecurityPolicyOptions Policy +@inject NavigationManager Navigation +@inject TimeProvider Clock + +Accedi · Khaemhat + +

Accedi

+

Scegli l'azienda e inserisci le credenziali.

+ +@foreach (var message in Errors) +{ + +} + + + + + + @foreach (var company in AvailableCompanies) + { + + } + + + + + + + + + + + + + +@if (TrialNotice is not null) +{ +
@TrialNotice
+} + +@code { + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private LoginInput Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + private IReadOnlyList AvailableCompanies { get; set; } = []; + + private IReadOnlyList Errors { get; set; } = []; + + private string? TrialNotice { get; set; } + + /// + protected override async Task OnInitializedAsync() + { + Input ??= new LoginInput(); + AvailableCompanies = [.. (await Companies.ListAsync(HttpContext.RequestAborted)).Where(c => c.Status is CompanyStatus.Active or CompanyStatus.ReadOnly)]; + if (HttpMethods.IsGet(HttpContext.Request.Method) && string.IsNullOrEmpty(Input.CompanyCode)) + { + Input.CompanyCode = AvailableCompanies.FirstOrDefault(c => c.IsDefault)?.Code; + } + + var license = Licenses.Current; + if (license.Kind == LicenseKind.Trial) + { + TrialNotice = $"Licenza in modalità prova: restano {license.DaysLeft(Clock.GetUtcNow().UtcDateTime)} giorni, con i moduli Base e Contabilità e {license.MaxConcurrentUsers} utenti collegati."; + } + else if (license.Status != LicenseStatus.Valid) + { + TrialNotice = "La licenza è scaduta: rivolgiti all'amministratore."; + } + } + + private async Task SubmitAsync() + { + var request = new SignInRequest( + Input.CompanyCode, Input.UserName ?? string.Empty, Input.Password ?? string.Empty, Input.Remember, + HttpContext.Connection.RemoteIpAddress?.ToString(), HttpContext.Request.Headers.UserAgent.ToString()); + var result = await SignIn.SignInAsync(request, HttpContext.RequestAborted); + Input.Password = null; + if (!result.Succeeded || result.Cookie is null) + { + Errors = LoginFlow.Messages(result.Error); + return; + } + + var persistent = result.State == SessionState.Active && Input.Remember ? Clock.GetUtcNow() + Policy.PersistentSessionLifetime : (DateTimeOffset?)null; + SessionCookie.Write(HttpContext, result.Cookie, persistent); + Navigation.NavigateTo(LoginFlow.NextPage(result.State, ReturnUrl)); + } + + private sealed class LoginInput + { + public string? CompanyCode { get; set; } + + public string? UserName { get; set; } + + public string? Password { get; set; } + + public bool Remember { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/LoginPasswordChange.razor b/src/Khaemhat.Web/Components/Pages/LoginPasswordChange.razor new file mode 100644 index 0000000..b215b1e --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/LoginPasswordChange.razor @@ -0,0 +1,106 @@ +@page "/login/cambio-password" +@attribute [ExcludeFromInteractiveRouting] +@layout AuthLayout +@using Khaemhat.Application.Security +@inject SignInService SignIn +@inject SecurityPolicyOptions Policy +@inject NavigationManager Navigation +@inject TimeProvider Clock + +Cambio password · Khaemhat + +

Scegli una nuova password

+

Al primo accesso, o dopo una password provvisoria, serve una password personale.

+ +@foreach (var message in Errors) +{ + +} + + + + + + + + + + + +
    +
  • Almeno @Policy.MinimumLength caratteri
  • +
  • Almeno tre tipi tra minuscole, maiuscole, cifre e simboli
  • +
  • Diversa dal nome utente e dalle ultime @Policy.HistorySize password
  • +
+ + +
+ +@code { + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private PasswordInput Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + private IReadOnlyList Errors { get; set; } = []; + + private SessionIdentity? Identity { get; set; } + + /// + protected override async Task OnInitializedAsync() + { + Input ??= new PasswordInput(); + Identity = await SignIn.ResolveAsync(SessionCookie.Read(HttpContext), HttpContext.RequestAborted); + if (Identity?.State != SessionState.PendingPasswordChange) + { + Navigation.NavigateTo(Identity is null ? LoginFlow.LoginPage : LoginFlow.NextPage(Identity.State, ReturnUrl)); + } + } + + private async Task SubmitAsync() + { + if (Identity?.State != SessionState.PendingPasswordChange) + { + return; + } + + if (!string.Equals(Input.New, Input.Confirm, StringComparison.Ordinal)) + { + Errors = ["Le due nuove password non coincidono."]; + Clear(); + return; + } + + var result = await SignIn.ChangePasswordAsync(SessionCookie.Read(HttpContext)!, Input.Current ?? string.Empty, Input.New ?? string.Empty, HttpContext.RequestAborted); + Clear(); + if (!result.Succeeded || result.Cookie is null) + { + Errors = LoginFlow.Messages(result.Error); + return; + } + + var persistent = result.State == SessionState.Active && Identity.Persistent ? Clock.GetUtcNow() + Policy.PersistentSessionLifetime : (DateTimeOffset?)null; + SessionCookie.Write(HttpContext, result.Cookie, persistent); + Navigation.NavigateTo(LoginFlow.NextPage(result.State, ReturnUrl)); + } + + private void Clear() + { + Input.Current = null; + Input.New = null; + Input.Confirm = null; + } + + private sealed class PasswordInput + { + public string? Current { get; set; } + + public string? New { get; set; } + + public string? Confirm { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/LoginTotp.razor b/src/Khaemhat.Web/Components/Pages/LoginTotp.razor new file mode 100644 index 0000000..507a380 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/LoginTotp.razor @@ -0,0 +1,85 @@ +@page "/login/verifica" +@attribute [ExcludeFromInteractiveRouting] +@layout AuthLayout +@using Khaemhat.Application.Security +@inject SignInService SignIn +@inject SecurityPolicyOptions Policy +@inject NavigationManager Navigation +@inject TimeProvider Clock + +Verifica in due passaggi · Khaemhat + +

Verifica in due passaggi

+

Inserisci il codice a 6 cifre dell'app di autenticazione.

+ +@foreach (var message in Errors) +{ + +} + + + + +
+ + Oppure un codice di recupero (XXXX-XXXX) +
+
+ +
Il codice cambia ogni 30 secondi. L'autenticazione a due fattori è obbligatoria per amministratori e super utente.
+ +@code { + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private CodeInput Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + private IReadOnlyList Errors { get; set; } = []; + + private SessionIdentity? Identity { get; set; } + + /// + protected override async Task OnInitializedAsync() + { + Input ??= new CodeInput(); + Identity = await SignIn.ResolveAsync(SessionCookie.Read(HttpContext), HttpContext.RequestAborted); + if (Identity?.State != SessionState.PendingTotp) + { + Navigation.NavigateTo(Identity is null ? LoginFlow.LoginPage : LoginFlow.NextPage(Identity.State, ReturnUrl)); + } + } + + private async Task SubmitAsync() + { + if (Identity?.State != SessionState.PendingTotp) + { + return; + } + + var result = await SignIn.VerifyTotpAsync(SessionCookie.Read(HttpContext)!, (Input.Code ?? string.Empty).Replace(" ", string.Empty, StringComparison.Ordinal), HttpContext.RequestAborted); + Input.Code = null; + if (!result.Succeeded || result.Cookie is null) + { + Errors = LoginFlow.Messages(result.Error); + if (result.Error == SecurityErrors.AccountLocked) + { + SessionCookie.Clear(HttpContext); + } + + return; + } + + var persistent = result.State == SessionState.Active && Identity.Persistent ? Clock.GetUtcNow() + Policy.PersistentSessionLifetime : (DateTimeOffset?)null; + SessionCookie.Write(HttpContext, result.Cookie, persistent); + Navigation.NavigateTo(LoginFlow.NextPage(result.State, ReturnUrl)); + } + + private sealed class CodeInput + { + public string? Code { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/LoginTotpSetup.razor b/src/Khaemhat.Web/Components/Pages/LoginTotpSetup.razor new file mode 100644 index 0000000..946a1db --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/LoginTotpSetup.razor @@ -0,0 +1,113 @@ +@page "/login/configura-verifica" +@attribute [ExcludeFromInteractiveRouting] +@layout AuthLayout +@using Khaemhat.Application.Security +@inject SignInService SignIn +@inject SecurityPolicyOptions Policy +@inject NavigationManager Navigation +@inject TimeProvider Clock + +Configura la verifica in due passaggi · Khaemhat + +@if (RecoveryCodes is not null) +{ +

Codici di recupero

+

Conservali in un luogo sicuro: ognuno vale una volta sola, al posto del codice dell'app, se perdi il telefono. Non verranno mostrati di nuovo.

+
    + @foreach (var recovery in RecoveryCodes) + { +
  • @recovery
  • + } +
+ Ho salvato i codici, continua +} +else +{ +

Configura la verifica in due passaggi

+

Aggiungi l'account a un'app di autenticazione (Google Authenticator, Microsoft Authenticator, Aegis, 2FAS...) e inserisci il primo codice.

+ + @foreach (var message in Errors) + { + + } + + @if (Setup is not null) + { +
+
Chiave da inserire nell'app
+
@Grouped(Setup.Secret)
+
Sul telefono
+
Apri nell'app di autenticazione
+
+ } + + + + + + +} + +@code { + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private CodeInput Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + private IReadOnlyList Errors { get; set; } = []; + + private SessionIdentity? Identity { get; set; } + + private TotpSetup? Setup { get; set; } + + private IReadOnlyList? RecoveryCodes { get; set; } + + private string NextUrl { get; set; } = "/"; + + /// + protected override async Task OnInitializedAsync() + { + Input ??= new CodeInput(); + Identity = await SignIn.ResolveAsync(SessionCookie.Read(HttpContext), HttpContext.RequestAborted); + if (Identity?.State != SessionState.PendingTotpSetup) + { + Navigation.NavigateTo(Identity is null ? LoginFlow.LoginPage : LoginFlow.NextPage(Identity.State, ReturnUrl)); + return; + } + + Setup = await SignIn.BeginTotpSetupAsync(SessionCookie.Read(HttpContext)!, HttpContext.RequestAborted); + } + + private async Task SubmitAsync() + { + if (Identity?.State != SessionState.PendingTotpSetup) + { + return; + } + + var (result, codes) = await SignIn.ConfirmTotpSetupAsync(SessionCookie.Read(HttpContext)!, (Input.Code ?? string.Empty).Trim(), HttpContext.RequestAborted); + Input.Code = null; + if (!result.Succeeded || result.Cookie is null || codes is null) + { + Errors = LoginFlow.Messages(result.Error); + return; + } + + var persistent = result.State == SessionState.Active && Identity.Persistent ? Clock.GetUtcNow() + Policy.PersistentSessionLifetime : (DateTimeOffset?)null; + SessionCookie.Write(HttpContext, result.Cookie, persistent); + RecoveryCodes = codes; + NextUrl = LoginFlow.NextPage(result.State, ReturnUrl); + } + + private static string Grouped(string secret) => + string.Join(' ', Enumerable.Range(0, (secret.Length + 3) / 4).Select(i => secret.Substring(i * 4, Math.Min(4, secret.Length - (i * 4))))); + + private sealed class CodeInput + { + public string? Code { get; set; } + } +} diff --git a/src/Khaemhat.Web/Components/RedirectToLogin.razor b/src/Khaemhat.Web/Components/RedirectToLogin.razor new file mode 100644 index 0000000..ce6b657 --- /dev/null +++ b/src/Khaemhat.Web/Components/RedirectToLogin.razor @@ -0,0 +1,21 @@ +@inject NavigationManager Navigation + +@* Inside an interactive circuit: a page needs a signed-in user (or the session ended) - back to the login page. *@ +@code { + [CascadingParameter] + private Task? AuthenticationState { get; set; } + + /// + protected override async Task OnInitializedAsync() + { + var signedIn = AuthenticationState is not null && (await AuthenticationState).User.Identity?.IsAuthenticated == true; + if (signedIn) + { + Navigation.NavigateTo("/accesso-negato", forceLoad: true); + return; + } + + var path = "/" + Navigation.ToBaseRelativePath(Navigation.Uri); + Navigation.NavigateTo(LoginFlow.LoginPage + (path.Length > 1 ? "?returnUrl=" + Uri.EscapeDataString(path) : string.Empty), forceLoad: true); + } +} diff --git a/src/Khaemhat.Web/Components/Routes.razor b/src/Khaemhat.Web/Components/Routes.razor index 105855d..c387474 100644 --- a/src/Khaemhat.Web/Components/Routes.razor +++ b/src/Khaemhat.Web/Components/Routes.razor @@ -1,6 +1,10 @@  - + + + + + diff --git a/src/Khaemhat.Web/Components/_Imports.razor b/src/Khaemhat.Web/Components/_Imports.razor index f9a9888..2855184 100644 --- a/src/Khaemhat.Web/Components/_Imports.razor +++ b/src/Khaemhat.Web/Components/_Imports.razor @@ -1,5 +1,7 @@ @using System.Net.Http @using System.Net.Http.Json +@using Microsoft.AspNetCore.Authorization +@using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web @@ -9,3 +11,5 @@ @using Khaemhat.Web @using Khaemhat.Web.Components @using Khaemhat.Web.Components.Layout +@using Khaemhat.Core.Security +@using Khaemhat.Web.Security diff --git a/src/Khaemhat.Web/Hosting/BootstrapService.cs b/src/Khaemhat.Web/Hosting/BootstrapService.cs new file mode 100644 index 0000000..471793c --- /dev/null +++ b/src/Khaemhat.Web/Hosting/BootstrapService.cs @@ -0,0 +1,81 @@ +using Khaemhat.Application.Configuration; +using Khaemhat.Application.Instance; +using Khaemhat.Data.Migrations; +using Khaemhat.Infrastructure.Logging; + +namespace Khaemhat.Web.Hosting; + +/// +/// Runs the start sequence in the background, so that /health/live answers at once and /health/ready +/// answers 503 until the databases are migrated. A failure stops the process with exit code 1: the container restart +/// policy retries, and the log says why. +/// +/// The start sequence. +/// The start state. +/// The database log, flushed at shutdown. +/// Stops the host on failure. +/// The log. +internal sealed partial class BootstrapService( + StartupOrchestrator orchestrator, BootstrapState state, DbLogSink logSink, IHostApplicationLifetime lifetime, ILogger logger) + : BackgroundService +{ + /// + /// Migrates the system database before the host serves anything (this service is registered before DataProtection, + /// whose key ring lives there), then lets the rest of the sequence run in the background. A failure here stops the + /// start: without the system database nothing can work. + /// + /// Cancellation. + /// A task. + public override async Task StartAsync(CancellationToken cancellationToken) + { + try + { + await orchestrator.PrepareSystemDatabaseAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + state.MarkFailed(Describe(ex)); + LogStartFailed(logger, ex, Describe(ex)); + throw; + } + + await base.StartAsync(cancellationToken).ConfigureAwait(false); + } + + /// + public override async Task StopAsync(CancellationToken cancellationToken) + { + await base.StopAsync(cancellationToken).ConfigureAwait(false); + await logSink.DisposeAsync().ConfigureAwait(false); + } + + /// + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + await orchestrator.RunAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + } + catch (Exception ex) + { + var reason = Describe(ex); + state.MarkFailed(reason); + LogStartFailed(logger, ex, reason); + Environment.ExitCode = 1; + lifetime.StopApplication(); + } + } + + private static string Describe(Exception ex) => ex switch + { + ConfigurationException config => string.Join(" ", config.Errors), + MigrationException migration => migration.Message, + _ => ex.GetType().Name + ": " + ex.Message, + }; + + [LoggerMessage(Level = LogLevel.Critical, Message = "Khaemhat cannot start: {Reason}")] + private static partial void LogStartFailed(ILogger logger, Exception exception, string reason); +} diff --git a/src/Khaemhat.Web/Hosting/HealthEndpoints.cs b/src/Khaemhat.Web/Hosting/HealthEndpoints.cs index ac88d16..e99e867 100644 --- a/src/Khaemhat.Web/Hosting/HealthEndpoints.cs +++ b/src/Khaemhat.Web/Hosting/HealthEndpoints.cs @@ -1,3 +1,4 @@ +using Khaemhat.Application.Instance; using Khaemhat.Core.Common; namespace Khaemhat.Web.Hosting; @@ -5,13 +6,14 @@ namespace Khaemhat.Web.Hosting; /// /// Health endpoints for Docker and reverse proxies (SPEC §16.1, ADR 0012): /// /health/live says the process answers (the image HEALTHCHECK), /health/ready says it can serve -/// requests (from M1 it also checks the system database), /health summarises both with the version. +/// requests (the start sequence completed: databases migrated), /health summarises both with the version. /// They carry no personal or configuration data and need no authentication. /// public static class HealthEndpoints { /// Maps the three health endpoints. /// The application's route builder. + /// The route builder. public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder endpoints) { ArgumentNullException.ThrowIfNull(endpoints); @@ -19,22 +21,26 @@ public static class HealthEndpoints endpoints.MapGet("/health/live", () => Results.Text("live", "text/plain")) .ExcludeFromDescription(); - endpoints.MapGet("/health/ready", () => Results.Text("ready", "text/plain")) + endpoints.MapGet("/health/ready", (BootstrapState state) => state.IsReady + ? Results.Text("ready", "text/plain") + : Results.Text(state.Phase == BootstrapPhase.Failed ? "failed" : "starting", "text/plain", statusCode: StatusCodes.Status503ServiceUnavailable)) .ExcludeFromDescription(); - endpoints.MapGet("/health", (ProductVersion version) => Results.Json(new HealthReport( - Status: "ok", - Live: true, - Ready: true, - Version: version.Version, - Revision: version.Revision))) + endpoints.MapGet("/health", (ProductVersion version, BootstrapState state) => Results.Json( + new HealthReport( + Status: state.IsReady ? "ok" : state.Phase == BootstrapPhase.Failed ? "failed" : "starting", + Live: true, + Ready: state.IsReady, + Version: version.Version, + Revision: version.Revision), + statusCode: state.IsReady ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable)) .ExcludeFromDescription(); return endpoints; } /// The body of /health. - /// ok when the instance is live and ready. + /// ok when the instance is live and ready, starting or failed otherwise. /// Whether the process answers. /// Whether the instance can serve requests. /// Product version (SemVer). diff --git a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs index 5e57ec9..924b5c6 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs @@ -1,6 +1,17 @@ +using Khaemhat.Application.Configuration; +using Khaemhat.Application.Security; using Khaemhat.Core.Common; +using Khaemhat.Infrastructure.Logging; +using Khaemhat.Infrastructure.Security; using Khaemhat.Web.Components; +using Khaemhat.Web.Security; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.DataProtection.KeyManagement; +using Microsoft.Extensions.Options; namespace Khaemhat.Web.Hosting; @@ -11,7 +22,9 @@ namespace Khaemhat.Web.Hosting; public static class KhaemhatApp { /// Creates the configured application, ready to run. - /// Command-line arguments (ASP.NET Core host conventions, e.g. --urls). + /// Command-line arguments (ASP.NET Core host conventions, e.g. --urls; also --KHAEMHAT_*=value). + /// The application. + /// The KHAEMHAT_* variables are missing or not valid. public static WebApplication Build(string[] args) { // ApplicationName pins the static web assets manifest to this assembly, also when tests host the app. @@ -21,9 +34,13 @@ public static class KhaemhatApp ApplicationName = typeof(KhaemhatApp).Assembly.GetName().Name, }); - ApplyInstanceVariables(builder, args); + // The variables of SPEC §6, with the _FILE variants of ADR 0014; any problem stops the start with every message. + var options = new EnvironmentConfigurationReader(name => builder.Configuration[name]).Read(); + options.EnsureValid(); + ApplyHostVariables(builder, options, args); - // One JSON line per event on stdout outside development (SPEC §9.5); the database sink arrives in M2. + // One pipeline (SPEC §9.5): JSON lines on stdout outside development, and the database sink everywhere. + var logSink = new DbLogSink(); if (!builder.Environment.IsDevelopment()) { builder.Logging.ClearProviders(); @@ -35,11 +52,29 @@ public static class KhaemhatApp }); } - // Until the database key store of M2 exists, keys live in memory: nothing is written outside the data - // folder (SPEC §1.5). Antiforgery and circuit tokens therefore reset when the container restarts. - builder.Services.AddDataProtection() - .SetApplicationName("Khaemhat") - .UseEphemeralDataProtectionProvider(); + builder.Logging.AddProvider(new DbLoggerProvider(logSink)); + builder.Logging.AddFilter("Microsoft", LogLevel.Warning); + builder.Logging.AddFilter("System", LogLevel.Warning); + builder.Logging.AddFilter(typeof(SessionAuthenticationHandler).FullName, LogLevel.Warning); + + builder.Services.AddKhaemhat(options, logSink); + + // DataProtection keys in the system database, encrypted with the instance key (SPEC §1.5). + builder.Services.AddDataProtection().SetApplicationName("Khaemhat"); + builder.Services.AddSingleton>(sp => new ConfigureOptions(o => + { + o.XmlRepository = new DataProtectionKeyStore(sp.GetRequiredService()); + o.XmlEncryptor = new SecretKeyXmlEncryptor(sp.GetRequiredService()); + })); + + // Sign-in with the session cookie (SPEC §7.3) and policies for permissions, levels and modules. + builder.Services.AddAuthentication(SessionCookie.Scheme) + .AddScheme(SessionCookie.Scheme, null); + builder.Services.AddAuthorization(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddCascadingAuthenticationState(); + builder.Services.AddScoped(); builder.Services.AddSingleton(ProductVersion.FromAssembly(typeof(KhaemhatApp).Assembly)); builder.Services.AddRazorComponents() @@ -53,37 +88,51 @@ public static class KhaemhatApp app.UseExceptionHandler("/Error", createScopeForErrors: true); } + app.UseSecurityHeaders(); app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); + app.MapHealthEndpoints(); + app.UseStartingPage(); + app.UseAuthentication(); + app.UseLogScope(); + app.UseCompanyAvailability(); + app.UseLoginRateLimit(); + app.UseAuthorization(); app.UseAntiforgery(); - app.MapHealthEndpoints(); app.MapStaticAssets(); + app.MapSignOut(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); return app; } - // The KHAEMHAT_* variables of SPEC §6 that the host itself needs. The full validation (KhaemhatOptions) is M1. - private static void ApplyInstanceVariables(WebApplicationBuilder builder, string[] args) + // Host settings taken from the variables: listening addresses and log level. + private static void ApplyHostVariables(WebApplicationBuilder builder, KhaemhatOptions options, string[] args) { // KHAEMHAT_URLS wins over ASPNETCORE_HTTP_PORTS of the image; an explicit --urls argument wins over both. - var urls = builder.Configuration["KHAEMHAT_URLS"]; - if (!string.IsNullOrWhiteSpace(urls) && !args.Any(a => a.StartsWith("--urls", StringComparison.Ordinal))) + if (!string.IsNullOrWhiteSpace(options.Urls) && !args.Any(a => a.StartsWith("--urls", StringComparison.Ordinal))) { - builder.WebHost.UseUrls(urls); + builder.WebHost.UseUrls(options.Urls); } - var level = builder.Configuration["KHAEMHAT_LOG_LEVEL"]; - if (!string.IsNullOrWhiteSpace(level)) + if (!string.IsNullOrWhiteSpace(options.LogLevel) && Enum.TryParse(options.LogLevel, ignoreCase: true, out var level)) { - if (!Enum.TryParse(level, ignoreCase: true, out var parsed) || !Enum.IsDefined(parsed)) - { - throw new InvalidOperationException( - $"KHAEMHAT_LOG_LEVEL '{level}' is not valid: use Trace, Debug, Information, Warning, Error, Critical or None."); - } - - builder.Configuration["Logging:LogLevel:Default"] = parsed.ToString(); + builder.Configuration["Logging:LogLevel:Default"] = level.ToString(); } } + + // POST /logout: closes the session and removes the cookie; a form with the antiforgery token posts here. + private static void MapSignOut(this IEndpointRouteBuilder endpoints) => + endpoints.MapPost("/logout", async (HttpContext context, SignInService signIn, IAntiforgery antiforgery) => + { + if (!await antiforgery.IsRequestValidAsync(context).ConfigureAwait(false)) + { + return Results.BadRequest(); + } + + await signIn.SignOutAsync(SessionCookie.Read(context), context.RequestAborted).ConfigureAwait(false); + SessionCookie.Clear(context); + return Results.Redirect("/login"); + }); } diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs new file mode 100644 index 0000000..a92b649 --- /dev/null +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -0,0 +1,141 @@ +using Khaemhat.Application.Audit; +using Khaemhat.Application.Configuration; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Jobs; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Notifications; +using Khaemhat.Application.Security; +using Khaemhat.Core.Caching; +using Khaemhat.Core.Logging; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Execution; +using Khaemhat.Data.Mapping; +using Khaemhat.Data.Migrations; +using Khaemhat.Data.PostgreSql; +using Khaemhat.Data.Sqlite; +using Khaemhat.Infrastructure.Caching; +using Khaemhat.Infrastructure.Licensing; +using Khaemhat.Infrastructure.Logging; +using Khaemhat.Infrastructure.Security; +using Khaemhat.Web.Security; + +namespace Khaemhat.Web.Hosting; + +/// +/// The composition of the instance (SPEC §3): data access on the configured databases, security, licences, log and +/// the start sequence. Services are singletons: they hold no per-request state and open a unit of work per call. +/// +internal static class KhaemhatServices +{ + /// Registers every service of the instance. + /// The container. + /// The validated variables. + /// The database log queue, already plugged into the logging pipeline. + /// The container. + public static IServiceCollection AddKhaemhat(this IServiceCollection services, KhaemhatOptions options, DbLogSink logSink) + { + var dataAssembly = typeof(CompanyRegistry).Assembly; + services.AddSingleton(options); + services.AddSingleton(logSink); + services.AddSingleton(TimeProvider.System); + services.AddSingleton(); + services.AddHttpContextAccessor(); + services.AddSingleton(); + + // Secrets and data access. + services.AddSingleton(SecretKey.FromBase64(options.SecretKey!)); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(new DbProviderCatalog(new SqliteProvider(), new PostgresProvider())); + services.AddSingleton(new MapRegistry().AddFromAssembly(dataAssembly)); + services.AddSingleton(sp => + { + var slow = sp.GetRequiredService().CreateLogger("Khaemhat.Performance.SlowQueries"); + var user = sp.GetRequiredService(); + return new DataAccessContext(sp.GetRequiredService(), user.Get) + { + SlowQueryObserver = query => + { + using var section = slow.BeginScope(LogSections.Scope(LogSection.Performance)); + slow.LogWarning( + "Slow query on {Database}: {Milliseconds} ms. {Sql}", + query.Database, (long)query.Duration.TotalMilliseconds, query.Sql.Length > 2000 ? query.Sql[..2000] : query.Sql); + }, + }; + }); + services.AddSingleton(sp => sp.GetRequiredService().Resolve(options.SystemDatabase)); + services.AddSingleton(sp => new CompanyRegistry( + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService())); + services.AddSingleton(sp => new DatabaseLocator(sp.GetRequiredService(), sp.GetRequiredService())); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(new InstanceDatabases( + options.SystemDatabase, options.CompanyServer, MigrationCatalog.ForSystem(dataAssembly), MigrationCatalog.ForCompany(dataAssembly))); + + // Cache: in memory, or on Redis when KHAEMHAT_REDIS is set (falling back to memory while Redis is down). + if (options.Redis is { } redis) + { + services.AddSingleton(new RedisClient(RedisEndpoint.Parse(redis))); + services.AddSingleton(sp => new RedisCacheProvider( + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>())); + } + else + { + services.AddSingleton(sp => new MemoryCacheProvider(sp.GetRequiredService())); + } + + // Security. + services.AddSingleton(new SecurityPolicyOptions()); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(ModuleRegistry.Default); + services.AddSingleton(LicenseVerifier.Product); + services.AddSingleton(new LicenseSettings(options.License, options.Mode)); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + // Companies and start. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddSingleton(sp => new StartupOrchestrator( + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService(), + logSink, sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService>())); + services.AddHostedService(); + + // History of the records and scheduled tasks. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(); + return services; + } +} + +/// The user name written in the audit columns: the signed-in user of the current request, else system. +/// The current request. +internal sealed class CurrentUserName(IHttpContextAccessor accessor) +{ + /// The name. + /// The user name, or outside requests. + public string? Get() => accessor.HttpContext?.User.Identity is { IsAuthenticated: true, Name: { } name } ? name : null; +} diff --git a/src/Khaemhat.Web/Hosting/Middleware.cs b/src/Khaemhat.Web/Hosting/Middleware.cs new file mode 100644 index 0000000..d6dffbd --- /dev/null +++ b/src/Khaemhat.Web/Hosting/Middleware.cs @@ -0,0 +1,186 @@ +using System.Diagnostics; +using System.Net; +using System.Threading.RateLimiting; +using Khaemhat.Application.Instance; +using Khaemhat.Core.Logging; +using Khaemhat.Web.Security; + +namespace Khaemhat.Web.Hosting; + +/// The middleware of the instance, in pipeline order. +internal static class KhaemhatMiddleware +{ + /// + /// Security headers on every response (SPEC §7.3): a content security policy without inline scripts, no framing, + /// no MIME sniffing, no referrer outside the site. + /// + /// The application. + /// The application. + public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app) => app.Use(async (context, next) => + { + context.Response.OnStarting(() => + { + var headers = context.Response.Headers; + headers.ContentSecurityPolicy = + "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; " + + "connect-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; object-src 'none'"; + headers.XContentTypeOptions = "nosniff"; + headers.XFrameOptions = "DENY"; + headers["Referrer-Policy"] = "same-origin"; + headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=()"; + headers["Cross-Origin-Opener-Policy"] = "same-origin"; + return Task.CompletedTask; + }); + await next(context).ConfigureAwait(false); + }); + + /// + /// While the start sequence runs (migrations), every request except health checks and static files gets a 503 page + /// that refreshes itself. + /// + /// The application. + /// The application. + public static IApplicationBuilder UseStartingPage(this IApplicationBuilder app) => app.Use(async (context, next) => + { + var state = context.RequestServices.GetRequiredService(); + var path = context.Request.Path; + if (state.IsReady || path.StartsWithSegments("/health") || Path.HasExtension(path.Value) || path.StartsWithSegments("/_framework")) + { + await next(context).ConfigureAwait(false); + return; + } + + var message = state.Phase == BootstrapPhase.Failed + ? "Avvio non riuscito: controlla il log del container." + : "Avvio in corso: aggiornamento dei database. La pagina si ricarica da sola."; + await WriteUnavailablePageAsync(context, message, refreshSeconds: 5).ConfigureAwait(false); + }); + + /// + /// Company states (SPEC §5.4): a company in maintenance answers 503 to company accounts (the API with a JSON body, + /// pages with a notice), a disabled company to everybody; an API call whose X-Company names another company + /// than the account's own gets 403. Sign-in, health checks and static files are never blocked. + /// + /// The application. + /// The application. + public static IApplicationBuilder UseCompanyAvailability(this IApplicationBuilder app) => app.Use(async (context, next) => + { + var path = context.Request.Path; + var actor = SessionCookie.ActorOf(context.User); + if (actor is null || Path.HasExtension(path.Value) || path.StartsWithSegments("/_framework") || path.StartsWithSegments("/_blazor") + || path.StartsWithSegments("/health") || path.StartsWithSegments("/login") || path.StartsWithSegments("/logout")) + { + await next(context).ConfigureAwait(false); + return; + } + + var isApi = path.StartsWithSegments("/api"); + var resolver = context.RequestServices.GetRequiredService(); + var requested = isApi ? context.Request.Headers[CompanyContextResolver.Header].ToString() : null; + var result = await resolver.ResolveAsync(actor, requested, context.RequestAborted).ConfigureAwait(false); + var refused = isApi && result.Access is CompanyAccess.Forbidden or CompanyAccess.NotFound; + if (!result.IsUnavailable && !refused) + { + await next(context).ConfigureAwait(false); + return; + } + + if (isApi) + { + context.Response.StatusCode = result.IsUnavailable ? StatusCodes.Status503ServiceUnavailable + : result.Access == CompanyAccess.Forbidden ? StatusCodes.Status403Forbidden : StatusCodes.Status404NotFound; + if (result.IsUnavailable) + { + context.Response.Headers.RetryAfter = "60"; + } + + await context.Response.WriteAsJsonAsync(new { error = ErrorCode(result.Access) }, context.RequestAborted).ConfigureAwait(false); + return; + } + + var message = result.Access == CompanyAccess.Maintenance + ? "L'azienda è in manutenzione. Riprova tra qualche minuto." + : "L'azienda è disattivata. Rivolgiti all'amministratore."; + await WriteUnavailablePageAsync(context, message, refreshSeconds: result.Access == CompanyAccess.Maintenance ? 60 : null).ConfigureAwait(false); + }); + + /// + /// Puts trace identifier, request, user and company in the logging scope of the request (SPEC §9.5: one trace + /// identifier follows the request across the log) and returns the identifier in X-Trace-Id. + /// + /// The application. + /// The application. + public static IApplicationBuilder UseLogScope(this IApplicationBuilder app) => app.Use(async (context, next) => + { + var traceId = Activity.Current?.TraceId.ToString() ?? context.TraceIdentifier; + context.Response.Headers["X-Trace-Id"] = traceId; + var logger = context.RequestServices.GetRequiredService().CreateLogger("Khaemhat.Web.Requests"); + var actor = SessionCookie.ActorOf(context.User); + using var scope = logger.BeginScope(new Dictionary + { + [LogSections.TraceIdKey] = traceId, + [LogSections.RequestKey] = context.Request.Method + " " + context.Request.Path, + [LogSections.UserKey] = actor?.UserName, + [LogSections.CompanyKey] = actor?.CompanyCode, + }); + await next(context).ConfigureAwait(false); + }); + + /// + /// Limits sign-in attempts per client address (SPEC §7.3): 10 posts a minute on the login pages; beyond that 429. + /// Account lockout after 5 wrong passwords is separate and lives in the account. + /// + /// The application. + /// The application. + public static IApplicationBuilder UseLoginRateLimit(this IApplicationBuilder app) + { + var limiter = PartitionedRateLimiter.Create(context => + RateLimitPartition.GetFixedWindowLimiter( + context.Connection.RemoteIpAddress?.ToString() ?? "unknown", + _ => new FixedWindowRateLimiterOptions { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 })); + return app.Use(async (context, next) => + { + if (HttpMethods.IsPost(context.Request.Method) && context.Request.Path.StartsWithSegments("/login")) + { + using var lease = await limiter.AcquireAsync(context, 1, context.RequestAborted).ConfigureAwait(false); + if (!lease.IsAcquired) + { + context.Response.StatusCode = StatusCodes.Status429TooManyRequests; + context.Response.Headers.RetryAfter = "60"; + await context.Response.WriteAsync("Troppi tentativi di accesso: riprova tra un minuto.", context.RequestAborted).ConfigureAwait(false); + return; + } + } + + await next(context).ConfigureAwait(false); + }); + } + + private static string ErrorCode(CompanyAccess access) => access switch + { + CompanyAccess.Maintenance => "company_maintenance", + CompanyAccess.Disabled => "company_disabled", + CompanyAccess.Forbidden => "company_forbidden", + _ => "company_not_found", + }; + + private static Task WriteUnavailablePageAsync(HttpContext context, string message, int? refreshSeconds) + { + context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; + context.Response.ContentType = "text/html; charset=utf-8"; + var refresh = string.Empty; + if (refreshSeconds is { } seconds) + { + var text = seconds.ToString(System.Globalization.CultureInfo.InvariantCulture); + context.Response.Headers.RetryAfter = text; + refresh = ""; + } + + return context.Response.WriteAsync( + "" + refresh + + "Khaemhat
" + + "\"\"

Khaemhat

" + WebUtility.HtmlEncode(message) + + "

", + context.RequestAborted); + } +} diff --git a/src/Khaemhat.Web/Program.cs b/src/Khaemhat.Web/Program.cs index 0faaef6..9829d30 100644 --- a/src/Khaemhat.Web/Program.cs +++ b/src/Khaemhat.Web/Program.cs @@ -1,3 +1,27 @@ +using Khaemhat.Application.Configuration; using Khaemhat.Web.Hosting; -await KhaemhatApp.Build(args).RunAsync().ConfigureAwait(false); +try +{ + await KhaemhatApp.Build(args).RunAsync().ConfigureAwait(false); +} +catch (ConfigurationException ex) +{ + // A missing or wrong variable: every problem on stderr, no value printed, exit code 2 (SPEC §6). + await Console.Error.WriteLineAsync("Khaemhat cannot start, the configuration is not valid:").ConfigureAwait(false); + foreach (var error in ex.Errors) + { + await Console.Error.WriteLineAsync(" - " + error).ConfigureAwait(false); + } + + return 2; +} +catch (Exception ex) when (ex is not OperationCanceledException) +{ + // The start failed after the configuration was read (system database unreachable, migration refused): the log + // already has the details; the container restart policy decides what happens next. + await Console.Error.WriteLineAsync("Khaemhat stopped: " + ex.Message).ConfigureAwait(false); + return 1; +} + +return Environment.ExitCode; diff --git a/src/Khaemhat.Web/Security/Authorization.cs b/src/Khaemhat.Web/Security/Authorization.cs new file mode 100644 index 0000000..e1fba81 --- /dev/null +++ b/src/Khaemhat.Web/Security/Authorization.cs @@ -0,0 +1,120 @@ +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Core.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.Options; + +namespace Khaemhat.Web.Security; + +/// Requires a permission (SPEC §7.2), checked with the licence: [RequirePermission("sales.invoices.create")]. +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] +public sealed class RequirePermissionAttribute : AuthorizeAttribute +{ + /// Creates the attribute. + /// The permission code. + public RequirePermissionAttribute(string code) + : base(KhaemhatPolicies.PermissionPrefix + code) => Code = code; + + /// The permission code. + public string Code { get; } +} + +/// Requires a level: [RequireLevel(UserLevel.Administrator)] for instance administration. +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] +public sealed class RequireLevelAttribute : AuthorizeAttribute +{ + /// Creates the attribute. + /// The minimum level. + public RequireLevelAttribute(UserLevel level) + : base(KhaemhatPolicies.LevelPrefix + level) => Level = level; + + /// The minimum level. + public UserLevel Level { get; } +} + +/// Requires a licensed module: [RequireModule("CRM")]. +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] +public sealed class RequireModuleAttribute : AuthorizeAttribute +{ + /// Creates the attribute. + /// The module code. + public RequireModuleAttribute(string moduleCode) + : base(KhaemhatPolicies.ModulePrefix + moduleCode) => ModuleCode = moduleCode; + + /// The module code. + public string ModuleCode { get; } +} + +/// The policy names built from the attributes. +public static class KhaemhatPolicies +{ + /// Prefix of permission policies. + public const string PermissionPrefix = "perm:"; + + /// Prefix of level policies. + public const string LevelPrefix = "level:"; + + /// Prefix of module policies. + public const string ModulePrefix = "module:"; +} + +/// A requirement built from a policy name. +/// The prefix. +/// The permission, level or module. +internal sealed record KhaemhatRequirement(string Kind, string Value) : IAuthorizationRequirement; + +/// Builds the policies named by on demand; other names go to the default provider. +/// The authorization options. +internal sealed class KhaemhatPolicyProvider(IOptions options) : IAuthorizationPolicyProvider +{ + private readonly DefaultAuthorizationPolicyProvider _fallback = new(options); + + /// + public Task GetDefaultPolicyAsync() => _fallback.GetDefaultPolicyAsync(); + + /// + public Task GetFallbackPolicyAsync() => _fallback.GetFallbackPolicyAsync(); + + /// + public Task GetPolicyAsync(string policyName) + { + foreach (var prefix in (string[])[KhaemhatPolicies.PermissionPrefix, KhaemhatPolicies.LevelPrefix, KhaemhatPolicies.ModulePrefix]) + { + if (policyName.StartsWith(prefix, StringComparison.Ordinal)) + { + return Task.FromResult(new AuthorizationPolicyBuilder(SessionCookie.Scheme) + .RequireAuthenticatedUser() + .AddRequirements(new KhaemhatRequirement(prefix, policyName[prefix.Length..])) + .Build()); + } + } + + return _fallback.GetPolicyAsync(policyName); + } +} + +/// Evaluates with the permission service and the licence. +/// The permissions. +/// The licence. +internal sealed class KhaemhatAuthorizationHandler(PermissionService permissions, ILicenseGate licenses) : AuthorizationHandler +{ + /// + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, KhaemhatRequirement requirement) + { + if (SessionCookie.ActorOf(context.User) is not { } actor) + { + return; + } + + var allowed = requirement.Kind switch + { + KhaemhatPolicies.LevelPrefix => Enum.TryParse(requirement.Value, out var level) && actor.Level >= level, + KhaemhatPolicies.ModulePrefix => licenses.IsModuleActive(requirement.Value), + _ => (await permissions.CheckAsync(actor, requirement.Value).ConfigureAwait(false)).Allowed, + }; + if (allowed) + { + context.Succeed(requirement); + } + } +} diff --git a/src/Khaemhat.Web/Security/LoginFlow.cs b/src/Khaemhat.Web/Security/LoginFlow.cs new file mode 100644 index 0000000..e818c72 --- /dev/null +++ b/src/Khaemhat.Web/Security/LoginFlow.cs @@ -0,0 +1,70 @@ +using Khaemhat.Application.Security; +using Khaemhat.Core.Security; + +namespace Khaemhat.Web.Security; + +/// The pages of the sign-in flow and the messages shown for the error codes of . +public static class LoginFlow +{ + /// The login page (mockup 001). + public const string LoginPage = "/login"; + + /// The TOTP page (mockup 002). + public const string TotpPage = "/login/verifica"; + + /// The TOTP setup page. + public const string TotpSetupPage = "/login/configura-verifica"; + + /// The forced password change (mockup 003). + public const string PasswordChangePage = "/login/cambio-password"; + + /// Where a session in a state goes next. + /// The state reached. + /// Where the user wanted to go. + /// The local address. + public static string NextPage(SessionState? state, string? returnUrl) => state switch + { + SessionState.PendingTotp => TotpPage + Carry(returnUrl), + SessionState.PendingTotpSetup => TotpSetupPage + Carry(returnUrl), + SessionState.PendingPasswordChange => PasswordChangePage + Carry(returnUrl), + SessionState.Active => SafeReturnUrl(returnUrl), + _ => LoginPage, + }; + + /// A return address only when it stays on this site. + /// The address asked for. + /// The address, or /. + public static string SafeReturnUrl(string? returnUrl) => + returnUrl is { Length: > 0 } url && url[0] == '/' && !url.StartsWith("//", StringComparison.Ordinal) && !url.StartsWith("/\\", StringComparison.Ordinal) + && !url.StartsWith("/login", StringComparison.OrdinalIgnoreCase) + ? url + : "/"; + + /// The Italian message of an error code (several codes may be joined by commas). + /// The code(s). + /// The messages. + public static IReadOnlyList Messages(string? error) => + string.IsNullOrEmpty(error) ? [] : [.. error.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(Message)]; + + private static string Message(string code) => code switch + { + SecurityErrors.InvalidCredentials => "Azienda, utente o password non corretti.", + SecurityErrors.AccountLocked => "Troppi tentativi non riusciti: l'account è bloccato per 15 minuti.", + SecurityErrors.AccountDisabled => "L'account è disattivato: rivolgiti all'amministratore.", + SecurityErrors.TemporaryPasswordExpired => "La password provvisoria è scaduta: chiedine una nuova all'amministratore.", + SecurityErrors.PasswordTooShort => "La nuova password è troppo corta: servono almeno 10 caratteri.", + SecurityErrors.PasswordTooSimple => "La nuova password deve contenere almeno tre tipi di carattere tra minuscole, maiuscole, cifre e simboli.", + SecurityErrors.PasswordContainsUserName => "La nuova password non può contenere il nome utente.", + SecurityErrors.PasswordReused => "La nuova password è uguale a una delle ultime cinque.", + SecurityErrors.CurrentPasswordWrong => "La password attuale non è corretta.", + SecurityErrors.TotpInvalid => "Codice non valido: controlla l'ora del telefono e riprova.", + SecurityErrors.RateLimited => "Troppi tentativi: riprova tra un minuto.", + SecurityErrors.ConcurrentUsersExceeded => "È stato raggiunto il numero massimo di utenti collegati previsto dalla licenza.", + SecurityErrors.CompanyUnavailable => "L'azienda è in manutenzione o non è disponibile.", + SecurityErrors.LicenseLimitReached => "La licenza non consente altri accessi di questo tipo.", + _ => "Accesso non riuscito.", + }; + + private static string Carry(string? returnUrl) => + SafeReturnUrl(returnUrl) is var url && url != "/" ? "?returnUrl=" + Uri.EscapeDataString(url) : string.Empty; +} diff --git a/src/Khaemhat.Web/Security/SessionAuthentication.cs b/src/Khaemhat.Web/Security/SessionAuthentication.cs new file mode 100644 index 0000000..811f04e --- /dev/null +++ b/src/Khaemhat.Web/Security/SessionAuthentication.cs @@ -0,0 +1,216 @@ +using System.Globalization; +using System.Security.Claims; +using System.Text.Encodings.Web; +using Khaemhat.Application.Configuration; +using Khaemhat.Application.Security; +using Khaemhat.Core.Security; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Components.Server; +using Microsoft.Extensions.Options; + +namespace Khaemhat.Web.Security; + +/// The session cookie and the claims built from it. +public static class SessionCookie +{ + /// The authentication scheme. + public const string Scheme = "KhaemhatSession"; + + /// The cookie name. + public const string Name = "khaemhat_session"; + + /// Claim: the session row. + public const string SessionIdClaim = "kh:session"; + + /// Claim: the database holding the account (_ for instance accounts). + public const string OwnerClaim = "kh:owner"; + + /// Claim: the account row. + public const string UserIdClaim = "kh:user"; + + /// Claim: the level. + public const string LevelClaim = "kh:level"; + + /// Claim: the company the session works in. + public const string CompanyClaim = "kh:company"; + + /// Claim: the linked company user of an administrator. + public const string LinkedUserClaim = "kh:linked"; + + /// Claim: the name shown. + public const string DisplayNameClaim = "kh:display"; + + /// Sets the cookie. + /// The request. + /// The cookie value. + /// Expiry for "remember me"; for a browser-session cookie. + public static void Write(HttpContext context, string value, DateTimeOffset? persistentUntil = null) + { + ArgumentNullException.ThrowIfNull(context); + context.Response.Cookies.Append(Name, value, Options(context, persistentUntil)); + } + + /// Removes the cookie. + /// The request. + public static void Clear(HttpContext context) + { + ArgumentNullException.ThrowIfNull(context); + context.Response.Cookies.Delete(Name, Options(context, null)); + } + + /// The cookie of the request. + /// The request. + /// The value, or . + public static string? Read(HttpContext context) => context?.Request.Cookies[Name]; + + /// The claims of a signed-in session. + /// The session. + /// The principal. + public static ClaimsPrincipal Principal(SessionIdentity identity) + { + ArgumentNullException.ThrowIfNull(identity); + var claims = new List + { + new(ClaimTypes.Name, identity.UserName), + new(DisplayNameClaim, identity.DisplayName), + new(SessionIdClaim, identity.SessionId.ToString(CultureInfo.InvariantCulture)), + new(OwnerClaim, identity.Owner.CompanyDatabase ?? "_"), + new(UserIdClaim, identity.Owner.UserId.ToString(CultureInfo.InvariantCulture)), + new(LevelClaim, identity.Level.ToString()), + }; + if (identity.CompanyCode is not null) + { + claims.Add(new Claim(CompanyClaim, identity.CompanyCode)); + } + + if (identity.LinkedUserId is { } linked) + { + claims.Add(new Claim(LinkedUserClaim, linked.ToString(CultureInfo.InvariantCulture))); + } + + return new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme, ClaimTypes.Name, LevelClaim)); + } + + /// The actor of a principal built by . + /// The principal. + /// The actor, or when not signed in. + public static Actor? ActorOf(ClaimsPrincipal? user) + { + if (user?.Identity is not { IsAuthenticated: true, Name: { } name } || OwnerOf(user) is not { } owner) + { + return null; + } + + var level = Enum.TryParse(user.FindFirst(LevelClaim)?.Value, out var parsed) ? parsed : UserLevel.Standard; + var company = user.FindFirst(CompanyClaim)?.Value; + var linked = long.TryParse(user.FindFirst(LinkedUserClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var l) ? l : (long?)null; + return owner.IsInstanceAccount + ? new Actor(name, level, owner.UserId, linked, company) + : new Actor(name, UserLevel.Standard, null, owner.UserId, company); + } + + /// The account of a principal. + /// The principal. + /// The owner, or . + public static SessionOwner? OwnerOf(ClaimsPrincipal? user) + { + var database = user?.FindFirst(OwnerClaim)?.Value; + return database is not null && long.TryParse(user!.FindFirst(UserIdClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var id) + ? new SessionOwner(database == "_" ? null : database, id) + : null; + } + + /// The session row of a principal. + /// The principal. + /// The session id, or . + public static long? SessionIdOf(ClaimsPrincipal? user) => + long.TryParse(user?.FindFirst(SessionIdClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var id) ? id : null; + + private static CookieOptions Options(HttpContext context, DateTimeOffset? persistentUntil) + { + var publicUrl = context.RequestServices.GetService()?.PublicUrl; + return new CookieOptions + { + HttpOnly = true, + IsEssential = true, + SameSite = SameSiteMode.Lax, + Path = "/", + Secure = context.Request.IsHttps || (publicUrl?.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ?? false), + Expires = persistentUntil, + }; + } +} + +/// +/// Authenticates requests with the session cookie (SPEC §7.3): only sessions that completed every sign-in step count; +/// a pending session (TOTP, password change) is handled by the login pages themselves. +/// +/// The scheme options. +/// The log factory. +/// The URL encoder. +/// Resolves sessions. +internal sealed class SessionAuthenticationHandler( + IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, SignInService signIn) + : AuthenticationHandler(options, logger, encoder) +{ + /// The key of the resolved identity in . + public const string IdentityItem = "kh:identity"; + + /// + protected override async Task HandleAuthenticateAsync() + { + var cookie = SessionCookie.Read(Context); + if (string.IsNullOrEmpty(cookie)) + { + return AuthenticateResult.NoResult(); + } + + var identity = await signIn.ResolveAsync(cookie, Context.RequestAborted).ConfigureAwait(false); + if (identity is null) + { + return AuthenticateResult.NoResult(); + } + + Context.Items[IdentityItem] = identity; + return identity.State == SessionState.Active + ? AuthenticateResult.Success(new AuthenticationTicket(SessionCookie.Principal(identity), SessionCookie.Scheme)) + : AuthenticateResult.NoResult(); + } + + /// + protected override Task HandleChallengeAsync(AuthenticationProperties properties) + { + var path = Request.Path + Request.QueryString; + Response.Redirect("/login" + (path.Length > 1 ? "?returnUrl=" + Uri.EscapeDataString(path) : string.Empty)); + return Task.CompletedTask; + } + + /// + protected override Task HandleForbiddenAsync(AuthenticationProperties properties) + { + Response.Redirect("/accesso-negato"); + return Task.CompletedTask; + } +} + +/// +/// Checks every minute that the session behind an open Blazor circuit is still valid: a revoked or expired session +/// (sign-out elsewhere, maintenance, disabled account) ends the circuit's authentication. +/// +/// The log factory. +/// The sessions. +internal sealed class SessionRevalidatingStateProvider(ILoggerFactory loggerFactory, SessionStore sessions) + : RevalidatingServerAuthenticationStateProvider(loggerFactory) +{ + /// + protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1); + + /// + protected override async Task ValidateAuthenticationStateAsync(AuthenticationState authenticationState, CancellationToken cancellationToken) + { + var user = authenticationState.User; + return SessionCookie.OwnerOf(user) is { } owner && SessionCookie.SessionIdOf(user) is { } id + && await sessions.IsActiveAsync(owner, id, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Web/Security/WebCompanyContext.cs b/src/Khaemhat.Web/Security/WebCompanyContext.cs new file mode 100644 index 0000000..aac3b9a --- /dev/null +++ b/src/Khaemhat.Web/Security/WebCompanyContext.cs @@ -0,0 +1,46 @@ +using System.Security.Claims; +using Khaemhat.Application.Instance; +using Microsoft.AspNetCore.Components.Authorization; + +namespace Khaemhat.Web.Security; + +/// +/// The company of a Blazor circuit or of an HTTP request: the user comes from the authentication state of the circuit, +/// or from the request outside circuits, where an API call may also name the company in X-Company. +/// +/// The authentication state of the circuit. +/// The current request, outside circuits. +/// The rules. +internal sealed class WebCompanyContext(AuthenticationStateProvider authentication, IHttpContextAccessor http, CompanyContextResolver resolver) : ICompanyContext +{ + private CompanyContextResult? _result; + + /// + public async ValueTask GetAsync(CancellationToken cancellationToken = default) + { + if (_result is not null) + { + return _result; + } + + ClaimsPrincipal? user; + string? requested = null; + try + { + user = (await authentication.GetAuthenticationStateAsync().ConfigureAwait(false)).User; + } + catch (InvalidOperationException) + { + // Outside a circuit the authentication state is not set: use the request. + var context = http.HttpContext; + user = context?.User; + if (context?.Request.Path.StartsWithSegments("/api") == true) + { + requested = context.Request.Headers[CompanyContextResolver.Header].ToString(); + } + } + + _result = await resolver.ResolveAsync(SessionCookie.ActorOf(user), requested, cancellationToken).ConfigureAwait(false); + return _result; + } +} diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index ec67893..bf09e1c 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -29,3 +29,54 @@ body { font-family: var(--kh-font); font-size: 13px; background: var(--kh-bg); - #blazor-error-ui { background: #FADEDC; color: #1E2733; bottom: 0; box-shadow: 0 -1px 2px rgba(0, 0, 0, .2); display: none; left: 0; padding: .6rem 1.25rem .7rem 1.25rem; position: fixed; width: 100%; z-index: 1000; } #blazor-error-ui .dismiss { cursor: pointer; position: absolute; right: .75rem; top: .5rem; } + +/* Sign-in pages (mockups 001-003): brand panel on the left, form card on the right. */ +.kh-auth { min-height: 100vh; display: grid; grid-template-columns: minmax(320px, 52%) 1fr; color: #1E2733; } +.kh-auth .brand { display: flex; flex-direction: column; justify-content: space-between; padding: 48px 44px 36px; color: #E8EDF5; + background: radial-gradient(1100px 620px at 15% 0%, #243A5E 0%, #17243A 55%, #0F1826 100%); } +.kh-auth .brand .mark { border-radius: 14px; box-shadow: 0 10px 30px rgba(0, 0, 0, .35); } +.kh-auth .brand h2 { font-size: 30px; letter-spacing: -.5px; margin: 18px 0 10px; font-weight: 650; } +.kh-auth .brand p { max-width: 460px; color: #B8C5DA; font-size: 14px; line-height: 1.5; margin: 0; } +.kh-auth .features { list-style: none; margin: 32px 0 0; padding: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +.kh-auth .features li { padding: 10px 12px; border-radius: 8px; font-size: 11.5px; color: #B8C5DA; line-height: 1.4; + background: rgba(255, 255, 255, .05); border: 1px solid rgba(255, 255, 255, .09); } +.kh-auth .features strong { display: block; color: #E8EDF5; font-weight: 600; margin-bottom: 2px; } +.kh-auth .panel { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 32px 24px; background: var(--kh-bg); } +.kh-auth .card { width: 100%; max-width: 380px; } +.kh-auth h1 { font-size: 20px; margin: 0 0 4px; font-weight: 650; } +.kh-auth .sub { color: #5B6776; margin: 0 0 18px; line-height: 1.45; } +.kh-auth footer { margin-top: 28px; font-size: 11.5px; color: #8A95A3; } +.kh-auth footer a { color: #1F5FA8; text-decoration: none; } + +.kh-form { display: flex; flex-direction: column; gap: 4px; } +.kh-form label { font-size: 11.5px; font-weight: 600; color: #5B6776; margin-top: 8px; } +.kh-form input[type=text], .kh-form input[type=password], .kh-form input:not([type]), .kh-form select { + height: 32px; padding: 0 10px; border: 1px solid #C5CDD7; border-radius: 6px; background: #FFF; font: inherit; color: inherit; } +.kh-form input:focus, .kh-form select:focus { outline: 2px solid #1F5FA8; outline-offset: -1px; border-color: #1F5FA8; } +.kh-form .check { display: flex; align-items: center; gap: 8px; font-weight: 400; color: #1E2733; margin-top: 12px; } +.kh-form .otp { height: 44px; font-size: 22px; letter-spacing: 8px; text-align: center; font-variant-numeric: tabular-nums; } +.kh-form .row { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 12px; } +.kh-form .row .kh-btn { margin-top: 0; } +.kh-form .hint { font-size: 11.5px; color: #8A95A3; } +.kh-btn { display: inline-flex; align-items: center; justify-content: center; height: 32px; padding: 0 14px; margin-top: 16px; border-radius: 6px; + border: 1px solid transparent; font: inherit; font-weight: 600; cursor: pointer; text-decoration: none; } +.kh-btn.primary { background: #1F5FA8; color: #FFF; align-self: flex-start; } +.kh-btn.primary:hover { background: #174A85; } +.kh-btn.ghost { background: transparent; color: #F0C86A; border-color: rgba(240, 200, 106, .5); } +.kh-alert { padding: 10px 12px; border-radius: 6px; margin: 12px 0; line-height: 1.45; font-size: 12.5px; } +.kh-alert.err { background: #FADEDC; color: #9E362D; } +.kh-alert.warn { background: #FBEFD9; color: #8B5511; margin-top: 20px; } +.kh-alert.info { background: #E3ECF8; color: #174A85; margin-top: 20px; } +.kh-rules { margin: 10px 0 0; padding-left: 18px; color: #5B6776; font-size: 11.5px; line-height: 1.6; } +.kh-secret { margin: 0 0 6px; } +.kh-secret dt { font-size: 11.5px; font-weight: 600; color: #5B6776; margin-top: 8px; } +.kh-secret dd { margin: 4px 0 0; } +.kh-secret code { font-size: 15px; letter-spacing: 1px; word-break: break-all; } +.kh-codes { list-style: none; padding: 0; margin: 0 0 8px; display: grid; grid-template-columns: 1fr 1fr; gap: 6px; } +.kh-codes code { display: block; padding: 6px 8px; background: #FFF; border: 1px solid #DDE3EA; border-radius: 6px; text-align: center; font-size: 14px; } + +@media (max-width: 760px) { + .kh-auth { grid-template-columns: 1fr; } + .kh-auth .brand { padding: 24px; } + .kh-auth .features { display: none; } +} diff --git a/tests/Khaemhat.Application.Tests/SystemRulesTests.cs b/tests/Khaemhat.Application.Tests/SystemRulesTests.cs new file mode 100644 index 0000000..6c463cd --- /dev/null +++ b/tests/Khaemhat.Application.Tests/SystemRulesTests.cs @@ -0,0 +1,147 @@ +using System.Security.Cryptography; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Configuration; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Companies; + +namespace Khaemhat.Application.Tests; + +/// Configuration, password policy, company context and record history (SPEC §5, §6, §7). +[TestClass] +public sealed class SystemRulesTests +{ + private static readonly string Key = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); + + [TestMethod] + public void Configuration_ReadsSecretsFromFiles() + { + var variables = Required(); + variables.Remove("KHAEMHAT_SECRET_KEY"); + variables["KHAEMHAT_SECRET_KEY_FILE"] = "/run/secrets/key"; + var reader = new EnvironmentConfigurationReader(n => variables.GetValueOrDefault(n), path => path == "/run/secrets/key" ? Key + "\n" : throw new IOException()); + + var options = reader.Read(); + options.EnsureValid(); + + Assert.AreEqual(Key, options.SecretKey); + } + + [TestMethod] + public void Configuration_RefusesAValueAndItsFileTogether_AndUnreadableFiles() + { + var variables = Required(); + variables["KHAEMHAT_SECRET_KEY_FILE"] = "/run/secrets/key"; + variables["KHAEMHAT_SUPERUSER_PASSWORD_FILE"] = "/missing"; + var reader = new EnvironmentConfigurationReader(n => variables.GetValueOrDefault(n), path => path == "/run/secrets/key" ? Key : throw new FileNotFoundException()); + + var error = Assert.ThrowsExactly(() => reader.Read().EnsureValid()); + + Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_SECRET_KEY and KHAEMHAT_SECRET_KEY_FILE", StringComparison.Ordinal))); + Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_SUPERUSER_PASSWORD_FILE", StringComparison.Ordinal))); + Assert.IsFalse(error.Errors.Any(e => e.Contains(Key, StringComparison.Ordinal)), "Errors never repeat a secret."); + } + + [TestMethod] + public void Configuration_ReportsEveryMissingVariableAtOnce() + { + var error = Assert.ThrowsExactly(() => new EnvironmentConfigurationReader(_ => null).Read().EnsureValid()); + + Assert.IsTrue(error.Errors.Count >= 2); + Assert.IsTrue(error.Errors.Any(e => e.StartsWith("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal))); + Assert.IsTrue(error.Errors.Any(e => e.StartsWith("KHAEMHAT_SECRET_KEY", StringComparison.Ordinal))); + } + + [TestMethod] + [DataRow("Corta-1", "password_too_short")] + [DataRow("sololettereminuscole", "password_too_simple")] + [DataRow("Mario.Rossi-2026", "password_contains_user_name")] + public void PasswordPolicy_RefusesWeakPasswords(string password, string error) => + CollectionAssert.Contains(new PasswordPolicy(new SecurityPolicyOptions()).Check(password, "mario.rossi").ToList(), error); + + [TestMethod] + public void PasswordPolicy_AcceptsAGoodPassword() => + Assert.AreEqual(0, new PasswordPolicy(new SecurityPolicyOptions()).Check("Granaio-di-Tebe-57", "mario.rossi").Count); + + [TestMethod] + public async Task CompanyContext_CompanyAccountsStayInTheirCompany() + { + var resolver = new CompanyContextResolver(new FakeRegistry(("A", CompanyStatus.Active), ("B", CompanyStatus.Active))); + var user = new Actor("mario", UserLevel.Standard, null, 7, "A"); + + Assert.AreEqual("A", (await resolver.ResolveAsync(user, null)).Code); + Assert.AreEqual("A", (await resolver.ResolveAsync(user, "a")).Code); + Assert.AreEqual(CompanyAccess.Forbidden, (await resolver.ResolveAsync(user, "B")).Access); + Assert.AreEqual(CompanyAccess.None, (await resolver.ResolveAsync(null, "A")).Access); + } + + [TestMethod] + public async Task CompanyContext_InstanceAccountsChooseTheCompany() + { + var resolver = new CompanyContextResolver(new FakeRegistry(("A", CompanyStatus.Active), ("B", CompanyStatus.Maintenance), ("C", CompanyStatus.Disabled))); + var admin = new Actor("root", UserLevel.SuperUser, 1, null, "A"); + + Assert.AreEqual("A", (await resolver.ResolveAsync(admin, null)).Code); + Assert.AreEqual("B", (await resolver.ResolveAsync(admin, "B")).Code); + Assert.AreEqual(CompanyAccess.Disabled, (await resolver.ResolveAsync(admin, "C")).Access); + Assert.AreEqual(CompanyAccess.NotFound, (await resolver.ResolveAsync(admin, "Z")).Access); + Assert.AreEqual(CompanyAccess.None, (await resolver.ResolveAsync(admin with { CompanyCode = null }, null)).Access); + } + + [TestMethod] + public async Task CompanyContext_MaintenanceIsClosedToCompanyAccounts_ReadOnlyIsFlagged() + { + var resolver = new CompanyContextResolver(new FakeRegistry(("B", CompanyStatus.Maintenance), ("R", CompanyStatus.ReadOnly))); + + var maintenance = await resolver.ResolveAsync(new Actor("mario", UserLevel.Standard, null, 7, "B"), null); + var readOnly = await resolver.ResolveAsync(new Actor("anna", UserLevel.Standard, null, 8, "R"), null); + + Assert.IsTrue(maintenance.IsUnavailable); + Assert.ThrowsExactly(() => maintenance.Scope()); + Assert.AreEqual(CompanyAccess.Granted, readOnly.Access); + Assert.IsTrue(readOnly.IsReadOnly); + Assert.AreEqual(DatabaseScope.Company("R"), readOnly.Scope()); + } + + [TestMethod] + public void AuditDiff_ListsOnlyChangedFields_AndNeverSecrets() + { + var before = new Role { Code = "VEND", Name = "Vendite", Description = null, CreatedBy = "a" }; + var after = new Role { Code = "VEND", Name = "Vendite Italia", Description = "Rete", CreatedBy = "b" }; + + var diff = AuditTrail.Diff(before, after); + + CollectionAssert.AreEquivalent(new[] { "Description", "Name" }, diff.Keys.ToArray()); + CollectionAssert.AreEqual(new object?[] { "Vendite", "Vendite Italia" }, diff["Name"]); + Assert.IsFalse(AuditTrail.Diff(new CompanyUser { PasswordHash = "x" }, new CompanyUser { PasswordHash = "y" }).ContainsKey("PasswordHash")); + Assert.IsTrue(AuditTrail.Diff(null, after).ContainsKey("Code")); + } + + private static Dictionary Required() => new(StringComparer.Ordinal) + { + ["KHAEMHAT_SYSTEM_DB"] = "sqlite://memory/config", + ["KHAEMHAT_SECRET_KEY"] = Key, + ["KHAEMHAT_DATA_DIR"] = Path.GetFullPath(Path.GetTempPath()), + ["KHAEMHAT_SUPERUSER"] = "root", + ["KHAEMHAT_SUPERUSER_PASSWORD"] = "Test-Password-2026", + }; + + private sealed class FakeRegistry(params (string Code, CompanyStatus Status)[] companies) : ICompanyRegistry + { + private readonly List _companies = [.. companies.Select((c, i) => new Company { Id = i + 1, Code = c.Code, Name = c.Code, Status = c.Status })]; + + public Task> ListAsync(CancellationToken cancellationToken = default) => Task.FromResult>(_companies); + + public Task FindAsync(string code, CancellationToken cancellationToken = default) => + Task.FromResult(_companies.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase))); + + public Task RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ResolveAsync(string code, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } +} diff --git a/tests/Khaemhat.Core.Tests/Common/CronExpressionTests.cs b/tests/Khaemhat.Core.Tests/Common/CronExpressionTests.cs new file mode 100644 index 0000000..7ba25a2 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Common/CronExpressionTests.cs @@ -0,0 +1,77 @@ +using Khaemhat.Core.Logging; +using Khaemhat.Core.Scheduling; + +namespace Khaemhat.Core.Tests.Common; + +/// The five-field cron of the scheduled tasks (SPEC §9.6) and the log sections (SPEC §9.5). +[TestClass] +public sealed class CronExpressionTests +{ + private static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); + + [TestMethod] + [DataRow("15 * * * *", "2026-11-11T10:20:00Z", "2026-11-11T11:15:00Z")] + [DataRow("*/10 * * * *", "2026-11-11T10:20:00Z", "2026-11-11T10:30:00Z")] + [DataRow("0 9-17/4 * * *", "2026-11-11T10:00:00Z", "2026-11-11T13:00:00Z")] + [DataRow("30 3 1,15 * *", "2026-11-11T00:00:00Z", "2026-11-15T03:30:00Z")] + [DataRow("0 0 * * 7", "2026-11-11T00:00:00Z", "2026-11-15T00:00:00Z")] + [DataRow("0 0 29 2 *", "2026-03-01T00:00:00Z", "2028-02-29T00:00:00Z")] + public void NextAfter_InUtc(string cron, string after, string expected) + { + var next = CronExpression.Parse(cron).NextAfter(DateTime.Parse(after, null, System.Globalization.DateTimeStyles.AdjustToUniversal), TimeZoneInfo.Utc); + + Assert.AreEqual(DateTime.Parse(expected, null, System.Globalization.DateTimeStyles.AdjustToUniversal), next); + } + + [TestMethod] + public void DayOfMonthAndDayOfWeek_MatchEither() + { + // The 13th or any Friday: after Wednesday 11 November 2026 comes Friday the 13th, then Friday the 20th. + var cron = CronExpression.Parse("0 12 13 * 5"); + var first = cron.NextAfter(new DateTime(2026, 11, 11, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Utc); + var second = cron.NextAfter(first!.Value, TimeZoneInfo.Utc); + + Assert.AreEqual(new DateTime(2026, 11, 13, 12, 0, 0, DateTimeKind.Utc), first); + Assert.AreEqual(new DateTime(2026, 11, 20, 12, 0, 0, DateTimeKind.Utc), second); + } + + [TestMethod] + public void LocalTimes_FollowTheTimeZone_AndSkipTheMissingHour() + { + var cron = CronExpression.Parse("30 2 * * *"); + + // 29 March 2026: in Rome clocks jump from 02:00 to 03:00, so 02:30 does not exist that night. + var spring = cron.NextAfter(new DateTime(2026, 3, 28, 12, 0, 0, DateTimeKind.Utc), Rome); + Assert.AreEqual(new DateTime(2026, 3, 30, 0, 30, 0, DateTimeKind.Utc), spring); + + // In winter Rome is UTC+1. + var winter = cron.NextAfter(new DateTime(2026, 11, 11, 12, 0, 0, DateTimeKind.Utc), Rome); + Assert.AreEqual(new DateTime(2026, 11, 12, 1, 30, 0, DateTimeKind.Utc), winter); + } + + [TestMethod] + [DataRow("")] + [DataRow("* * * *")] + [DataRow("60 * * * *")] + [DataRow("* 24 * * *")] + [DataRow("* * 0 * *")] + [DataRow("* * * 13 *")] + [DataRow("* * * * 8")] + [DataRow("*/0 * * * *")] + [DataRow("a * * * *")] + public void InvalidExpressions_AreRefused(string text) + { + Assert.IsFalse(CronExpression.TryParse(text, out _, out var error)); + Assert.IsFalse(string.IsNullOrEmpty(error)); + } + + [TestMethod] + public void LogSections_ComeFromTheCategory() + { + Assert.AreEqual(LogSection.Migrations, LogSections.FromCategory("Khaemhat.Data.Migrations.MigrationRunner")); + Assert.AreEqual("Sistema", LogSections.Label(LogSection.System)); + Assert.AreEqual(LogSection.Authentication, LogSections.FromCategory("Khaemhat.Application.Security.SignInService")); + Assert.AreEqual(LogSection.ScheduledJobs, LogSections.FromCategory("Khaemhat.Application.Jobs.JobScheduler")); + Assert.AreEqual("Performance", LogSections.Scope(LogSection.Performance).Single().Value); + } +} diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index 8c6fc90..9ef680f 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -63,11 +63,17 @@ public sealed class MappingTests } [TestMethod] - public void Registry_FindsTheSystemMaps() + public void Registry_FindsTheMapsOfBothDatabases() { var registry = new MapRegistry().AddFromAssembly(typeof(CompanyMap).Assembly); - CollectionAssert.AreEquivalent(new[] { "sys_companies", "sys_settings" }, registry.Maps.Select(m => m.Table).ToArray()); + string[] expected = + [ + "sys_companies", "sys_data_protection_keys", "sys_job_locks", "sys_job_runs", "sys_license_activations", "sys_licenses", "sys_log", + "sys_notifications", "sys_roles_templates", "sys_scheduled_tasks", "sys_security_audit", "sys_sessions", "sys_settings", "sys_users", + "audit_log", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "users", + ]; + CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray()); } [TestMethod] diff --git a/tests/Khaemhat.Data.Tests/MigrationTests.cs b/tests/Khaemhat.Data.Tests/MigrationTests.cs index 364c2d6..fca4a23 100644 --- a/tests/Khaemhat.Data.Tests/MigrationTests.cs +++ b/tests/Khaemhat.Data.Tests/MigrationTests.cs @@ -87,14 +87,17 @@ public sealed class MigrationTests } [TestMethod] - public void SystemMaps_AgreeWithTheMigratedSchema() + public void Maps_AgreeWithTheMigratedSchema() { - var model = MigrationCatalog.ForSystem().BuildModel(); + var systemModel = MigrationCatalog.ForSystem().BuildModel(); + var companyModel = MigrationCatalog.ForCompany().BuildModel(); var maps = new MapRegistry().AddFromAssembly(typeof(CompanyMap).Assembly); var problems = new List(); foreach (var map in maps.Maps) { + // System tables carry the sys_ prefix (SPEC 5.4); every other table lives in the company databases. + var model = map.Table.StartsWith("sys_", StringComparison.Ordinal) ? systemModel : companyModel; var table = model.Table(map.Table); if (table is null) { diff --git a/tests/Khaemhat.Infrastructure.Tests/RespTests.cs b/tests/Khaemhat.Infrastructure.Tests/RespTests.cs new file mode 100644 index 0000000..7c9f653 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/RespTests.cs @@ -0,0 +1,117 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; +using Khaemhat.Core.Caching; +using Khaemhat.Infrastructure.Caching; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Khaemhat.Infrastructure.Tests; + +/// The in-house Redis client (SPEC §9.3): protocol vectors, URL parsing and the fall back to memory. +[TestClass] +public sealed class RespTests +{ + [TestMethod] + public void Command_IsAnArrayOfBulkStrings() + { + var bytes = Resp.Command("SET", "kh:_:a", "\u00e8", "PX", 1500L); + + Assert.AreEqual("*5\r\n$3\r\nSET\r\n$6\r\nkh:_:a\r\n$2\r\n\u00e8\r\n$2\r\nPX\r\n$4\r\n1500\r\n", Encoding.UTF8.GetString(bytes)); + } + + [TestMethod] + public async Task Replies_OfEveryKind_AreRead() + { + var reader = Reader("+OK\r\n-ERR wrong\r\n:42\r\n$5\r\nhello\r\n$-1\r\n*2\r\n$1\r\na\r\n:7\r\n*-1\r\n$0\r\n\r\n"); + + Assert.AreEqual("OK", (await Resp.ReadAsync(reader)).Text); + var error = await Resp.ReadAsync(reader); + Assert.AreEqual(RespKind.Error, error.Kind); + Assert.AreEqual("ERR wrong", error.Text); + Assert.AreEqual(42, (await Resp.ReadAsync(reader)).Number); + Assert.AreEqual("hello", (await Resp.ReadAsync(reader)).Text); + Assert.AreEqual(RespKind.Null, (await Resp.ReadAsync(reader)).Kind); + var array = await Resp.ReadAsync(reader); + Assert.AreEqual(2, array.Items!.Count); + Assert.AreEqual("a", array.Items[0].Text); + Assert.AreEqual(7, array.Items[1].Number); + Assert.AreEqual(RespKind.Null, (await Resp.ReadAsync(reader)).Kind); + Assert.AreEqual(string.Empty, (await Resp.ReadAsync(reader)).Text); + } + + [TestMethod] + public async Task BulkStrings_MayContainLineBreaks_AndArriveInPieces() + { + var reader = new BufferedReader(new TrickleStream(Encoding.UTF8.GetBytes("$4\r\na\r\nb\r\n+OK\r\n"))); + + Assert.AreEqual("a\r\nb", (await Resp.ReadAsync(reader)).Text); + Assert.AreEqual("OK", (await Resp.ReadAsync(reader)).Text); + } + + [TestMethod] + public async Task AClosedConnection_IsAnIoError() + { + await Assert.ThrowsExactlyAsync(() => Resp.ReadAsync(Reader("$10\r\nabc"))); + } + + [TestMethod] + public void Endpoint_ReadsTheUrl_AndHidesThePassword() + { + var endpoint = RedisEndpoint.Parse("rediss://cache:s%40cret@redis.local:6380/2"); + + Assert.AreEqual("redis.local", endpoint.Host); + Assert.AreEqual(6380, endpoint.Port); + Assert.IsTrue(endpoint.UseTls); + Assert.AreEqual("cache", endpoint.User); + Assert.AreEqual("s@cret", endpoint.Password); + Assert.AreEqual(2, endpoint.Database); + Assert.AreEqual("rediss://***@redis.local:6380/2", endpoint.ToString()); + + var plain = RedisEndpoint.Parse("redis://:pw@localhost"); + Assert.IsNull(plain.User); + Assert.AreEqual("pw", plain.Password); + Assert.AreEqual(6379, plain.Port); + Assert.AreEqual(0, plain.Database); + } + + [TestMethod] + [DataRow("http://localhost")] + [DataRow("redis://localhost/abc")] + [DataRow("not a url")] + public void Endpoint_RefusesOtherUrls(string url) => Assert.ThrowsExactly(() => RedisEndpoint.Parse(url)); + + [TestMethod] + public void Pattern_EscapesGlobCharacters() => + Assert.AreEqual(@"kh:A\*B:\[x\]:", RedisCacheProvider.EscapePattern("kh:A*B:[x]:")); + + [TestMethod] + public async Task UnreachableRedis_FallsBackToMemory() + { + // A port nobody listens on: bind a listener, take its port, close it. + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + await using var cache = new RedisCacheProvider( + new RedisClient(RedisEndpoint.Parse("redis://127.0.0.1:" + port)) { Timeout = TimeSpan.FromSeconds(1) }, + TimeProvider.System, NullLogger.Instance); + var key = CacheKeys.For("A", "test", "x"); + + await cache.SetAsync(key, 41, TimeSpan.FromMinutes(1)); + var value = await cache.GetOrCreateAsync(key, _ => ValueTask.FromResult(0), TimeSpan.FromMinutes(1)); + + Assert.AreEqual(41, value); + Assert.IsFalse(cache.IsDistributed); + await cache.RemoveByPrefixAsync(CacheKeys.Prefix("A", "test")); + Assert.AreEqual(0, await cache.GetAsync(key)); + } + + private static BufferedReader Reader(string text) => new(new MemoryStream(Encoding.UTF8.GetBytes(text))); + + /// Returns one byte per read, as a slow network would. + private sealed class TrickleStream(byte[] data) : MemoryStream(data) + { + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + base.ReadAsync(buffer[..Math.Min(1, buffer.Length)], cancellationToken); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/SecurityPrimitivesTests.cs b/tests/Khaemhat.Infrastructure.Tests/SecurityPrimitivesTests.cs new file mode 100644 index 0000000..0b446e1 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/SecurityPrimitivesTests.cs @@ -0,0 +1,91 @@ +using System.Security.Cryptography; +using System.Text; +using Khaemhat.Infrastructure.Licensing; +using Khaemhat.Infrastructure.Security; + +namespace Khaemhat.Infrastructure.Tests; + +/// TOTP (RFC 6238), password hashes and signed licences (SPEC §7, §8). +[TestClass] +public sealed class SecurityPrimitivesTests +{ + private static readonly byte[] RfcSecret = Encoding.ASCII.GetBytes("12345678901234567890"); + + [TestMethod] + [DataRow(59L, "287082")] + [DataRow(1111111109L, "081804")] + [DataRow(1234567890L, "005924")] + [DataRow(2000000000L, "279037")] + public void Totp_MatchesTheRfc6238Vectors(long unixSeconds, string expected) => + Assert.AreEqual(expected, TotpGenerator.Compute(RfcSecret, TotpGenerator.StepOf(DateTimeOffset.FromUnixTimeSeconds(unixSeconds)))); + + [TestMethod] + public void Totp_AcceptsOneStepOfDrift_AndNeverTheSameCodeTwice() + { + var secret = Base32.Encode(RfcSecret); + var now = DateTimeOffset.FromUnixTimeSeconds(1111111109); + var previous = TotpGenerator.Compute(RfcSecret, TotpGenerator.StepOf(now) - 1); + + var step = TotpGenerator.Verify(secret, previous, now, lastUsedStep: null); + + Assert.AreEqual(TotpGenerator.StepOf(now) - 1, step); + Assert.IsNull(TotpGenerator.Verify(secret, previous, now, lastUsedStep: step)); + Assert.IsNull(TotpGenerator.Verify(secret, "12345", now, null)); + Assert.IsNull(TotpGenerator.Verify(secret, "abcdef", now, null)); + } + + [TestMethod] + public void Base32_RoundTrips() + { + var data = RandomNumberGenerator.GetBytes(20); + + CollectionAssert.AreEqual(data, Base32.Decode(Base32.Encode(data))); + Assert.AreEqual("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", Base32.Encode(RfcSecret)); + } + + [TestMethod] + public void Licence_SignedWithTheKey_IsValid_AndAnyChangeBreaksIt() + { + var (privatePem, publicKey) = LicenseSigner.CreateKeyPair(); + using var key = ECDsa.Create(); + key.ImportFromPem(privatePem); + var document = new LicenseDocument + { + Id = "L-1", + Licensee = "Prova S.r.l.", + IssuedAt = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc), + MaxConcurrentUsers = 5, + MaxCompanies = 1, + Modules = ["CORE", "ACCT"], + }; + var text = LicenseSigner.Sign(document, key); + var verifier = new LicenseVerifier(publicKey); + + var valid = verifier.Verify(text); + Assert.IsNull(valid.Error); + Assert.AreEqual("Prova S.r.l.", valid.Document!.Licensee); + + var tampered = text.Replace("Prova S.r.l.", "Altra S.r.l.", StringComparison.Ordinal); + Assert.AreNotEqual(text, tampered, "The test must change the licence."); + Assert.AreEqual(LicenseErrors.SignatureInvalid, verifier.Verify(tampered).Error); + Assert.AreEqual(LicenseErrors.SignatureInvalid, LicenseVerifier.Product.Verify(text).Error); + Assert.AreEqual(LicenseErrors.FormatInvalid, verifier.Verify("{not json").Error); + } + + [TestMethod] + public void ActivationCode_SignedWithTheKey_IsValid_AndForgeriesAreNot() + { + var (privatePem, publicKey) = LicenseSigner.CreateKeyPair(); + using var key = ECDsa.Create(); + key.ImportFromPem(privatePem); + var code = LicenseSigner.SignActivationCode("CRM", new DateOnly(2027, 12, 1), null, key); + var verifier = new LicenseVerifier(publicKey); + + var (parsed, error) = verifier.VerifyActivationCode(code); + + Assert.IsNull(error); + Assert.AreEqual("CRM", parsed!.Module); + Assert.IsNotNull(LicenseVerifier.Product.VerifyActivationCode(code).Error); + Assert.IsNotNull(verifier.VerifyActivationCode(code.Replace("CRM", "ACCT", StringComparison.Ordinal)).Error); + } +} diff --git a/tests/Khaemhat.Web.Tests/Hosting/CompanyIsolationTests.cs b/tests/Khaemhat.Web.Tests/Hosting/CompanyIsolationTests.cs new file mode 100644 index 0000000..bec4d29 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Hosting/CompanyIsolationTests.cs @@ -0,0 +1,86 @@ +using Khaemhat.Application.Instance; +using Khaemhat.Application.Jobs; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Querying; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Hosting; + +/// Two companies on one instance (SPEC §1.4, issue #23): each has its own database and no data crosses over. +[TestClass] +public sealed class CompanyIsolationTests +{ + [TestMethod] + public async Task ASecondCompany_HasItsOwnDatabase_AndSeesNothingOfTheFirst() + { + var (app, _, first) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var services = app.Services; + var second = "S" + first[1..]; + + // One company is free; more need the MULTI module (here the test code, accepted only in test mode). + var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + var activation = await services.GetRequiredService().ActivateAsync(root, TestLicenseCatalog.All); + Assert.IsTrue(activation.Succeeded, activation.Outcome); + var created = await services.GetRequiredService().CreateAsync(Actor.System, new NewCompany(second, "Seconda S.r.l.")); + Assert.AreEqual(CompanyStatus.Active, created.Status); + + var factory = services.GetRequiredService(); + await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(first))) + { + await unitOfWork.BeginAsync(); + await unitOfWork.Repository().InsertAsync(new Role { Code = "SOLO_PRIMA", Name = "Solo nella prima" }); + await unitOfWork.CommitAsync(); + } + + Assert.AreEqual(1, await CountAsync(factory, first, "SOLO_PRIMA")); + Assert.AreEqual(0, await CountAsync(factory, second, "SOLO_PRIMA")); + + // Both companies got the predefined roles from their own seeding. + Assert.IsTrue(await CountAsync(factory, second, null) > 0); + var registry = services.GetRequiredService(); + Assert.AreNotEqual((await registry.ResolveAsync(first)).DatabaseName, (await registry.ResolveAsync(second)).DatabaseName); + await app.StopAsync(); + } + } + + [TestMethod] + public async Task TheStartSequence_RunTwice_ChangesNothing_AndSystemJobsRun() + { + var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var services = app.Services; + var registry = services.GetRequiredService(); + var roles = await CountAsync(services.GetRequiredService(), company, null); + + await services.GetRequiredService().RunAsync(); + + Assert.AreEqual(1, (await registry.ListAsync()).Count); + Assert.AreEqual(roles, await CountAsync(services.GetRequiredService(), company, null)); + Assert.IsTrue(services.GetRequiredService().IsReady); + + var scheduler = services.GetRequiredService(); + await scheduler.EnsureSystemTasksAsync(); + foreach (var task in JobScheduler.SystemTasks) + { + Assert.AreEqual(JobOutcome.Succeeded, await scheduler.RunAsync(task.Code), task.Code); + } + + await app.StopAsync(); + } + } + + private static async Task CountAsync(IUnitOfWorkFactory factory, string company, string? code) + { + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company)); + var query = code is null ? Query.For() : Query.For().Where(r => r.Code == code); + return (await unitOfWork.Repository().ListAsync(query)).Items.Count; + } +} diff --git a/tests/Khaemhat.Web.Tests/Hosting/HostTests.cs b/tests/Khaemhat.Web.Tests/Hosting/HostTests.cs index 3fe660b..6b2ca91 100644 --- a/tests/Khaemhat.Web.Tests/Hosting/HostTests.cs +++ b/tests/Khaemhat.Web.Tests/Hosting/HostTests.cs @@ -12,20 +12,18 @@ namespace Khaemhat.Web.Tests.Hosting; public sealed class HostTests { private static WebApplication? _app; - private static HttpClient? _client; + private static Uri? _address; + private static string? _company; [ClassInitialize] public static async Task StartAsync(TestContext context) { - _app = KhaemhatApp.Build(["--urls", "http://127.0.0.1:0", "--environment", "Production"]); - await _app.StartAsync(context.CancellationToken); - _client = new HttpClient { BaseAddress = new Uri(_app.Urls.First()) }; + (_app, _address, _company) = await TestInstance.StartAsync(context.CancellationToken); } [ClassCleanup] public static async Task StopAsync() { - _client?.Dispose(); if (_app is not null) { await _app.StopAsync(); @@ -38,7 +36,8 @@ public sealed class HostTests [DataRow("/health/ready", "ready")] public async Task HealthProbes_AnswerOk(string path, string body) { - using var response = await Client.GetAsync(new Uri(path, UriKind.Relative)); + using var client = Client(); + using var response = await client.GetAsync(new Uri(path, UriKind.Relative)); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(body, await response.Content.ReadAsStringAsync()); @@ -47,7 +46,8 @@ public sealed class HostTests [TestMethod] public async Task Health_ReportsStatusAndVersion() { - var report = await Client.GetFromJsonAsync(new Uri("/health", UriKind.Relative)); + using var client = Client(); + var report = await client.GetFromJsonAsync(new Uri("/health", UriKind.Relative)); Assert.IsNotNull(report); Assert.AreEqual("ok", report.Status); @@ -57,22 +57,86 @@ public sealed class HostTests } [TestMethod] - public async Task HomePage_ShowsTheUnderConstructionPage() + public async Task HomePage_RedirectsAnonymousUsersToTheLogin() { - var html = await Client.GetStringAsync(new Uri("/", UriKind.Relative)); + using var client = Client(); + using var response = await client.GetAsync(new Uri("/", UriKind.Relative)); + + Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode); + StringAssert.StartsWith(response.Headers.Location?.OriginalString, "/login"); + } + + [TestMethod] + public async Task LoginPage_IsItalianAndListsTheCompany() + { + using var client = Client(); + var html = await client.GetStringAsync(new Uri("/login", UriKind.Relative)); - StringAssert.Contains(html, "Khaemhat"); - StringAssert.Contains(html, "in costruzione"); StringAssert.Contains(html, "lang=\"it\""); + StringAssert.Contains(html, "Accedi"); + StringAssert.Contains(html, _company!); + } + + [TestMethod] + public async Task Responses_CarryTheSecurityHeaders() + { + using var client = Client(); + using var response = await client.GetAsync(new Uri("/login", UriKind.Relative)); + + StringAssert.Contains(string.Join(';', response.Headers.GetValues("Content-Security-Policy")), "script-src 'self'"); + Assert.AreEqual("DENY", response.Headers.GetValues("X-Frame-Options").Single()); + Assert.IsTrue(response.Headers.Contains("X-Trace-Id")); + } + + [TestMethod] + public async Task Login_WithAWrongPassword_StaysOnThePage() + { + using var client = Client(); + using var response = await PostLoginAsync(client, TestInstance.SuperUser, "not-the-password"); + + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.IsFalse(response.Headers.TryGetValues("Set-Cookie", out var cookies) && cookies.Any(c => c.StartsWith("khaemhat_session=", StringComparison.Ordinal))); + } + + [TestMethod] + public async Task Login_OfTheSuperUser_AsksForANewPasswordFirst() + { + using var client = Client(); + using var response = await PostLoginAsync(client, TestInstance.SuperUser, TestInstance.SuperUserPassword); + + Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode); + StringAssert.Contains(response.Headers.Location?.OriginalString, "/login/cambio-password"); + var cookie = response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith("khaemhat_session=", StringComparison.Ordinal)); + StringAssert.Contains(cookie, "httponly"); + StringAssert.Contains(cookie, "samesite=lax"); } [TestMethod] public async Task UnknownPage_AnswersNotFound() { - using var response = await Client.GetAsync(new Uri("/does-not-exist", UriKind.Relative)); + using var client = Client(); + using var response = await client.GetAsync(new Uri("/does-not-exist", UriKind.Relative)); Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); } - private static HttpClient Client => _client ?? throw new InvalidOperationException("Host not started."); + private static async Task PostLoginAsync(HttpClient client, string user, string password) + { + var page = await client.GetStringAsync(new Uri("/login", UriKind.Relative)); + using var form = new FormUrlEncodedContent(new Dictionary + { + ["_handler"] = "login", + ["__RequestVerificationToken"] = TestInstance.AntiforgeryToken(page), + ["Input.CompanyCode"] = string.Empty, + ["Input.UserName"] = user, + ["Input.Password"] = password, + }); + return await client.PostAsync(new Uri("/login", UriKind.Relative), form); + } + + private static HttpClient Client() => + new(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) + { + BaseAddress = _address ?? throw new InvalidOperationException("Host not started."), + }; } diff --git a/tests/Khaemhat.Web.Tests/Hosting/InstanceVariablesTests.cs b/tests/Khaemhat.Web.Tests/Hosting/InstanceVariablesTests.cs index 41d9300..bb3ca02 100644 --- a/tests/Khaemhat.Web.Tests/Hosting/InstanceVariablesTests.cs +++ b/tests/Khaemhat.Web.Tests/Hosting/InstanceVariablesTests.cs @@ -1,3 +1,4 @@ +using Khaemhat.Application.Configuration; using Khaemhat.Web.Hosting; namespace Khaemhat.Web.Tests.Hosting; @@ -12,7 +13,7 @@ public sealed class InstanceVariablesTests [TestMethod] public async Task LogLevel_SetsTheDefaultLevel() { - await using var app = KhaemhatApp.Build(["--urls", "http://127.0.0.1:0", "--KHAEMHAT_LOG_LEVEL=warning"]); + await using var app = KhaemhatApp.Build(TestInstance.Arguments(out _, "--KHAEMHAT_LOG_LEVEL=warning")); Assert.AreEqual("Warning", app.Configuration["Logging:LogLevel:Default"]); } @@ -20,16 +21,26 @@ public sealed class InstanceVariablesTests [TestMethod] public void LogLevel_RejectsAnUnknownValue() { - var error = Assert.ThrowsExactly( - () => KhaemhatApp.Build(["--urls", "http://127.0.0.1:0", "--KHAEMHAT_LOG_LEVEL=loud"])); + var error = Assert.ThrowsExactly( + () => KhaemhatApp.Build(TestInstance.Arguments(out _, "--KHAEMHAT_LOG_LEVEL=loud"))); - StringAssert.Contains(error.Message, "KHAEMHAT_LOG_LEVEL"); + Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_LOG_LEVEL", StringComparison.Ordinal))); + } + + [TestMethod] + public void MissingRequiredVariables_AreAllReported() + { + var error = Assert.ThrowsExactly(() => KhaemhatApp.Build(["--urls", "http://127.0.0.1:0"])); + + Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal))); + Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_SECRET_KEY", StringComparison.Ordinal))); } [TestMethod] public async Task Urls_AreTakenFromTheVariable() { - await using var app = KhaemhatApp.Build(["--KHAEMHAT_URLS=http://127.0.0.1:0"]); + var arguments = TestInstance.Arguments(out _).Where(a => a is not ("--urls" or "http://127.0.0.1:0")).Append("--KHAEMHAT_URLS=http://127.0.0.1:0"); + await using var app = KhaemhatApp.Build([.. arguments]); Assert.AreEqual("http://127.0.0.1:0", app.Configuration["urls"]); } diff --git a/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs b/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs new file mode 100644 index 0000000..6b82a06 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs @@ -0,0 +1,82 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text.RegularExpressions; +using Khaemhat.Web.Hosting; +using Microsoft.AspNetCore.Builder; + +namespace Khaemhat.Web.Tests.Hosting; + +/// +/// The variables of a test instance: in-memory SQLite databases with unique names (tests run in one process), a fresh +/// secret key, a super user, one company and licences in test mode. +/// +internal static partial class TestInstance +{ + /// The super user of the test instances. + public const string SuperUser = "root"; + + /// Its first password (test value, valid for the password policy). + public const string SuperUserPassword = "Test-Password-2026"; + + /// The arguments that start an instance, plus . + /// The company created at the first start. + /// More arguments (they win over the defaults). + /// The command line. + public static string[] Arguments(out string companyCode, params string[] extra) + { + var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(4)); + companyCode = "T" + id; + string[] defaults = + [ + "--urls", "http://127.0.0.1:0", + "--environment", "Production", + "--KHAEMHAT_SYSTEM_DB=sqlite://memory/system_" + id, + "--KHAEMHAT_SECRET_KEY=" + Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)), + "--KHAEMHAT_DATA_DIR=" + Path.Combine(Path.GetTempPath(), "khaemhat-tests", id), + "--KHAEMHAT_SUPERUSER=" + SuperUser, + "--KHAEMHAT_SUPERUSER_PASSWORD=" + SuperUserPassword, + "--KHAEMHAT_COMPANY_CODE=" + companyCode, + "--KHAEMHAT_LICENSE_MODE=test", + ]; + return [.. defaults, .. extra]; + } + + /// Builds and starts an instance and waits until the start sequence is over. + /// Cancellation. + /// The running instance, its address and the company code. + public static async Task<(WebApplication App, Uri Address, string Company)> StartAsync(CancellationToken cancellationToken) + { + var app = KhaemhatApp.Build(Arguments(out var company)); + await app.StartAsync(cancellationToken); + var address = new Uri(app.Urls.First()); + using var client = new HttpClient { BaseAddress = address }; + var deadline = DateTime.UtcNow.AddSeconds(60); + while (true) + { + using var response = await client.GetAsync(new Uri("/health/ready", UriKind.Relative), cancellationToken); + if (response.StatusCode == HttpStatusCode.OK) + { + return (app, address, company); + } + + if (DateTime.UtcNow > deadline || await response.Content.ReadAsStringAsync(cancellationToken) == "failed") + { + throw new InvalidOperationException("The test instance did not become ready."); + } + + await Task.Delay(100, cancellationToken); + } + } + + /// The antiforgery token of a page with a form. + /// The page. + /// The token. + public static string AntiforgeryToken(string html) + { + var match = TokenPattern().Match(html); + return match.Success ? WebUtility.HtmlDecode(match.Groups[1].Value) : throw new InvalidOperationException("No antiforgery token in the page."); + } + + [GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"")] + private static partial Regex TokenPattern(); +} diff --git a/tools/Khaemhat.LicenseTool/Program.cs b/tools/Khaemhat.LicenseTool/Program.cs index 2b8ae2b..cd7b591 100644 --- a/tools/Khaemhat.LicenseTool/Program.cs +++ b/tools/Khaemhat.LicenseTool/Program.cs @@ -1,6 +1,177 @@ -// Khaemhat.LicenseTool: key pair, issuing and verification of .khl licences (SPEC §8). The private key never -// enters the repository. Completed in milestone M2; until then it only explains that and exits with an error. +// Khaemhat.LicenseTool: key pair, issuing and verification of .khl licences and module activation codes (SPEC §8.2). +// The private key (.khkey, PKCS#8 PEM) stays outside the repository: .gitignore excludes *.khkey and *.pem. -Console.Error.WriteLine("Khaemhat.LicenseTool: non ancora disponibile, arriva con la milestone M2 (SPEC §8)."); -Console.Error.WriteLine("Comandi previsti: keygen, issue, verify."); -return 1; +using System.Globalization; +using System.Security.Cryptography; +using Khaemhat.Infrastructure.Licensing; + +const string Usage = """ + Khaemhat.LicenseTool + + keygen --out + Creates a key pair: writes the private key and prints the public key to put in LicenseVerifier.ProductPublicKey. + + issue --key --licensee --modules CORE,ACCT,... --users --companies + [--expires yyyy-mm-dd] [--grace ] [--instance ] [--id ] --out + Signs an instance licence. + + code --key --module --expires yyyy-mm [--instance ] + Signs an activation code for one module. + + verify [--public-key ] + Checks a licence or a code with the product public key (or the one given). + """; + +if (args.Length == 0 || args[0] is "-h" or "--help" or "help") +{ + Console.WriteLine(Usage); + return args.Length == 0 ? 1 : 0; +} + +try +{ + var options = Options.Parse(args.Skip(1)); + return args[0] switch + { + "keygen" => KeyGen(options), + "issue" => Issue(options), + "code" => Code(options), + "verify" => Verify(options), + _ => Fail($"Unknown command '{args[0]}'.\n\n{Usage}"), + }; +} +catch (Exception ex) when (ex is ArgumentException or FormatException or IOException or CryptographicException or UnauthorizedAccessException) +{ + return Fail(ex.Message); +} + +static int KeyGen(Options options) +{ + var path = options.Required("out"); + if (File.Exists(path)) + { + return Fail($"{path} exists: the tool never overwrites a key."); + } + + var (privateKey, publicKey) = LicenseSigner.CreateKeyPair(); + File.WriteAllText(path, privateKey); + Console.WriteLine($"Private key written to {path}. Keep it outside the repository and back it up."); + Console.WriteLine("Public key (LicenseVerifier.ProductPublicKey):"); + Console.WriteLine(publicKey); + return 0; +} + +static int Issue(Options options) +{ + using var key = LoadKey(options.Required("key")); + var document = new LicenseDocument + { + Id = options.Optional("id") ?? "KHL-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture), + Licensee = options.Required("licensee"), + InstanceId = options.Optional("instance"), + IssuedAt = DateTime.UtcNow, + ExpiresAt = options.Optional("expires") is { } expires + ? DateTime.SpecifyKind(DateTime.ParseExact(expires, "yyyy-MM-dd", CultureInfo.InvariantCulture).AddDays(1).AddSeconds(-1), DateTimeKind.Utc) + : null, + MaxConcurrentUsers = int.Parse(options.Required("users"), CultureInfo.InvariantCulture), + MaxCompanies = int.Parse(options.Required("companies"), CultureInfo.InvariantCulture), + Modules = [.. options.Required("modules").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)], + GracePeriodDays = int.Parse(options.Optional("grace") ?? "30", CultureInfo.InvariantCulture), + }; + + var path = options.Required("out"); + File.WriteAllText(path, LicenseSigner.Sign(document, key)); + Console.WriteLine($"Licence {document.Id} for {document.Licensee} written to {path}."); + return 0; +} + +static int Code(Options options) +{ + using var key = LoadKey(options.Required("key")); + var month = DateOnly.ParseExact(options.Required("expires") + "-01", "yyyy-MM-dd", CultureInfo.InvariantCulture); + Console.WriteLine(LicenseSigner.SignActivationCode(options.Required("module"), month, options.Optional("instance"), key)); + return 0; +} + +static int Verify(Options options) +{ + var input = options.Positional ?? throw new ArgumentException("Give a .khl file or an activation code."); + var verifier = options.Optional("public-key") is { } publicKey ? new LicenseVerifier(publicKey) : LicenseVerifier.Product; + if (File.Exists(input)) + { + var result = verifier.Verify(File.ReadAllText(input)); + if (!result.IsValid) + { + return Fail($"Not valid: {result.Error}."); + } + + var d = result.Document!; + Console.WriteLine($"Valid licence {d.Id} for {d.Licensee}: modules {string.Join(',', d.Modules)}, {d.MaxConcurrentUsers} users, " + + $"{d.MaxCompanies} companies, expires {d.ExpiresAt?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) ?? "never"}, grace {d.GracePeriodDays} days."); + return 0; + } + + var (code, error) = verifier.VerifyActivationCode(input); + if (code is null) + { + return Fail($"Not valid: {error}."); + } + + Console.WriteLine($"Valid activation code for {code.Module} until {code.ExpiresAt:yyyy-MM-dd}."); + return 0; +} + +static ECDsa LoadKey(string path) +{ + var key = ECDsa.Create(); + key.ImportFromPem(File.ReadAllText(path)); + return key; +} + +static int Fail(string message) +{ + Console.Error.WriteLine(message); + return 1; +} + +/// Command-line options: --name value pairs and one positional argument. +internal sealed class Options +{ + private readonly Dictionary _values = new(StringComparer.Ordinal); + + /// The positional argument. + public string? Positional { get; private set; } + + /// Parses the arguments after the command. + /// The arguments. + /// The options. + public static Options Parse(IEnumerable args) + { + var options = new Options(); + using var e = args.GetEnumerator(); + while (e.MoveNext()) + { + if (e.Current.StartsWith("--", StringComparison.Ordinal)) + { + var name = e.Current[2..]; + options._values[name] = e.MoveNext() ? e.Current : throw new ArgumentException($"--{name} needs a value."); + } + else + { + options.Positional = e.Current; + } + } + + return options; + } + + /// A required option. + /// The name. + /// The value. + public string Required(string name) => _values.TryGetValue(name, out var value) ? value : throw new ArgumentException($"--{name} is required."); + + /// An optional option. + /// The name. + /// The value, or . + public string? Optional(string name) => _values.GetValueOrDefault(name); +}