Merge M2 · Sistema e sicurezza (#118)

This commit is contained in:
Alby96 committed 2026-11-11 15:56:07 +01:00
commit 28d8fe531c
109 files changed
+12220 -125

No files matched your search

+11 -5
View File
@@ -135,19 +135,25 @@ jobs:
docker build -f docker/Dockerfile --build-arg VERSION=0.0.0-ci --build-arg GIT_SHA="$(git rev-parse --short HEAD)" \
--label khaemhat-ci.job="$(hostname)" -t "$NAME:image" .
- name: Smoke test (/health/live, non-root user, PUID/PGID)
- name: Smoke test (start-up, login page, non-root user, PUID/PGID)
run: |
docker network create --label khaemhat-ci.job="$(hostname)" "$NAME"
docker network connect "$NAME" "$(hostname)"
# Since M2 the instance needs a key, a super user and a first company; the key is thrown away with the run.
docker run -d --name "$NAME-app" --network "$NAME" --label khaemhat-ci.job="$(hostname)" \
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test -e PUID=99 -e PGID=100 "$NAME:image"
for i in $(seq 1 30); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/live"; then echo; break; fi
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test \
-e KHAEMHAT_SECRET_KEY="$(head -c 32 /dev/urandom | base64)" \
-e KHAEMHAT_SUPERUSER=root -e KHAEMHAT_SUPERUSER_PASSWORD=Ci-Smoke-Test-2026 -e KHAEMHAT_COMPANY_CODE=CI \
-e PUID=99 -e PGID=100 "$NAME:image"
for i in $(seq 1 60); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/ready"; then echo; break; fi
sleep 2
done
curl -fsS --max-time 5 "http://$NAME-app:8080/health"
echo
curl -fsS --max-time 5 "http://$NAME-app:8080/" | grep -q "in costruzione"
test "$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://$NAME-app:8080/")" = "302"
curl -fsS --max-time 5 "http://$NAME-app:8080/login" | grep -q "Accedi"
curl -fsS -D - -o /dev/null --max-time 5 "http://$NAME-app:8080/login" | grep -qi "content-security-policy"
test "$(docker exec "$NAME-app" sh -c 'stat -c %u:%g /proc/1')" = "99:100"
test "$(docker exec "$NAME-app" stat -c %u:%g /data)" = "99:100"
docker exec "$NAME-app" pg_dump --version
+7 -4
View File
@@ -113,15 +113,18 @@ jobs:
--label khaemhat-ci.job="$(hostname)" \
-t "$IMAGE:$VERSION" .
- name: Smoke test (/health/live)
- name: Smoke test (/health/ready)
if: env.PUBLISHED != 'true'
run: |
docker network create --label khaemhat-ci.job="$(hostname)" "$NAME"
docker network connect "$NAME" "$(hostname)"
docker run -d --name "$NAME-app" --network "$NAME" --label khaemhat-ci.job="$(hostname)" \
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test "$IMAGE:$VERSION"
for i in $(seq 1 30); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/live"; then echo; break; fi
-e KHAEMHAT_SYSTEM_DB=sqlite:///data/system.db -e KHAEMHAT_LICENSE_MODE=test \
-e KHAEMHAT_SECRET_KEY="$(head -c 32 /dev/urandom | base64)" \
-e KHAEMHAT_SUPERUSER=root -e KHAEMHAT_SUPERUSER_PASSWORD=Ci-Smoke-Test-2026 -e KHAEMHAT_COMPANY_CODE=CI \
"$IMAGE:$VERSION"
for i in $(seq 1 60); do
if curl -fsS --max-time 5 "http://$NAME-app:8080/health/ready"; then echo; break; fi
sleep 2
done
report="$(curl -fsS --max-time 5 "http://$NAME-app:8080/health")"
+1
View File
@@ -424,3 +424,4 @@ deploy/.env
out/
# License signing keys (tools/Khaemhat.LicenseTool): the private key never enters the repository (ADR 0008).
*.khkey
*.pem
+37
View File
@@ -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
+418 -1
View File
@@ -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`
<!-- END GENERATED -->
+21 -13
View File
@@ -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.<Env>.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 `<ImportMap />` 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).
+14 -6
View File
@@ -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,
+54
View File
@@ -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` = `<database>.<token>`: `_` 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.
+14 -1
View File
@@ -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
+6 -1
View File
@@ -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
+6 -1
View File
@@ -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
+6 -1
View File
@@ -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,
+28 -14
View File
@@ -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
+7 -1
View File
@@ -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**:
@@ -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;
/// <summary>What happened to a record.</summary>
public enum AuditAction
{
/// <summary>Created.</summary>
Insert = 0,
/// <summary>Changed.</summary>
Update = 1,
/// <summary>Deleted.</summary>
Delete = 2,
}
/// <summary>
/// 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 <c>audit_log</c>, in the same unit of work as the change, with the
/// changed fields as JSON <c>{"Field": [old, new]}</c>. Audit columns and secrets are never written.
/// </summary>
public sealed class AuditTrail(TimeProvider clock)
{
private static readonly HashSet<string> Skipped = new(StringComparer.Ordinal)
{
nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion",
"PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString",
};
/// <summary>Writes the history row of a change, inside the caller's unit of work.</summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="unitOfWork">The company unit of work holding the change.</param>
/// <param name="action">What happened.</param>
/// <param name="entityId">The record.</param>
/// <param name="before">The record before (updates and deletes).</param>
/// <param name="after">The record after (inserts and updates).</param>
/// <param name="userName">Who did it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when a row was written (an update that changes nothing writes none).</returns>
public async Task<bool> RecordAsync<T>(
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<AuditEntry, long>().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;
}
/// <summary>The history of a record, newest first (the "Storico" panel).</summary>
/// <param name="unitOfWork">A company unit of work.</param>
/// <param name="entity">The entity name.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public static async Task<IReadOnlyList<AuditEntry>> HistoryAsync(IUnitOfWork unitOfWork, string entity, string entityId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
return (await unitOfWork.Repository<AuditEntry, long>().ListAsync(
Query.For<AuditEntry>().Where(a => a.Entity == entity && a.EntityId == entityId).OrderByDescending(a => a.Id), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>The changed fields between two versions of a record.</summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="before">The old version, or <see langword="null"/>.</param>
/// <param name="after">The new version, or <see langword="null"/>.</param>
/// <returns>Field name to <c>[old, new]</c>.</returns>
public static IReadOnlyDictionary<string, object?[]> Diff<T>(T? before, T? after)
where T : class
{
var result = new SortedDictionary<string, object?[]>(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(),
};
}
@@ -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;
/// <summary>A security or instance action to record.</summary>
/// <param name="Action">The action code, for example <c>login.succeeded</c>, <c>user.created</c>, <c>license.activated</c>.</param>
/// <param name="UserName">Who acted.</param>
/// <param name="CompanyCode">The company concerned.</param>
/// <param name="Target">What the action was about.</param>
/// <param name="Details">Further details, serialized as JSON (never secrets).</param>
/// <param name="IpAddress">The client address.</param>
public sealed record SecurityEvent(
string Action, string? UserName, string? CompanyCode = null, string? Target = null, object? Details = null, string? IpAddress = null);
/// <summary>Writes <c>sys_security_audit</c>.</summary>
public interface ISecurityAuditLog
{
/// <summary>Records an action.</summary>
/// <param name="securityEvent">The action.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task WriteAsync(SecurityEvent securityEvent, CancellationToken cancellationToken = default);
}
/// <summary>
/// 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. <see cref="VerifyAsync"/>
/// finds a changed or removed row.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="clock">The clock.</param>
public sealed class SecurityAuditLog(IUnitOfWorkFactory factory, TimeProvider clock) : ISecurityAuditLog
{
private const string LockKey = "security-audit";
/// <inheritdoc />
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<SecurityAuditEntry, long>();
var last = await repository.FindAsync(Query.For<SecurityAuditEntry>().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);
}
/// <summary>Checks the whole chain.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The identifier of the first row that does not match, or <see langword="null"/> when the chain is intact.</returns>
public async Task<long?> 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<SecurityAuditEntry, long>()
.ListAsync(Query.For<SecurityAuditEntry>().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;
}
}
}
/// <summary>The hash of a row: every field and the previous hash, separated so that fields cannot run into each other.</summary>
/// <param name="entry">The row.</param>
/// <returns>64 hexadecimal digits.</returns>
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];
}
@@ -0,0 +1,115 @@
namespace Khaemhat.Application.Configuration;
/// <summary>
/// Reads the <c>KHAEMHAT_*</c> variables of SPEC §6 into <see cref="KhaemhatOptions"/>, applying the <c>_FILE</c>
/// rule of ADR 0014 to the sensitive ones: when <c>X_FILE</c> is set, the value of <c>X</c> 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 <see cref="KhaemhatOptions.ReadErrors"/>; values never appear in messages.
/// </summary>
public sealed class EnvironmentConfigurationReader
{
/// <summary>The variables that accept a <c>_FILE</c> variant (ADR 0014).</summary>
public static readonly IReadOnlySet<string> FileVariables = new HashSet<string>(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<string, string?> _lookup;
private readonly Func<string, string> _readFile;
/// <summary>Creates a reader.</summary>
/// <param name="lookup">Returns a variable, or <see langword="null"/> when unset (the host configuration: environment and command line).</param>
/// <param name="readFile">Reads a secret file; the default reads from disk.</param>
public EnvironmentConfigurationReader(Func<string, string?> lookup, Func<string, string>? readFile = null)
{
ArgumentNullException.ThrowIfNull(lookup);
_lookup = lookup;
_readFile = readFile ?? File.ReadAllText;
}
/// <summary>Reads every variable.</summary>
/// <returns>The options, with the reading problems in <see cref="KhaemhatOptions.ReadErrors"/>.</returns>
public KhaemhatOptions Read()
{
var errors = new List<string>();
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<string> 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;
}
}
@@ -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;
/// <summary>How the licences behave (<c>KHAEMHAT_LICENSE_MODE</c>).</summary>
public enum LicenseMode
{
/// <summary>Only signed licences count.</summary>
Production = 0,
/// <summary>The fictitious codes of SPEC §8.3 are accepted too. Never in production.</summary>
Test = 1,
}
/// <summary>The connection security of the mail server.</summary>
public enum SmtpSecurity
{
/// <summary>STARTTLS on a plain connection (port 587).</summary>
StartTls = 0,
/// <summary>TLS from the start (port 465).</summary>
Ssl = 1,
/// <summary>No encryption: only for a local relay.</summary>
None = 2,
}
/// <summary>A configuration that does not let the instance start. The message lists every problem, never a value.</summary>
public sealed class ConfigurationException : Exception
{
/// <summary>Creates the exception.</summary>
public ConfigurationException()
: this([])
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public ConfigurationException(string message)
: base(message) => Errors = [message];
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public ConfigurationException(string message, Exception innerException)
: base(message, innerException) => Errors = [message];
/// <summary>Creates the exception from a list of problems.</summary>
/// <param name="errors">The problems.</param>
public ConfigurationException(IReadOnlyList<string> errors)
: base(Describe(errors)) => Errors = errors;
/// <summary>The problems, one per line of the message.</summary>
public IReadOnlyList<string> Errors { get; }
private static string Describe(IReadOnlyList<string> 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));
}
/// <summary>
/// The instance configuration of SPEC §6, read from the environment by <see cref="EnvironmentConfigurationReader"/>.
/// Values stay in memory: nothing is written to disk. <see cref="Validate"/> checks everything before the host starts;
/// the typed accessors (<see cref="SystemDatabase"/>, <see cref="Mode"/>...) are meant for a validated instance.
/// </summary>
public sealed class KhaemhatOptions
{
/// <summary><c>KHAEMHAT_SYSTEM_DB</c>: the system database URL (required).</summary>
public string? SystemDb { get; init; }
/// <summary><c>KHAEMHAT_DB_SERVER</c>: the PostgreSQL server where company databases are created.</summary>
public string? DbServer { get; init; }
/// <summary><c>KHAEMHAT_SECRET_KEY</c>: base64 of at least 32 bytes (required).</summary>
public string? SecretKey { get; init; }
/// <summary><c>KHAEMHAT_SECRET_KEY_NEW</c>: the new key during a rotation (SPEC §12.9).</summary>
public string? RotationSecretKey { get; init; }
/// <summary><c>KHAEMHAT_SUPERUSER</c>: the super user name, read only while <c>sys_users</c> is empty.</summary>
public string? SuperUser { get; init; }
/// <summary><c>KHAEMHAT_SUPERUSER_PASSWORD</c>: its first password, to change at the first access.</summary>
public string? SuperUserPassword { get; init; }
/// <summary><c>KHAEMHAT_SUPERUSER_EMAIL</c>: its e-mail address.</summary>
public string? SuperUserEmail { get; init; }
/// <summary><c>KHAEMHAT_COMPANY_CODE</c>: the first company, read only while <c>sys_companies</c> is empty.</summary>
public string? CompanyCode { get; init; }
/// <summary><c>KHAEMHAT_COMPANY_NAME</c>: its name.</summary>
public string? CompanyName { get; init; }
/// <summary><c>KHAEMHAT_COUNTRY</c>: the fiscal package of the first company (default <c>IT</c>).</summary>
public string Country { get; init; } = "IT";
/// <summary><c>KHAEMHAT_LICENSE_MODE</c>: <c>production</c> (default) or <c>test</c>.</summary>
public string LicenseMode { get; init; } = "production";
/// <summary><c>KHAEMHAT_LICENSE</c>: the text of a <c>.khl</c> licence; absent means Trial.</summary>
public string? License { get; init; }
/// <summary><c>KHAEMHAT_REDIS</c>: <c>redis://</c> or <c>rediss://</c>; absent means in-memory cache.</summary>
public string? Redis { get; init; }
/// <summary><c>KHAEMHAT_DATA_DIR</c>: the only folder the instance writes to (default <c>/data</c>).</summary>
public string DataDir { get; init; } = "/data";
/// <summary><c>KHAEMHAT_URLS</c>: the listening addresses.</summary>
public string? Urls { get; init; }
/// <summary><c>KHAEMHAT_PUBLIC_URL</c>: the address users reach, for links in e-mails.</summary>
public string? PublicUrl { get; init; }
/// <summary><c>KHAEMHAT_SMTP_HOST</c>.</summary>
public string? SmtpHost { get; init; }
/// <summary><c>KHAEMHAT_SMTP_PORT</c>.</summary>
public string? SmtpPort { get; init; }
/// <summary><c>KHAEMHAT_SMTP_USER</c>.</summary>
public string? SmtpUser { get; init; }
/// <summary><c>KHAEMHAT_SMTP_PASSWORD</c>.</summary>
public string? SmtpPassword { get; init; }
/// <summary><c>KHAEMHAT_SMTP_FROM</c>.</summary>
public string? SmtpFrom { get; init; }
/// <summary><c>KHAEMHAT_SMTP_SECURITY</c>: <c>starttls</c> (default), <c>ssl</c> or <c>none</c>.</summary>
public string? SmtpSecurity { get; init; }
/// <summary><c>KHAEMHAT_LOG_LEVEL</c>: the minimum level on stdout.</summary>
public string? LogLevel { get; init; }
/// <summary><c>KHAEMHAT_SEED_BASE</c>: load the base tables when a company is created (default true).</summary>
public string? SeedBase { get; init; }
/// <summary><c>KHAEMHAT_SEED_DEMO</c>: load the demo data into an empty company (default false).</summary>
public string? SeedDemo { get; init; }
/// <summary><c>KHAEMHAT_UPDATE_FEED</c>: the package list read by the update check.</summary>
public string? UpdateFeed { get; init; }
/// <summary><c>KHAEMHAT_UPDATE_TOKEN</c>: a read-only token for the feed.</summary>
public string? UpdateToken { get; init; }
/// <summary><c>TZ</c>: the time zone of the container.</summary>
public string? TimeZone { get; init; }
/// <summary>The problems met while reading (both <c>X</c> and <c>X_FILE</c>, unreadable files).</summary>
public IReadOnlyList<string> ReadErrors { get; init; } = [];
/// <summary>The system database, parsed.</summary>
public DatabaseUrl SystemDatabase => DatabaseUrl.Parse(SystemDb ?? throw new ConfigurationException("KHAEMHAT_SYSTEM_DB is not set."));
/// <summary>
/// Where company databases are created: <see cref="DbServer"/> when set, otherwise the server (PostgreSQL) or the
/// folder (SQLite) of the system database.
/// </summary>
public DatabaseUrl CompanyServer => DbServer is { } server ? DatabaseUrl.Parse(server) : SystemDatabase;
/// <summary>The licence mode, parsed.</summary>
public LicenseMode Mode => string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase)
? Configuration.LicenseMode.Test
: Configuration.LicenseMode.Production;
/// <summary>Whether base data is loaded into new companies.</summary>
public bool SeedBaseEnabled => ParseBool(SeedBase) ?? true;
/// <summary>Whether demo data is loaded into new, empty companies.</summary>
public bool SeedDemoEnabled => ParseBool(SeedDemo) ?? false;
/// <summary>The SMTP port, defaulting by security mode.</summary>
public int SmtpPortNumber => int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port)
? port
: SmtpSecurityMode == Configuration.SmtpSecurity.Ssl ? 465 : 587;
/// <summary>The SMTP security, parsed.</summary>
public SmtpSecurity SmtpSecurityMode => SmtpSecurity?.ToUpperInvariant() switch
{
"SSL" or "TLS" => Configuration.SmtpSecurity.Ssl,
"NONE" => Configuration.SmtpSecurity.None,
_ => Configuration.SmtpSecurity.StartTls,
};
/// <summary>
/// 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.
/// </summary>
/// <returns>The problems; empty when the instance can start.</returns>
public IReadOnlyList<string> Validate()
{
var errors = new List<string>(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>(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;
}
/// <summary>Throws when <see cref="Validate"/> finds problems.</summary>
/// <exception cref="ConfigurationException">The configuration is not valid.</exception>
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<string> 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();
}
@@ -0,0 +1,116 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
namespace Khaemhat.Application.Instance;
/// <summary>The outcome of choosing the company a request or a circuit works in.</summary>
public enum CompanyAccess
{
/// <summary>The company can be used.</summary>
Granted = 0,
/// <summary>No company chosen (an instance account on instance pages).</summary>
None = 1,
/// <summary>The company does not exist.</summary>
NotFound = 2,
/// <summary>A company account asked for another company.</summary>
Forbidden = 3,
/// <summary>The company is in maintenance and the account is not an instance account.</summary>
Maintenance = 4,
/// <summary>The company is disabled.</summary>
Disabled = 5,
}
/// <summary>The company of the current request or Blazor circuit (SPEC §5.4).</summary>
/// <param name="Access">Whether the company can be used.</param>
/// <param name="Company">The company, when it exists.</param>
public sealed record CompanyContextResult(CompanyAccess Access, Company? Company)
{
/// <summary>No company.</summary>
public static CompanyContextResult None { get; } = new(CompanyAccess.None, null);
/// <summary>The company code, when granted.</summary>
public string? Code => Access == CompanyAccess.Granted ? Company!.Code : null;
/// <summary>Whether writes are refused (company in <see cref="CompanyStatus.ReadOnly"/>).</summary>
public bool IsReadOnly => Company?.Status == CompanyStatus.ReadOnly;
/// <summary>Whether the company is temporarily unavailable (the API answers 503).</summary>
public bool IsUnavailable => Access is CompanyAccess.Maintenance or CompanyAccess.Disabled;
/// <summary>The database scope of the company.</summary>
/// <returns>The scope.</returns>
/// <exception cref="InvalidOperationException">No company is granted.</exception>
public DatabaseScope Scope() =>
Access == CompanyAccess.Granted ? DatabaseScope.Company(Company!.Code) : throw new InvalidOperationException("No company is available in this context.");
}
/// <summary>The company the current user works in. Scoped: one per request and one per Blazor circuit.</summary>
public interface ICompanyContext
{
/// <summary>Resolves (once) and returns the company.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The result.</returns>
ValueTask<CompanyContextResult> GetAsync(CancellationToken cancellationToken = default);
}
/// <summary>
/// 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 <c>X-Company</c> header of an API call). A company in maintenance is open
/// only to instance accounts; a disabled company to nobody.
/// </summary>
/// <param name="companies">The company registry.</param>
public sealed class CompanyContextResolver(ICompanyRegistry companies)
{
/// <summary>The header naming the company of an API call.</summary>
public const string Header = "X-Company";
/// <summary>Chooses the company.</summary>
/// <param name="actor">The signed-in user, or <see langword="null"/>.</param>
/// <param name="requested">The company asked by the request (header), or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The result.</returns>
public async Task<CompanyContextResult> 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),
};
}
}
@@ -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;
/// <summary>Where the databases of the instance are and which migrations they get.</summary>
/// <param name="System">The system database (<c>KHAEMHAT_SYSTEM_DB</c>).</param>
/// <param name="CompanyServer">Where new company databases are created (<c>KHAEMHAT_DB_SERVER</c>, or next to the system one).</param>
/// <param name="SystemMigrations">The migrations of the system database.</param>
/// <param name="CompanyMigrations">The migrations of every company database.</param>
public sealed record InstanceDatabases(DatabaseUrl System, DatabaseUrl CompanyServer, MigrationCatalog SystemMigrations, MigrationCatalog CompanyMigrations);
/// <summary>A company to create.</summary>
/// <param name="Code">The code (database <c>khaemhat_&lt;code&gt;</c>).</param>
/// <param name="Name">The company name.</param>
/// <param name="IsDefault">Whether it becomes the default company.</param>
/// <param name="Notes">Notes for administrators.</param>
/// <param name="SeedDemo">Whether to load the demo data.</param>
public sealed record NewCompany(string Code, string Name, bool IsDefault = false, string? Notes = null, bool SeedDemo = false);
/// <summary>
/// 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.
/// </summary>
public interface ICompanySeeder
{
/// <summary>The order among seeders (lower first).</summary>
int Order { get; }
/// <summary>Fills the database.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="context">What to load.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default);
}
/// <summary>What a seeder is asked to load.</summary>
/// <param name="IsNew">Whether the database was just created.</param>
/// <param name="Base">Whether the base data is wanted (<c>KHAEMHAT_SEED_BASE</c>).</param>
/// <param name="Demo">Whether the demo data is wanted.</param>
public sealed record CompanySeedContext(bool IsNew, bool Base, bool Demo);
/// <summary>The predefined roles of SPEC §7.2, kept equal to their templates in every company.</summary>
/// <param name="roles">The role service.</param>
public sealed class PredefinedRolesSeeder(RoleService roles) : ICompanySeeder
{
/// <inheritdoc />
public int Order => 0;
/// <inheritdoc />
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) =>
roles.SyncPredefinedRolesAsync(companyCode, cancellationToken);
}
/// <summary>
/// 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).
/// </summary>
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<ICompanySeeder> _seeders;
private readonly ILogger<CompanyService> _logger;
/// <summary>Creates the service.</summary>
/// <param name="registry">The company registry.</param>
/// <param name="providers">The database providers.</param>
/// <param name="migrations">Applies migrations.</param>
/// <param name="databases">Where databases are.</param>
/// <param name="licenses">The licence in force.</param>
/// <param name="sessions">The sessions (revoked when a company goes into maintenance).</param>
/// <param name="audit">The security audit.</param>
/// <param name="seeders">The seeders of the modules.</param>
/// <param name="logger">The log.</param>
public CompanyService(
ICompanyRegistry registry, DbProviderCatalog providers, MigrationRunner migrations, InstanceDatabases databases, ILicenseGate licenses,
SessionStore sessions, ISecurityAuditLog audit, IEnumerable<ICompanySeeder> seeders, ILogger<CompanyService> 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;
}
/// <summary>The companies of the instance.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The companies by code.</returns>
public Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default) => _registry.ListAsync(cancellationToken);
/// <summary>
/// Creates a company: a new database <c>khaemhat_&lt;code&gt;</c> on the company server, registered, migrated and
/// filled by the seeders.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The registered company.</returns>
/// <exception cref="AccessDeniedException">The actor is not an instance account, or the licence allows no more companies.</exception>
public async Task<Company> 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;
}
/// <summary>
/// Attaches an existing company database (restored from a backup or moved from another instance) and migrates it.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="code">The company code.</param>
/// <param name="name">The company name.</param>
/// <param name="database">Where the database is.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The registered company.</returns>
public async Task<Company> 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;
}
/// <summary>
/// Changes the state of a company. Maintenance and disabling sign out its users at once; instance accounts can still
/// open a company in maintenance.
/// </summary>
/// <param name="actor">Who acts: an instance account.</param>
/// <param name="code">The company.</param>
/// <param name="status">The new state.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="seedDemo">Whether demo data is wanted (<c>KHAEMHAT_SEED_DEMO</c>).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The companies that failed.</returns>
public async Task<IReadOnlyList<string>> PrepareAllAsync(bool seedDemo, CancellationToken cancellationToken = default)
{
var failed = new List<string>();
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);
}
}
/// <summary>Writes a migration report in the section <i>Migrazioni</i>.</summary>
/// <param name="logger">The log.</param>
/// <param name="report">The report.</param>
/// <param name="companyCode">The company, or <see langword="null"/> for the system database.</param>
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<string, object?> { [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<string>();
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.");
}
}
}
@@ -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;
/// <summary>Where the start of the instance is.</summary>
public enum BootstrapPhase
{
/// <summary>Migrations and first-start setup in progress: <c>/health/ready</c> answers 503.</summary>
Starting = 0,
/// <summary>Ready to serve.</summary>
Ready = 1,
/// <summary>The start failed; the process is stopping.</summary>
Failed = 2,
}
/// <summary>The start state, read by the readiness endpoint and the middleware.</summary>
public sealed class BootstrapState
{
private volatile BootstrapPhase _phase;
/// <summary>The phase.</summary>
public BootstrapPhase Phase => _phase;
/// <summary>Whether the instance serves requests.</summary>
public bool IsReady => _phase == BootstrapPhase.Ready;
/// <summary>Why the start failed (no secrets).</summary>
public string? Error { get; private set; }
/// <summary>Companies put in maintenance because their migration failed.</summary>
public IReadOnlyList<string> FailedCompanies { get; private set; } = [];
/// <summary>Marks the start as completed.</summary>
/// <param name="failedCompanies">The companies that could not be migrated.</param>
public void MarkReady(IReadOnlyList<string> failedCompanies)
{
FailedCompanies = failedCompanies ?? [];
_phase = BootstrapPhase.Ready;
}
/// <summary>Marks the start as failed.</summary>
/// <param name="error">Why.</param>
public void MarkFailed(string error)
{
Error = error;
_phase = BootstrapPhase.Failed;
}
}
/// <summary>
/// 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.
/// </summary>
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<StartupOrchestrator> _logger;
private bool _systemReady;
/// <summary>Creates the orchestrator.</summary>
/// <param name="databases">Where databases are.</param>
/// <param name="providers">The providers.</param>
/// <param name="migrations">Applies migrations.</param>
/// <param name="settings">The instance settings.</param>
/// <param name="roles">The role templates.</param>
/// <param name="licenses">The licence.</param>
/// <param name="systemUsers">The instance accounts.</param>
/// <param name="companies">The companies.</param>
/// <param name="options">The variables.</param>
/// <param name="factory">Opens the databases.</param>
/// <param name="logSink">The database log, started once the system database is ready (absent in some tests).</param>
/// <param name="state">The start state.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
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<StartupOrchestrator> 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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="cancellationToken">Cancellation (host stopping).</param>
/// <returns>A task.</returns>
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;
}
/// <summary>Runs the start sequence and marks the state ready.</summary>
/// <param name="cancellationToken">Cancellation (host stopping).</param>
/// <returns>A task.</returns>
/// <exception cref="ConfigurationException">First start without the variables it needs.</exception>
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<string>();
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;
}
}
}
}
@@ -0,0 +1,82 @@
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Instance;
/// <summary>
/// Instance settings in <c>sys_settings</c>. Secret values are encrypted with the instance key and the purpose
/// <c>setting:&lt;key&gt;</c>.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="protector">Encrypts secret values.</param>
public sealed class SystemSettingsStore(IUnitOfWorkFactory factory, ISecretProtector protector)
{
/// <summary>The identifier of the instance, created at first start.</summary>
public const string InstanceIdKey = "instance.id";
/// <summary>When the trial started (ISO 8601 UTC), set at first start.</summary>
public const string TrialStartedKey = "license.trial-started-at";
/// <summary>Reads a setting.</summary>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value (decrypted when secret), or <see langword="null"/>.</returns>
public async Task<string?> 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<SystemSetting, long>().FindAsync(Query.For<SystemSetting>().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;
}
/// <summary>Writes a setting.</summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="secret">Whether to encrypt it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<SystemSetting, long>();
var stored = value is null || !secret ? value : protector.Protect(value, Purpose(key));
var setting = await settings.FindAsync(Query.For<SystemSetting>().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);
}
/// <summary>Writes a setting only if it does not exist yet (bootstrap values such as the instance id).</summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value now stored.</returns>
public async Task<string> 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;
}
@@ -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;
/// <summary>What a job run receives.</summary>
/// <param name="Task">The task (code, company, parameters).</param>
/// <param name="Attempt">The attempt number, from 1.</param>
/// <param name="TraceId">The trace identifier of the run, also in the log.</param>
public sealed record JobContext(ScheduledTask Task, int Attempt, string TraceId);
/// <summary>
/// A kind of job the scheduler can run (SPEC §9.4). Modules register theirs (e-mail import, SDI polling, reminders,
/// backups); <see cref="Type"/> is what <c>sys_scheduled_tasks.job_type</c> names.
/// </summary>
public interface IScheduledJob
{
/// <summary>The job type.</summary>
string Type { get; }
/// <summary>Runs the job. The token is cancelled at the task timeout or at shutdown.</summary>
/// <param name="context">The run.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A message for the run history, or <see langword="null"/>.</returns>
Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken);
}
/// <summary>A task created at start when missing.</summary>
/// <param name="Code">The task code.</param>
/// <param name="Name">The name shown.</param>
/// <param name="JobType">The job type.</param>
/// <param name="Cron">When it runs.</param>
/// <param name="TimeoutSeconds">Its timeout.</param>
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600);
/// <summary>
/// The scheduler (SPEC §9.4; mockup 083): reads <c>sys_scheduled_tasks</c>, runs the due ones with a lock in
/// <c>sys_job_locks</c> (so two instances never run the same task together), applies timeout and retries, writes
/// <c>sys_job_runs</c> and the section <i>Attività programmate</i> of the log, and notifies the instance accounts when a
/// task fails for good.
/// </summary>
public sealed class JobScheduler
{
/// <summary>The system tasks of M2.</summary>
public static readonly IReadOnlyList<SystemTaskDefinition> 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<string, IScheduledJob> _jobs;
private readonly NotificationDispatcher _notifications;
private readonly TimeProvider _clock;
private readonly ILogger<JobScheduler> _logger;
private readonly string _owner = Environment.MachineName + ":" + Environment.ProcessId;
/// <summary>Creates the scheduler.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="jobs">The job types.</param>
/// <param name="notifications">Notifies failures.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public JobScheduler(IUnitOfWorkFactory factory, IEnumerable<IScheduledJob> jobs, NotificationDispatcher notifications, TimeProvider clock, ILogger<JobScheduler> 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;
}
/// <summary>Creates the system tasks that are missing and computes the next run of every task without one.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<ScheduledTask, long>();
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<ScheduledTask>().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);
}
/// <summary>Runs every enabled task that is due, one after the other.</summary>
/// <param name="cancellationToken">Cancellation (shutdown).</param>
/// <returns>How many tasks ran.</returns>
public async Task<int> RunDueAsync(CancellationToken cancellationToken = default)
{
var now = _clock.GetUtcNow().UtcDateTime;
IReadOnlyList<ScheduledTask> due;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
due = (await unitOfWork.Repository<ScheduledTask, long>().ListAsync(
Query.For<ScheduledTask>().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;
}
/// <summary>Runs a task now (also "Esegui ora" from the administration page).</summary>
/// <param name="code">The task code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome; <see cref="JobOutcome.Skipped"/> when another run holds the lock.</returns>
public async Task<JobOutcome> RunAsync(string code, CancellationToken cancellationToken = default)
{
ScheduledTask? task;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
task = await unitOfWork.Repository<ScheduledTask, long>().FindAsync(Query.For<ScheduledTask>().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<JobOutcome> 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<string, object?> { [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<ScheduledTask, long>();
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<long> SaveRunAsync(JobRun run, bool insert, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var runs = unitOfWork.Repository<JobRun, long>();
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<bool> 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<JobLock, string>();
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);
}
}
/// <summary>Runs the scheduler every 30 seconds once the instance is ready.</summary>
/// <param name="scheduler">The scheduler.</param>
/// <param name="state">The start state.</param>
/// <param name="logger">The log.</param>
public sealed class JobSchedulerService(JobScheduler scheduler, BootstrapState state, ILogger<JobSchedulerService> logger) : BackgroundService
{
/// <summary>How often due tasks are looked for.</summary>
public static readonly TimeSpan Interval = TimeSpan.FromSeconds(30);
/// <inheritdoc />
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));
}
}
+119
View File
@@ -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;
/// <summary>Deletes sessions expired or revoked more than 30 days ago, in the system database and in every company.</summary>
/// <param name="sessions">The sessions.</param>
/// <param name="companies">The companies.</param>
public sealed class SessionCleanupJob(SessionStore sessions, ICompanyRegistry companies) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "system.sessions-cleanup";
/// <summary>How long ended sessions stay for the history.</summary>
public static readonly TimeSpan Keep = TimeSpan.FromDays(30);
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> 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.");
}
}
/// <summary>
/// Computes the licence again every hour (SPEC §8.2) and notifies the instance accounts when it is about to expire or
/// has expired.
/// </summary>
/// <param name="licenses">The licence.</param>
/// <param name="notifications">The notifications.</param>
/// <param name="clock">The clock.</param>
public sealed class LicenseCheckJob(ILicenseGate licenses, NotificationDispatcher notifications, TimeProvider clock) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "system.license-check";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> 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))}.";
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="clock">The clock.</param>
public sealed class LogRetentionJob(IUnitOfWorkFactory factory, TimeProvider clock) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "system.log-retention";
/// <summary>How many days each level is kept.</summary>
public static readonly IReadOnlyDictionary<string, int> RetentionDays = new Dictionary<string, int>(StringComparer.Ordinal)
{
["Trace"] = 7,
["Debug"] = 7,
["Information"] = 90,
["Warning"] = 180,
["Error"] = 365,
["Critical"] = 365,
};
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> 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.");
}
}
@@ -4,6 +4,11 @@
<RootNamespace>Khaemhat.Application</RootNamespace>
</PropertyGroup>
<!-- The ASP.NET Core shared framework (logging, options, DataProtection, hosting): part of .NET, not a package. -->
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
@@ -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;
/// <summary>The licence in force and the modules it activates.</summary>
public interface ILicenseGate
{
/// <summary>The licence computed at the last refresh.</summary>
LicenseState Current { get; }
/// <summary>Whether a module is licensed.</summary>
/// <param name="moduleCode">The module code.</param>
/// <returns><see langword="true"/> if active.</returns>
bool IsModuleActive(string moduleCode);
/// <summary>Recomputes the licence from the database and the environment.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new state.</returns>
Task<LicenseState> RefreshAsync(CancellationToken cancellationToken = default);
}
/// <summary>Where the gate reads the licence from the environment.</summary>
/// <param name="EnvironmentLicense">The text of <c>KHAEMHAT_LICENSE</c>, if set.</param>
/// <param name="Mode">The licence mode.</param>
public sealed record LicenseSettings(string? EnvironmentLicense, LicenseMode Mode);
/// <summary>
/// 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.
/// </summary>
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<LicenseGate> _logger;
private volatile LicenseState _current;
/// <summary>Creates the gate. Until the first refresh the state is the trial.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="settings">The instance settings.</param>
/// <param name="verifier">Checks signatures.</param>
/// <param name="licenseSettings">The environment licence and mode.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public LicenseGate(
IUnitOfWorkFactory factory, SystemSettingsStore settings, LicenseVerifier verifier, LicenseSettings licenseSettings,
TimeProvider clock, ILogger<LicenseGate> 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);
}
/// <inheritdoc />
public LicenseState Current => _current;
/// <summary>The instance identifier read at the last refresh.</summary>
public string? InstanceId { get; private set; }
/// <inheritdoc />
public bool IsModuleActive(string moduleCode) => _current.Includes(moduleCode);
/// <inheritdoc />
public async Task<LicenseState> 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<LicenseRecord> records;
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
records = (await unitOfWork.Repository<LicenseRecord, long>()
.ListAsync(Query.For<LicenseRecord>().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<string>(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<TestCode>())
{
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<string> extra, int testUsers, bool testMode)
{
var modules = new HashSet<string>(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<string> extra, int testUsers, bool testMode)
{
var modules = new HashSet<string>(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,
};
}
}
/// <summary>The outcome of an activation.</summary>
/// <param name="Succeeded">Whether the licence or code was installed.</param>
/// <param name="Outcome">The outcome code: <c>ok</c> or one of <see cref="LicenseErrors"/>.</param>
/// <param name="State">The licence in force afterwards.</param>
public sealed record ActivationResult(bool Succeeded, string Outcome, LicenseState State);
/// <summary>Installs and removes licences (SPEC §8.2). Today offline; a remote activation server may come later.</summary>
public interface ILicenseActivationService
{
/// <summary>Installs a <c>.khl</c> licence, a module activation code or, in test mode, a fictitious code.</summary>
/// <param name="actor">Who acts: only the super user.</param>
/// <param name="input">The licence text or the code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome.</returns>
Task<ActivationResult> ActivateAsync(Actor actor, string input, CancellationToken cancellationToken = default);
/// <summary>Removes an installed licence or code (it stays in the history).</summary>
/// <param name="actor">Who acts: only the super user.</param>
/// <param name="licenseId">The row of <c>sys_licenses</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The licence in force afterwards.</returns>
Task<LicenseState> DeactivateAsync(Actor actor, long licenseId, CancellationToken cancellationToken = default);
}
/// <summary>Activation checked locally with the public key: no network involved.</summary>
public sealed class OfflineActivationService(
IUnitOfWorkFactory factory, LicenseGate gate, LicenseVerifier verifier, LicenseSettings settings, ModuleRegistry modules,
ISecurityAuditLog audit, TimeProvider clock) : ILicenseActivationService
{
/// <inheritdoc />
public async Task<ActivationResult> 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<LicenseRecord, long>();
if (record.Source == LicenseSource.File)
{
// A new instance licence replaces the previous one; codes stay.
foreach (var old in (await licenses.ListAsync(
Query.For<LicenseRecord>().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<LicenseActivation, long>().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);
}
/// <inheritdoc />
public async Task<LicenseState> 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<LicenseRecord, long>();
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<LicenseActivation, long>().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.");
}
}
}
@@ -0,0 +1,136 @@
using Khaemhat.Application.Modules;
namespace Khaemhat.Application.Licensing;
/// <summary>Where the instance stands with its licence.</summary>
public enum LicenseStatus
{
/// <summary>Valid.</summary>
Valid = 0,
/// <summary>Expired but within the grace period: everything works, with a banner.</summary>
Grace = 1,
/// <summary>Expired beyond the grace period: read-only with a banner (SPEC §8.2).</summary>
Expired = 2,
}
/// <summary>What kind of licence is in force.</summary>
public enum LicenseKind
{
/// <summary>No licence: CORE and ACCT, 3 users, 60 days.</summary>
Trial = 0,
/// <summary>A signed licence.</summary>
Licensed = 1,
}
/// <summary>The licence in force, computed by <see cref="LicenseGate"/>. Immutable.</summary>
public sealed record LicenseState
{
/// <summary>The trial modules (SPEC §6).</summary>
public static readonly IReadOnlyList<string> TrialModules = [ModuleCodes.Core, ModuleCodes.Accounting];
/// <summary>The trial users.</summary>
public const int TrialUsers = 3;
/// <summary>The trial length.</summary>
public static readonly TimeSpan TrialLength = TimeSpan.FromDays(60);
/// <summary>The licence kind.</summary>
public LicenseKind Kind { get; init; }
/// <summary>The status.</summary>
public LicenseStatus Status { get; init; }
/// <summary>The holder.</summary>
public string? Licensee { get; init; }
/// <summary>The active modules.</summary>
public IReadOnlySet<string> Modules { get; init; } = new HashSet<string>(StringComparer.Ordinal);
/// <summary>The concurrent users allowed across all companies.</summary>
public int MaxConcurrentUsers { get; init; }
/// <summary>The companies allowed.</summary>
public int MaxCompanies { get; init; }
/// <summary>When the licence (or the trial) expires.</summary>
public DateTime? ExpiresAt { get; init; }
/// <summary>When the grace period ends.</summary>
public DateTime? GraceEndsAt { get; init; }
/// <summary>Whether the fictitious codes are accepted (<c>KHAEMHAT_LICENSE_MODE=test</c>): the interface shows a banner.</summary>
public bool IsTestMode { get; init; }
/// <summary>Whether data can only be read.</summary>
public bool IsReadOnly => Status == LicenseStatus.Expired;
/// <summary>Whether a module is active.</summary>
/// <param name="module">The module code.</param>
/// <returns><see langword="true"/> if licensed.</returns>
public bool Includes(string module) => Modules.Contains(module);
/// <summary>Days left before the expiry (0 when expired), or <see langword="null"/> without expiry.</summary>
/// <param name="now">The current time.</param>
/// <returns>The days.</returns>
public int? DaysLeft(DateTime now) => ExpiresAt is { } expires ? Math.Max(0, (int)Math.Ceiling((expires - now).TotalDays)) : null;
}
/// <summary>
/// The fictitious licence codes of SPEC §8.3, valid only with <c>KHAEMHAT_LICENSE_MODE=test</c>. Outside test mode they
/// are refused with <c>license_test_only</c>. Automated tests use <see cref="All"/>.
/// </summary>
public static class TestLicenseCatalog
{
/// <summary>Every module.</summary>
public const string All = "KH-TEST-ALL-0000-9999";
/// <summary>25 concurrent users.</summary>
public const string Users25 = "KH-TEST-USERS-0025-0014";
/// <summary>60 more days of trial.</summary>
public const string TrialExtension = "KH-TEST-TRIAL-0060-0015";
private static readonly Dictionary<string, TestCode> 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),
};
/// <summary>Every code.</summary>
public static IReadOnlyCollection<string> AllCodes => Codes.Keys;
/// <summary>Whether the text looks like a fictitious code (to refuse it with the right error outside test mode).</summary>
/// <param name="text">The text.</param>
/// <returns><see langword="true"/> if it starts with <c>KH-TEST-</c>.</returns>
public static bool LooksLikeTestCode(string? text) => text?.Trim().StartsWith("KH-TEST-", StringComparison.OrdinalIgnoreCase) == true;
/// <summary>Finds a code.</summary>
/// <param name="code">The code.</param>
/// <returns>The effect, or <see langword="null"/> when unknown.</returns>
public static TestCode? Find(string code) => Codes.GetValueOrDefault(code.Trim().ToUpperInvariant());
private static TestCode Module(string module) => new([module], 0, 0);
}
/// <summary>The effect of a fictitious code.</summary>
/// <param name="Modules">The modules it activates.</param>
/// <param name="ConcurrentUsers">The users it grants (0 = no change).</param>
/// <param name="TrialExtensionDays">The days it adds to the trial.</param>
public sealed record TestCode(IReadOnlyList<string> Modules, int ConcurrentUsers, int TrialExtensionDays);
@@ -0,0 +1,152 @@
namespace Khaemhat.Application.Modules;
/// <summary>
/// The modules of SPEC §8.1 with their permissions. Codes follow <c>area.entity.action</c>; the area is functional
/// (<c>sales</c>, <c>ledger</c>...) while <see cref="PermissionDefinition.Module"/> is the licence code.
/// </summary>
public static class BuiltInModules
{
/// <summary>Every module, in the order of SPEC §8.1.</summary>
public static IReadOnlyList<IModule> 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))]);
}
/// <summary>A predefined role (SPEC §7.2): kept in <c>sys_roles_templates</c> and copied into each company.</summary>
/// <param name="Code">The role code.</param>
/// <param name="Name">The name shown.</param>
/// <param name="Description">What the role is for.</param>
/// <param name="Permissions">The permission patterns.</param>
public sealed record RoleTemplateDefinition(string Code, string Name, string Description, IReadOnlyList<string> Permissions);
/// <summary>The eight predefined roles of SPEC §7.2.</summary>
public static class PredefinedRoles
{
/// <summary>The administration role: every permission.</summary>
public const string Administration = "ADMIN";
/// <summary>The read-only role.</summary>
public const string ReadOnly = "READONLY";
/// <summary>The roles, in display order.</summary>
public static IReadOnlyList<RoleTemplateDefinition> 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"]),
];
}
@@ -0,0 +1,166 @@
namespace Khaemhat.Application.Modules;
/// <summary>The module codes of SPEC §8.1, which are also the licence codes.</summary>
public static class ModuleCodes
{
/// <summary>Base: parties, items, documents, warehouse, administration.</summary>
public const string Core = "CORE";
/// <summary>Accounting and VAT.</summary>
public const string Accounting = "ACCT";
/// <summary>Fixed assets.</summary>
public const string Assets = "ASSET";
/// <summary>Treasury.</summary>
public const string Finance = "FIN";
/// <summary>Electronic invoicing.</summary>
public const string EInvoicing = "EINV";
/// <summary>Intrastat.</summary>
public const string Intrastat = "INTRA";
/// <summary>CRM.</summary>
public const string Crm = "CRM";
/// <summary>Services.</summary>
public const string Services = "SVC";
/// <summary>E-commerce channels.</summary>
public const string Channels = "CHAN";
/// <summary>Automations.</summary>
public const string Automation = "AUTO";
/// <summary>API, MCP and webhooks.</summary>
public const string Api = "API";
/// <summary>Companies beyond the first.</summary>
public const string MultiCompany = "MULTI";
/// <summary>Advanced reports.</summary>
public const string Reports = "REPORT";
}
/// <summary>A permission a module declares: a code <c>module.entity.action</c> (SPEC §7.2).</summary>
/// <param name="Code">The code, for example <c>sales.invoice.issue</c>.</param>
/// <param name="Module">The licence code of the module that owns it.</param>
/// <param name="Description">What it allows, in Italian (shown in the permission matrix).</param>
public sealed record PermissionDefinition(string Code, string Module, string Description);
/// <summary>A functional module (SPEC §8.1): its licence code, its name and the permissions it declares.</summary>
public interface IModule
{
/// <summary>The licence code.</summary>
string Code { get; }
/// <summary>The name shown in the interface.</summary>
string Name { get; }
/// <summary>The permissions.</summary>
IReadOnlyList<PermissionDefinition> Permissions { get; }
}
/// <summary>A module declared in code.</summary>
/// <param name="Code">The licence code.</param>
/// <param name="Name">The name shown.</param>
/// <param name="Permissions">The permissions.</param>
public sealed record ModuleDefinition(string Code, string Name, IReadOnlyList<PermissionDefinition> Permissions) : IModule;
/// <summary>
/// The modules of the product and their permissions. The list is static: what the licence does not include stays
/// declared but is filtered by <c>ILicenseGate</c> (menus hidden, permissions denied with
/// <c>module_not_licensed</c>). Each milestone adds the permissions of the screens it delivers.
/// </summary>
public sealed class ModuleRegistry
{
private readonly Dictionary<string, IModule> _modules;
private readonly Dictionary<string, PermissionDefinition> _permissions;
/// <summary>Creates a registry.</summary>
/// <param name="modules">The modules.</param>
/// <exception cref="InvalidOperationException">Two modules share a code, or two permissions share a code.</exception>
public ModuleRegistry(IEnumerable<IModule> modules)
{
ArgumentNullException.ThrowIfNull(modules);
_modules = new Dictionary<string, IModule>(StringComparer.Ordinal);
_permissions = new Dictionary<string, PermissionDefinition>(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.");
}
}
}
}
/// <summary>The registry of the product modules.</summary>
public static ModuleRegistry Default { get; } = new(BuiltInModules.All);
/// <summary>The modules, in the order of SPEC §8.1.</summary>
public IReadOnlyCollection<IModule> Modules => _modules.Values;
/// <summary>Every permission.</summary>
public IReadOnlyCollection<PermissionDefinition> Permissions => _permissions.Values;
/// <summary>Finds a module.</summary>
/// <param name="code">The licence code.</param>
/// <returns>The module, or <see langword="null"/>.</returns>
public IModule? FindModule(string code) => _modules.GetValueOrDefault(code);
/// <summary>Finds a permission.</summary>
/// <param name="code">The permission code.</param>
/// <returns>The permission, or <see langword="null"/>.</returns>
public PermissionDefinition? FindPermission(string code) => _permissions.GetValueOrDefault(code);
/// <summary>The permissions a pattern grants (<c>*</c>, <c>sales.*</c>, <c>*.read</c> or a code).</summary>
/// <param name="pattern">The pattern.</param>
/// <returns>The matching permissions.</returns>
public IEnumerable<PermissionDefinition> Expand(string pattern) => _permissions.Values.Where(p => PermissionPattern.Matches(pattern, p.Code));
}
/// <summary>Permission codes and the patterns used by roles: <c>*</c>, <c>module.*</c>, <c>*.action</c> or an exact code.</summary>
public static class PermissionPattern
{
/// <summary>Whether <paramref name="code"/> has the form <c>module.entity.action</c> (two or three lower-case segments).</summary>
/// <param name="code">The code.</param>
/// <returns><see langword="true"/> if valid.</returns>
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 '_'));
/// <summary>Whether a pattern grants a permission code.</summary>
/// <param name="pattern">The pattern.</param>
/// <param name="code">The permission code.</param>
/// <returns><see langword="true"/> if it matches.</returns>
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);
}
}
@@ -0,0 +1,102 @@
using Khaemhat.Core.Instance;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.Notifications;
/// <summary>A notification to deliver.</summary>
/// <param name="Category">The area: <c>security</c>, <c>jobs</c>, <c>system</c>, <c>licenses</c>...</param>
/// <param name="Severity">The weight.</param>
/// <param name="Title">The title.</param>
/// <param name="Body">The text.</param>
/// <param name="Link">A link inside the application.</param>
public sealed record NotificationMessage(string Category, NotificationSeverity Severity, string Title, string? Body = null, string? Link = null);
/// <summary>
/// Delivers in-app notifications (SPEC §9; mockup 010): to instance accounts in <c>sys_notifications</c>, to company
/// users in the company's <c>notifications</c>. A notification without recipient goes to everyone in the scope.
/// Delivery never breaks the caller: a failure is logged.
/// </summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="logger">The log.</param>
public sealed class NotificationDispatcher(IUnitOfWorkFactory factory, ILogger<NotificationDispatcher> logger)
{
/// <summary>Notifies instance accounts.</summary>
/// <param name="message">The notification.</param>
/// <param name="recipientUserId">One account, or <see langword="null"/> for all of them.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<SystemNotification, long>().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);
}
}
/// <summary>Notifies the users of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="message">The notification.</param>
/// <param name="recipientUserId">One user, or <see langword="null"/> for all of them.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<Notification, long>().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);
}
}
/// <summary>The unread notifications of an instance account (its own and those for everyone).</summary>
/// <param name="userId">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The notifications, newest first.</returns>
public async Task<IReadOnlyList<SystemNotification>> UnreadForInstanceAsync(long userId, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<SystemNotification, long>().ListAsync(
Query.For<SystemNotification>().Where(n => n.ReadAt == null && (n.RecipientUserId == null || n.RecipientUserId == userId)).OrderByDescending(n => n.Id).Take(100),
cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>The unread notifications of a company user.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The notifications, newest first.</returns>
public async Task<IReadOnlyList<Notification>> 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<Notification, long>().ListAsync(
Query.For<Notification>().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>(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];
}
@@ -0,0 +1,351 @@
using System.Text.Json;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>The outcome of a password check at sign-in.</summary>
/// <param name="Succeeded">Whether the password was right and the account may go on.</param>
/// <param name="Error">The error code when it did not succeed (<see cref="SecurityErrors"/>).</param>
/// <param name="MustChangePassword">The password must be changed before entering.</param>
public sealed record PasswordCheck(bool Succeeded, string? Error, bool MustChangePassword)
{
/// <summary>A failure.</summary>
/// <param name="error">The error code.</param>
/// <returns>The outcome.</returns>
public static PasswordCheck Fail(string error) => new(false, error, false);
}
/// <summary>
/// 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.
/// </summary>
public sealed class AccountSecurity
{
private const string SecretPurpose = "account:totp";
private readonly PasswordPolicy _policy;
private readonly ISecretProtector _protector;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="policy">The password policy.</param>
/// <param name="protector">Encrypts TOTP secrets.</param>
/// <param name="clock">The clock.</param>
public AccountSecurity(PasswordPolicy policy, ISecretProtector protector, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(policy);
ArgumentNullException.ThrowIfNull(protector);
ArgumentNullException.ThrowIfNull(clock);
_policy = policy;
_protector = protector;
_clock = clock;
}
/// <summary>The policy settings.</summary>
public SecurityPolicyOptions Options => _policy.Options;
private DateTime Now => _clock.GetUtcNow().UtcDateTime;
/// <summary>Checks the password typed at sign-in, counting failures and locking the account after too many.</summary>
/// <param name="account">The account.</param>
/// <param name="password">The password typed.</param>
/// <returns>The outcome.</returns>
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);
}
/// <summary>Records a completed sign-in.</summary>
/// <param name="account">The account.</param>
public void RecordSignIn(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
account.LastLoginAt = Now;
}
/// <summary>Sets a new password chosen by the user, after checking policy and history.</summary>
/// <param name="account">The account.</param>
/// <param name="newPassword">The new password.</param>
/// <returns>The error codes; empty when the password was set.</returns>
public IReadOnlyList<string> ChangePassword(IAccount account, string newPassword)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(newPassword);
var errors = new List<string>(_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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="account">The account.</param>
/// <param name="password">The password.</param>
/// <param name="temporary">Whether it expires after <see cref="SecurityPolicyOptions.TemporaryPasswordLifetime"/>.</param>
/// <returns>The policy error codes; empty when the password was set.</returns>
public IReadOnlyList<string> 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;
}
/// <summary>Creates a temporary password that satisfies the policy and sets it.</summary>
/// <param name="account">The account.</param>
/// <returns>The password to give to the user, once.</returns>
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;
}
/// <summary>Creates a single-use recovery token, valid for <see cref="SecurityPolicyOptions.RecoveryTokenLifetime"/>.</summary>
/// <param name="account">The account.</param>
/// <returns>The token to send by e-mail; only its hash is stored.</returns>
public string IssueRecoveryToken(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
var token = SecureTokenGenerator.Create();
account.RecoveryTokenHash = SecureTokenGenerator.Hash(token);
account.RecoveryTokenExpiresAt = Now + Options.RecoveryTokenLifetime;
return token;
}
/// <summary>Uses a recovery token to set a new password. The token stops working whatever the outcome of the policy.</summary>
/// <param name="account">The account.</param>
/// <param name="token">The token from the e-mail.</param>
/// <param name="newPassword">The new password.</param>
/// <returns>The error codes; empty when the password was set.</returns>
public IReadOnlyList<string> 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;
}
/// <summary>Starts the TOTP setup: a new secret, stored encrypted and not yet active.</summary>
/// <param name="account">The account.</param>
/// <returns>The secret in base32, to show once with <see cref="TotpGenerator.ProvisioningUri"/>.</returns>
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;
}
/// <summary>The secret of a setup started and not yet confirmed, so that reloading the page shows the same one.</summary>
/// <param name="account">The account.</param>
/// <returns>The secret in base32, or <see langword="null"/> when no setup is pending.</returns>
public string? PendingTotpSecret(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
return account is { TotpEnabled: false, TotpSecret: { } secret } ? _protector.Unprotect(secret, SecretPurpose) : null;
}
/// <summary>Completes the TOTP setup with a first code from the app, and creates the recovery codes.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The code shown by the app.</param>
/// <returns>The ten recovery codes to show once; <see langword="null"/> if the code is wrong.</returns>
public IReadOnlyList<string>? 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;
}
/// <summary>Checks a TOTP code at sign-in. A code is never accepted twice.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The code.</param>
/// <returns>Whether the code is valid.</returns>
public bool VerifyTotp(IAccount account, string code)
{
ArgumentNullException.ThrowIfNull(account);
return account.TotpEnabled && account.TotpSecret is not null && VerifyCode(account, code);
}
/// <summary>Uses one of the recovery codes in place of a TOTP code. Each code works once.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The recovery code.</param>
/// <returns>Whether the code was valid.</returns>
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;
}
/// <summary>Turns the two-step verification off (an administrator resetting a lost phone).</summary>
/// <param name="account">The account.</param>
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<string> Deserialize(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return [];
}
try
{
return JsonSerializer.Deserialize<List<string>>(json) ?? [];
}
catch (JsonException)
{
return [];
}
}
}
@@ -0,0 +1,85 @@
using Khaemhat.Core.Security;
namespace Khaemhat.Application.Security;
/// <summary>
/// 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.
/// </summary>
/// <param name="UserName">The user name, written in the audit columns and logs.</param>
/// <param name="Level">The level.</param>
/// <param name="SystemUserId">The instance account, for super user and administrators.</param>
/// <param name="CompanyUserId">The company user (or the user an administrator is linked to).</param>
/// <param name="CompanyCode">The company the actor works in.</param>
public sealed record Actor(string UserName, UserLevel Level, long? SystemUserId, long? CompanyUserId, string? CompanyCode)
{
/// <summary>The instance itself: bootstrap, scheduled jobs.</summary>
public static Actor System { get; } = new("system", UserLevel.SuperUser, null, null, null);
/// <summary>Whether the actor is an instance account.</summary>
public bool IsInstanceAccount => Level >= UserLevel.Administrator;
/// <summary>Whether the actor is the super user.</summary>
public bool IsSuperUser => Level == UserLevel.SuperUser;
}
/// <summary>An action the actor may not perform. <see cref="Code"/> is one of <see cref="SecurityErrors"/>.</summary>
public sealed class AccessDeniedException : Exception
{
/// <summary>Creates the exception.</summary>
public AccessDeniedException()
: this(SecurityErrors.PermissionDenied, "Access denied.")
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public AccessDeniedException(string message)
: this(SecurityErrors.PermissionDenied, message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public AccessDeniedException(string message, Exception innerException)
: base(message, innerException) => Code = SecurityErrors.PermissionDenied;
/// <summary>Creates the exception.</summary>
/// <param name="code">The error code.</param>
/// <param name="message">The message.</param>
public AccessDeniedException(string code, string message)
: base(message) => Code = code;
/// <summary>The error code.</summary>
public string Code { get; }
}
/// <summary>A request the rules refuse (policy, duplicates); <see cref="Errors"/> holds error codes for the interface.</summary>
public sealed class ValidationFailedException : Exception
{
/// <summary>Creates the exception.</summary>
public ValidationFailedException()
: this([])
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public ValidationFailedException(string message)
: base(message) => Errors = [message];
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public ValidationFailedException(string message, Exception innerException)
: base(message, innerException) => Errors = [message];
/// <summary>Creates the exception.</summary>
/// <param name="errors">The error codes.</param>
public ValidationFailedException(IReadOnlyList<string> errors)
: base("The request is not valid: " + string.Join(", ", errors ?? [])) => Errors = errors ?? [];
/// <summary>The error codes.</summary>
public IReadOnlyList<string> Errors { get; }
}
@@ -0,0 +1,165 @@
using System.Text.RegularExpressions;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>Sign-in names: 3 to 50 characters, letters, digits, dot, dash and underscore; compared in lower case.</summary>
public static partial class UserNames
{
/// <summary>Whether a name has the allowed form.</summary>
/// <param name="name">The name.</param>
/// <returns><see langword="true"/> if valid.</returns>
public static bool IsValid(string? name) => name is not null && Pattern().IsMatch(name.Trim());
/// <summary>The stored form: trimmed, lower case.</summary>
/// <param name="name">The name.</param>
/// <returns>The normalized name.</returns>
/// <exception cref="ArgumentException">The name is not valid.</exception>
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();
}
/// <summary>The security settings of accounts (SPEC §7.3). The defaults are those of the specification.</summary>
public sealed record SecurityPolicyOptions
{
/// <summary>Minimum password length.</summary>
public int MinimumLength { get; init; } = 10;
/// <summary>Minimum character classes among lower case, upper case, digits and symbols.</summary>
public int MinimumClasses { get; init; } = 3;
/// <summary>How many previous passwords cannot be reused.</summary>
public int HistorySize { get; init; } = 5;
/// <summary>Days after which a password must be changed; <see langword="null"/> for no expiry.</summary>
public int? ExpiryDays { get; init; }
/// <summary>Failed sign-ins before the account is locked.</summary>
public int MaxFailedAttempts { get; init; } = 5;
/// <summary>How long a locked account stays locked.</summary>
public TimeSpan LockoutDuration { get; init; } = TimeSpan.FromMinutes(15);
/// <summary>How long a temporary password works.</summary>
public TimeSpan TemporaryPasswordLifetime { get; init; } = TimeSpan.FromHours(72);
/// <summary>How long a password-recovery link works.</summary>
public TimeSpan RecoveryTokenLifetime { get; init; } = TimeSpan.FromMinutes(30);
/// <summary>The sliding lifetime of a session.</summary>
public TimeSpan SessionLifetime { get; init; } = TimeSpan.FromMinutes(480);
/// <summary>The lifetime of a session with "remember me on this device".</summary>
public TimeSpan PersistentSessionLifetime { get; init; } = TimeSpan.FromDays(14);
/// <summary>The time to complete a pending sign-in step (TOTP, password change).</summary>
public TimeSpan PendingStepLifetime { get; init; } = TimeSpan.FromMinutes(10);
/// <summary>Whether company users must use the two-step verification.</summary>
public bool TotpRequiredForUsers { get; init; }
/// <summary>PBKDF2 iterations; lowered only by tests.</summary>
public int HashIterations { get; init; } = PasswordHasher.Iterations;
}
/// <summary>Checks new passwords against the policy.</summary>
/// <param name="options">The policy.</param>
public sealed class PasswordPolicy(SecurityPolicyOptions options)
{
/// <summary>The policy settings.</summary>
public SecurityPolicyOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>Checks the form of a password.</summary>
/// <param name="password">The new password.</param>
/// <param name="userName">The user name, which the password must not contain.</param>
/// <returns>Error codes: <c>password_too_short</c>, <c>password_too_simple</c>, <c>password_contains_user_name</c>.</returns>
public IReadOnlyList<string> Check(string password, string? userName)
{
ArgumentNullException.ThrowIfNull(password);
var errors = new List<string>();
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;
}
}
/// <summary>The error codes of the security services; the interface turns them into Italian messages.</summary>
public static class SecurityErrors
{
/// <summary>Wrong user, company or password (never says which).</summary>
public const string InvalidCredentials = "invalid_credentials";
/// <summary>Too many failed attempts: the account is locked for a while.</summary>
public const string AccountLocked = "account_locked";
/// <summary>The account is disabled.</summary>
public const string AccountDisabled = "account_disabled";
/// <summary>The temporary password has expired.</summary>
public const string TemporaryPasswordExpired = "temporary_password_expired";
/// <summary>The password is shorter than the policy.</summary>
public const string PasswordTooShort = "password_too_short";
/// <summary>The password uses too few character classes.</summary>
public const string PasswordTooSimple = "password_too_simple";
/// <summary>The password contains the user name.</summary>
public const string PasswordContainsUserName = "password_contains_user_name";
/// <summary>The password was used recently.</summary>
public const string PasswordReused = "password_reused";
/// <summary>The current password is wrong.</summary>
public const string CurrentPasswordWrong = "current_password_wrong";
/// <summary>The TOTP code is wrong or already used.</summary>
public const string TotpInvalid = "totp_invalid";
/// <summary>The recovery token is wrong, used or expired.</summary>
public const string RecoveryTokenInvalid = "recovery_token_invalid";
/// <summary>Too many attempts from this address.</summary>
public const string RateLimited = "rate_limited";
/// <summary>The licence allows no more concurrent users.</summary>
public const string ConcurrentUsersExceeded = "concurrent_users_exceeded";
/// <summary>The level of the account does not allow the action.</summary>
public const string LevelTooLow = "level_too_low";
/// <summary>The permission is missing.</summary>
public const string PermissionDenied = "permission_denied";
/// <summary>The module is not in the licence.</summary>
public const string ModuleNotLicensed = "module_not_licensed";
/// <summary>The company is in maintenance or disabled.</summary>
public const string CompanyUnavailable = "company_unavailable";
/// <summary>The licence allows no more of something (companies, users).</summary>
public const string LicenseLimitReached = "license_limit_reached";
}
@@ -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;
/// <summary>The per-user flags of SPEC §7.2.</summary>
/// <param name="OwnCustomersOnly">Sees only the customers assigned to the user.</param>
/// <param name="CanSeeCosts">Sees costs and margins.</param>
/// <param name="CanExport">Can export.</param>
/// <param name="CanUseApi">Can use the API.</param>
public sealed record UserFlags(bool OwnCustomersOnly, bool CanSeeCosts, bool CanExport, bool CanUseApi)
{
/// <summary>Everything allowed: instance accounts.</summary>
public static UserFlags Unrestricted { get; } = new(false, true, true, true);
}
/// <summary>What a user may do in a company, before the licence is applied. Cached per user.</summary>
/// <param name="AllAccess">Instance accounts: every permission.</param>
/// <param name="Granted">The patterns granted by roles and overrides.</param>
/// <param name="Denied">The patterns denied by overrides (they win).</param>
/// <param name="Flags">The per-user flags.</param>
public sealed record EffectivePermissions(bool AllAccess, IReadOnlyList<string> Granted, IReadOnlyList<string> Denied, UserFlags Flags)
{
/// <summary>Every permission.</summary>
public static EffectivePermissions All { get; } = new(true, ["*"], [], UserFlags.Unrestricted);
/// <summary>No permission.</summary>
public static EffectivePermissions None { get; } = new(false, [], [], new UserFlags(true, false, false, false));
/// <summary>Whether the roles and overrides allow a code (the licence is checked by <see cref="PermissionService"/>).</summary>
/// <param name="code">The permission code.</param>
/// <returns><see langword="true"/> if allowed.</returns>
public bool Allows(string code) =>
AllAccess || (!Denied.Any(d => PermissionPattern.Matches(d, code)) && Granted.Any(g => PermissionPattern.Matches(g, code)));
}
/// <summary>The outcome of a permission check: <see cref="Error"/> is <c>permission_denied</c>, <c>module_not_licensed</c> or <c>license_read_only</c>.</summary>
/// <param name="Allowed">Whether the action is allowed.</param>
/// <param name="Error">The reason otherwise.</param>
public sealed record PermissionCheck(bool Allowed, string? Error)
{
/// <summary>Allowed.</summary>
public static PermissionCheck Ok { get; } = new(true, null);
}
/// <summary>
/// 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
/// <c>module_not_licensed</c>; past the licence grace only <c>.read</c> permissions remain. Results are cached per user
/// under <c>kh:{company}:permissions:</c> and invalidated when roles or users change.
/// </summary>
public sealed class PermissionService(IUnitOfWorkFactory factory, ICacheProvider cache, ILicenseGate licenses, ModuleRegistry modules)
{
/// <summary>The error when the licence is expired beyond the grace period.</summary>
public const string LicenseReadOnly = "license_read_only";
private const string Area = "permissions";
private static readonly TimeSpan CacheTime = TimeSpan.FromMinutes(10);
/// <summary>The permissions of an actor in its company.</summary>
/// <param name="actor">The actor.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The permissions.</returns>
public async Task<EffectivePermissions> 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<EffectivePermissions>(LoadAsync(company, userId, ct)),
CacheTime,
cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks one permission, licence included.</summary>
/// <param name="actor">The actor.</param>
/// <param name="code">The permission code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome.</returns>
public async Task<PermissionCheck> 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);
}
/// <summary>Throws when the actor may not perform the action.</summary>
/// <param name="actor">The actor.</param>
/// <param name="code">The permission code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The permission is missing or the module is not licensed.</exception>
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.");
}
}
/// <summary>Whether the actor holds every permission a set of patterns would grant (roles are never above one's own).</summary>
/// <param name="actor">The actor.</param>
/// <param name="patterns">The patterns.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when nothing in the patterns exceeds the actor.</returns>
public async Task<bool> CoversAsync(Actor actor, IEnumerable<string> 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));
}
/// <summary>Forgets the cached permissions of a company, here and on the other instances.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask InvalidateAsync(string companyCode, CancellationToken cancellationToken = default) =>
cache.PublishInvalidationAsync(CacheKeys.Prefix(CompanyCodes.Normalize(companyCode), Area), cancellationToken);
private async Task<EffectivePermissions> 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<CompanyUser, long>().GetAsync(userId, cancellationToken).ConfigureAwait(false);
if (user is not { IsActive: true })
{
return EffectivePermissions.None;
}
var roleIds = (await unitOfWork.Repository<UserRole, long>()
.ListAsync(Query.For<UserRole>().Where(r => r.UserId == userId), cancellationToken).ConfigureAwait(false)).Items.Select(r => r.RoleId).ToArray();
var granted = roleIds.Length == 0
? []
: (await unitOfWork.Repository<RoleGrant, long>()
.ListAsync(Query.For<RoleGrant>().Where(g => roleIds.Contains(g.RoleId)), cancellationToken).ConfigureAwait(false)).Items
.Select(g => g.Permission).ToList();
var overrides = (await unitOfWork.Repository<UserPermissionOverride, long>()
.ListAsync(Query.For<UserPermissionOverride>().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));
}
}
@@ -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;
/// <summary>A role with its permission patterns.</summary>
/// <param name="Role">The role.</param>
/// <param name="Permissions">The patterns.</param>
public sealed record RoleWithPermissions(Role Role, IReadOnlyList<string> Permissions);
/// <summary>
/// Roles (SPEC §7.2): the eight predefined roles live as templates in <c>sys_roles_templates</c> and are copied into each
/// company, where they can be cloned but not changed. Users with <c>company.users.manage</c> manage roles never above
/// their own permissions.
/// </summary>
public sealed class RoleService(IUnitOfWorkFactory factory, PermissionService permissions, ISecurityAuditLog audit)
{
/// <summary>Writes or updates the predefined templates in the system database (bootstrap and every start).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SeedTemplatesAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var templates = unitOfWork.Repository<RoleTemplate, long>();
var existing = (await templates.ListAsync(Query.For<RoleTemplate>(), 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);
}
/// <summary>
/// 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).
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SyncPredefinedRolesAsync(string companyCode, CancellationToken cancellationToken = default)
{
IReadOnlyList<RoleTemplate> templates;
await using (var system = await factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
templates = (await system.Repository<RoleTemplate, long>().ListAsync(Query.For<RoleTemplate>().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<Role, long>();
var grants = unitOfWork.Repository<RoleGrant, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var template in templates)
{
var code = template.Code;
var role = await roles.FindAsync(Query.For<Role>().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<List<string>>(template.Permissions) ?? [];
await ReplaceGrantsAsync(grants, role.Id, wanted, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
await permissions.InvalidateAsync(companyCode, cancellationToken).ConfigureAwait(false);
}
/// <summary>The roles of a company with their permissions.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The roles, predefined first.</returns>
public async Task<IReadOnlyList<RoleWithPermissions>> ListAsync(string companyCode, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
var roles = (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>().OrderByDescending(r => r.IsPredefined).OrderBy(r => r.Name), cancellationToken)
.ConfigureAwait(false)).Items;
var grants = (await unitOfWork.Repository<RoleGrant, long>().ListAsync(Query.For<RoleGrant>(), 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)]))];
}
/// <summary>Clones a role into a new, modifiable one.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="sourceCode">The role to clone.</param>
/// <param name="newCode">The new code.</param>
/// <param name="newName">The new name.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new role.</returns>
public async Task<Role> 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<Role, long>();
var grants = unitOfWork.Repository<RoleGrant, long>();
var source = await roles.FindAsync(Query.For<Role>().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<RoleGrant>().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<Role>().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;
}
/// <summary>Sets the permissions of a cloned role. Predefined roles are refused.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="roleCode">The role.</param>
/// <param name="patterns">The new permission patterns.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetPermissionsAsync(Actor actor, string companyCode, string roleCode, IReadOnlyList<string> 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<Role, long>().FindAsync(Query.For<Role>().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<RoleGrant, long>(), 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);
}
/// <summary>Checks that the actor may manage users and roles of a company.</summary>
/// <param name="actor">The actor.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="AccessDeniedException">The actor may not.</exception>
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<RoleGrant, long> grants, long roleId, IEnumerable<string> patterns, CancellationToken cancellationToken)
{
var current = (await grants.ListAsync(Query.For<RoleGrant>().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);
}
}
}
@@ -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;
/// <summary>
/// Who a session belongs to: an instance account (<c>sys_sessions</c>) or a user of a company (<c>user_sessions</c> in
/// that company's database).
/// </summary>
/// <param name="CompanyDatabase">The company whose database holds the user; <see langword="null"/> for instance accounts.</param>
/// <param name="UserId">The account.</param>
public sealed record SessionOwner(string? CompanyDatabase, long UserId)
{
/// <summary>Whether the owner is an instance account.</summary>
public bool IsInstanceAccount => CompanyDatabase is null;
}
/// <summary>What a valid session says about its user, resolved at each request and cached briefly.</summary>
/// <param name="SessionId">The session row.</param>
/// <param name="Owner">The owner.</param>
/// <param name="State">The sign-in state.</param>
/// <param name="UserName">The user name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Level">The level.</param>
/// <param name="CompanyCode">The company the session works in.</param>
/// <param name="LinkedUserId">For administrators linked to a user of <paramref name="CompanyCode"/>: that user.</param>
/// <param name="ExpiresAt">When the session expires unless used.</param>
/// <param name="Persistent">Whether the cookie survives the browser.</param>
public sealed record SessionIdentity(
long SessionId, SessionOwner Owner, SessionState State, string UserName, string DisplayName, UserLevel Level,
string? CompanyCode, long? LinkedUserId, DateTime ExpiresAt, bool Persistent)
{
/// <summary>The actor for the services.</summary>
/// <returns>The actor.</returns>
public Actor ToActor() => Owner.IsInstanceAccount
? new Actor(UserName, Level, Owner.UserId, LinkedUserId, CompanyCode)
: new Actor(UserName, UserLevel.Standard, null, Owner.UserId, CompanyCode);
}
/// <summary>A session as listed to its user or to administrators.</summary>
/// <param name="Id">The session row.</param>
/// <param name="CreatedAt">The sign-in time.</param>
/// <param name="LastSeenAt">The last request.</param>
/// <param name="IpAddress">The client address.</param>
/// <param name="UserAgent">The browser.</param>
/// <param name="CompanyCode">The company.</param>
public sealed record SessionSummary(long Id, DateTime CreatedAt, DateTime LastSeenAt, string? IpAddress, string? UserAgent, string? CompanyCode);
/// <summary>
/// Sign-in sessions (SPEC §7.3). The cookie value is <c>&lt;scope&gt;.&lt;token&gt;</c>: the scope says which database
/// holds the row (<c>_</c> 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.
/// </summary>
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;
/// <summary>Creates the store.</summary>
/// <param name="factory">Opens the databases.</param>
/// <param name="companies">The company registry.</param>
/// <param name="cache">The cache of resolved sessions.</param>
/// <param name="policy">Session lifetimes.</param>
/// <param name="clock">The clock.</param>
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);
/// <summary>Creates a session.</summary>
/// <param name="owner">The owner.</param>
/// <param name="state">The sign-in state.</param>
/// <param name="companyCode">The company the session works in.</param>
/// <param name="ipAddress">The client address.</param>
/// <param name="userAgent">The browser.</param>
/// <param name="persistent">"Remember me on this device".</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The cookie value.</returns>
public async Task<string> 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<SystemSession, long>().InsertAsync(system, cancellationToken).ConfigureAwait(false);
}
else
{
await unitOfWork.Repository<UserSession, long>().InsertAsync((UserSession)session, cancellationToken).ConfigureAwait(false);
}
return (owner.CompanyDatabase ?? SystemScope) + "." + token;
}
/// <summary>Finds the valid session of a cookie (not revoked, not expired) and slides its expiry.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The session row and owner, or <see langword="null"/>.</returns>
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<SystemSession, long>().FindAsync(Query.For<SystemSession>().Where(s => s.TokenHash == hash), cancellationToken).ConfigureAwait(false)
: (SessionRecord?)await unitOfWork.Repository<UserSession, long>().FindAsync(Query.For<UserSession>().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 });
}
/// <summary>Moves a session to another sign-in state and gives it a new token (the old cookie stops working).</summary>
/// <param name="cookie">The current cookie value.</param>
/// <param name="state">The new state.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new cookie value, or <see langword="null"/> when the session is not valid.</returns>
public async Task<string?> 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;
}
/// <summary>Changes the company a session of an instance account works in.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="companyCode">The company, or <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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);
}
/// <summary>Revokes the session of a cookie (sign-out).</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The owner of the revoked session, or <see langword="null"/>.</returns>
public async Task<SessionOwner?> 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;
}
/// <summary>Revokes one session of an owner (from the list of sessions).</summary>
/// <param name="owner">The owner.</param>
/// <param name="sessionId">The session row.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Whether a session was revoked.</returns>
public async Task<bool> 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;
}
/// <summary>Revokes every session of an owner, except one (password change, administrator action).</summary>
/// <param name="owner">The owner.</param>
/// <param name="reason">Why.</param>
/// <param name="exceptSessionId">The session to keep.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of sessions revoked.</returns>
public Task<int> 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);
}
/// <summary>
/// Revokes every session of the users of a company (maintenance, disabling): instance accounts keep theirs, also when
/// they work in that company.
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="reason">Why.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of sessions revoked.</returns>
public async Task<int> 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;
}
/// <summary>Whether a signed-in session is still valid (the periodic check of open Blazor circuits).</summary>
/// <param name="owner">The owner.</param>
/// <param name="sessionId">The session row.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> while the session is active, not revoked and not expired.</returns>
public async Task<bool> 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<SystemSession, long>().CountAsync(
Query.For<SystemSession>().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<UserSession, long>().CountAsync(
Query.For<UserSession>().Where(s => s.Id == sessionId && s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now && s.State == SessionState.Active),
cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>The active sessions of an owner.</summary>
/// <param name="owner">The owner.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The sessions, most recent first.</returns>
public async Task<IReadOnlyList<SessionSummary>> 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<SessionRecord> sessions = owner.IsInstanceAccount
? (await unitOfWork.Repository<SystemSession, long>().ListAsync(
Query.For<SystemSession>().Where(s => s.UserId == userId && s.RevokedAt == null && s.ExpiresAt > now).OrderByDescending(s => s.LastSeenAt), cancellationToken)
.ConfigureAwait(false)).Items
: (await unitOfWork.Repository<UserSession, long>().ListAsync(
Query.For<UserSession>().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))];
}
/// <summary>Whether an owner has signed in before from the same browser (to warn about new devices).</summary>
/// <param name="owner">The owner.</param>
/// <param name="userAgent">The browser.</param>
/// <param name="exceptSessionId">The session just created.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> if a previous session used the same browser.</returns>
public async Task<bool> 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<SystemSession, long>().CountAsync(
Query.For<SystemSession>().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken)
.ConfigureAwait(false) > 0
: await unitOfWork.Repository<UserSession, long>().CountAsync(
Query.For<UserSession>().Where(s => s.UserId == userId && s.UserAgent == agent && s.Id != exceptSessionId && s.State == SessionState.Active), cancellationToken)
.ConfigureAwait(false) > 0;
}
/// <summary>
/// The users with an active session across the system database and every company (the concurrent-user limit of the
/// licence, SPEC §7.3).
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The owners with at least one active session.</returns>
public async Task<IReadOnlySet<SessionOwner>> ActiveOwnersAsync(CancellationToken cancellationToken = default)
{
var now = Now;
var owners = new HashSet<SessionOwner>();
await using (var system = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
{
var rows = await system.QueryAsync<long>(
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<long>(
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;
}
/// <summary>Deletes sessions expired or revoked more than <paramref name="age"/> ago (the cleanup job).</summary>
/// <param name="scope">The database.</param>
/// <param name="age">How long to keep them for the history.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows deleted.</returns>
public async Task<int> 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);
}
/// <summary>The cache key of a cookie's resolved identity.</summary>
/// <param name="cookie">The cookie value.</param>
/// <returns>The key.</returns>
public static string CacheKey(string cookie) => CacheKeys.For(null, CacheArea, SecureTokenGenerator.Hash(cookie ?? string.Empty));
/// <summary>Forgets the cached identity of a cookie.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public ValueTask ForgetAsync(string cookie, CancellationToken cancellationToken = default) => _cache.RemoveAsync(CacheKey(cookie), cancellationToken);
/// <summary>How long a resolved identity may stay cached (revocations by id also clear the whole area).</summary>
public static TimeSpan IdentityCacheTime => CacheTime;
private async Task<int> RevokeWhereAsync(SessionOwner owner, System.Linq.Expressions.Expression<Func<SessionRecord, bool>> 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<SessionRecord> sessions = owner.IsInstanceAccount
? (await unitOfWork.Repository<SystemSession, long>().ListAsync(Query.For<SystemSession>().Where(s => s.UserId == userId && s.RevokedAt == null), cancellationToken).ConfigureAwait(false)).Items
: (await unitOfWork.Repository<UserSession, long>().ListAsync(Query.For<UserSession>().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<SystemSession, long>().UpdateAsync(system, cancellationToken).ConfigureAwait(false);
}
else
{
await unitOfWork.Repository<UserSession, long>().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<IUnitOfWork> 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];
}
@@ -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;
/// <summary>A sign-in attempt from the login page (mockup 001).</summary>
/// <param name="CompanyCode">The company chosen; instance accounts may leave it empty.</param>
/// <param name="UserName">The user name.</param>
/// <param name="Password">The password.</param>
/// <param name="Persistent">"Remember me on this device".</param>
/// <param name="IpAddress">The client address.</param>
/// <param name="UserAgent">The browser.</param>
public sealed record SignInRequest(string? CompanyCode, string UserName, string Password, bool Persistent, string? IpAddress, string? UserAgent);
/// <summary>The outcome of a sign-in step.</summary>
/// <param name="Succeeded">Whether the step succeeded.</param>
/// <param name="Error">The error code otherwise (<see cref="SecurityErrors"/>).</param>
/// <param name="Cookie">The new cookie value to set.</param>
/// <param name="State">The state reached: the page to show next.</param>
public sealed record SignInResult(bool Succeeded, string? Error, string? Cookie, SessionState? State)
{
/// <summary>A failure.</summary>
/// <param name="error">The error code.</param>
/// <returns>The outcome.</returns>
public static SignInResult Fail(string error) => new(false, error, null, null);
}
/// <summary>The data of a TOTP setup, shown once.</summary>
/// <param name="Secret">The secret in base32, for manual entry.</param>
/// <param name="ProvisioningUri">The <c>otpauth://</c> address.</param>
public sealed record TotpSetup(string Secret, string ProvisioningUri);
/// <summary>
/// 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 <c>sys_security_audit</c>; the error never says whether the user exists.
/// </summary>
public sealed class SignInService(
SystemUserService systemUsers,
UserService companyUsers,
ICompanyRegistry companies,
AccountSecurity security,
SessionStore sessions,
ILicenseGate licenses,
NotificationDispatcher notifications,
ISecurityAuditLog audit,
ILogger<SignInService> logger)
{
/// <summary>Checks company, user and password and opens a session in the first state.</summary>
/// <param name="request">The attempt.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome and the cookie.</returns>
public async Task<SignInResult> 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);
}
/// <summary>Checks the TOTP code (or a recovery code) of a session waiting for it.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome and the new cookie.</returns>
public async Task<SignInResult> 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);
}
/// <summary>Starts the TOTP setup of a session waiting for it, or of a complete session (profile).</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The secret to show, or <see langword="null"/> when the session is not valid.</returns>
public async Task<TotpSetup?> 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));
}
/// <summary>Completes the TOTP setup with the first code from the app.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome, the new cookie and the recovery codes to show once.</returns>
public async Task<(SignInResult Result, IReadOnlyList<string>? 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);
}
/// <summary>Changes the password: the forced change of mockup 003, or a change from the profile.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="currentPassword">The current (or temporary) password.</param>
/// <param name="newPassword">The new password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome, with every policy error code joined in <see cref="SignInResult.Error"/>.</returns>
public async Task<SignInResult> 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);
}
/// <summary>Signs out: the session is revoked.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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);
}
}
/// <summary>Resolves the identity of a cookie for the authentication handler.</summary>
/// <param name="cookie">The cookie value.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The identity, or <see langword="null"/> when the session is not valid or the account cannot sign in anymore.</returns>
public async Task<SessionIdentity?> 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<SignInResult> CompleteAsync(
IAccount account, SessionOwner owner, string? companyCode, SignInRequest request, Func<CancellationToken, Task> 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<SignInResult> 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<CancellationToken, Task> 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<CancellationToken, Task> 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<CancellationToken, Task> 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);
}
}
/// <summary>A hash of a random password, compared when the user does not exist so the timing stays the same.</summary>
private static class DummyHash
{
public static readonly string Value = PasswordHasher.Hash(SecureTokenGenerator.Create());
}
}
@@ -0,0 +1,297 @@
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>A new instance account.</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Email">The e-mail address.</param>
public sealed record NewSystemUser(string UserName, string DisplayName, string? Email);
/// <summary>
/// Instance accounts (<c>sys_users</c>, 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.
/// </summary>
public sealed class SystemUserService
{
private readonly IUnitOfWorkFactory _factory;
private readonly AccountSecurity _security;
private readonly ISecurityAuditLog _audit;
/// <summary>Creates the service.</summary>
/// <param name="factory">Opens the system database.</param>
/// <param name="security">The credential rules.</param>
/// <param name="audit">The security audit.</param>
public SystemUserService(IUnitOfWorkFactory factory, AccountSecurity security, ISecurityAuditLog audit)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(security);
ArgumentNullException.ThrowIfNull(audit);
_factory = factory;
_security = security;
_audit = audit;
}
/// <summary>Whether any instance account exists (the bootstrap reads the variables only when none does).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when <c>sys_users</c> has rows.</returns>
public async Task<bool> AnyAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<SystemUser, long>().CountAsync(Query.For<SystemUser>(), cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>Lists the instance accounts.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The accounts, super user first.</returns>
public async Task<IReadOnlyList<SystemUser>> ListAsync(CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
var page = await unitOfWork.Repository<SystemUser, long>()
.ListAsync(Query.For<SystemUser>().OrderByDescending(u => u.Level).OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false);
return page.Items;
}
/// <summary>Finds an account by sign-in name.</summary>
/// <param name="userName">The name, in any case.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account, or <see langword="null"/>.</returns>
public async Task<SystemUser?> 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<SystemUser, long>().FindAsync(Query.For<SystemUser>().Where(u => u.UserName == name), cancellationToken)
.ConfigureAwait(false);
}
/// <summary>Finds an account.</summary>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account, or <see langword="null"/>.</returns>
public async Task<SystemUser?> GetAsync(long id, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
return await unitOfWork.Repository<SystemUser, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates the super user at first start, from <c>KHAEMHAT_SUPERUSER*</c>. Refused when a super user exists.
/// The password must be changed at the first access and the two-step verification set up.
/// </summary>
/// <param name="account">The account.</param>
/// <param name="password">The first password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account.</returns>
/// <exception cref="ValidationFailedException">The password does not satisfy the policy.</exception>
public async Task<SystemUser> 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<SystemUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
await unitOfWork.AcquireLockAsync("sys-users", ct).ConfigureAwait(false);
if (await users.CountAsync(Query.For<SystemUser>().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;
}
/// <summary>Creates an administrator with a temporary password. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="account">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The account and its temporary password, to give once.</returns>
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<SystemUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await users.CountAsync(Query.For<SystemUser>().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);
}
/// <summary>Changes name, e-mail and state of an account.</summary>
/// <param name="actor">Who acts: the super user, or an administrator on its own profile.</param>
/// <param name="id">The account.</param>
/// <param name="displayName">The new name.</param>
/// <param name="email">The new e-mail.</param>
/// <param name="isActive">The new state; the super user cannot be disabled.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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);
}
/// <summary>Gives an administrator a new temporary password. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The temporary password.</returns>
public async Task<string> 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!;
}
/// <summary>Turns off the two-step verification of an administrator who lost the phone. Only the super user may.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetTotpAsync(Actor actor, long id, CancellationToken cancellationToken = default) =>
ChangeAsync(actor, id, "user.totp-reset", AccountSecurity.ResetTotp, allowSelf: false, cancellationToken);
/// <summary>Links an administrator to a company user, to work as that user without a second sign-in.</summary>
/// <param name="actor">Who acts: the super user, or the administrator itself.</param>
/// <param name="id">The administrator.</param>
/// <param name="companyCode">The company, or <see langword="null"/> to remove the link.</param>
/// <param name="companyUserId">The company user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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);
/// <summary>Deletes an administrator. Only the super user may; the super user itself cannot be deleted.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="id">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<SystemUser, long>();
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);
}
/// <summary>Saves an account changed by the sign-in flow (failures, lockout, TOTP step, password).</summary>
/// <param name="user">The account.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<SystemUser, long>().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<SystemUser> 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<SystemUser, long>();
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);
}
}
@@ -0,0 +1,274 @@
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Security;
/// <summary>A new company user.</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown.</param>
/// <param name="Email">The e-mail address.</param>
/// <param name="Kind">A person or a technical user for the API.</param>
/// <param name="Roles">The role codes.</param>
/// <param name="Flags">The per-user flags.</param>
public sealed record NewCompanyUser(string UserName, string DisplayName, string? Email, UserKind Kind, IReadOnlyList<string> Roles, UserFlags Flags);
/// <summary>
/// Company users (<c>users</c>, SPEC §7.1): created by instance accounts or by company users holding
/// <c>company.users.manage</c>, who can never give roles above their own permissions.
/// </summary>
public sealed class UserService(IUnitOfWorkFactory factory, AccountSecurity security, PermissionService permissions, RoleService roles, ISecurityAuditLog audit)
{
/// <summary>Lists the users of a company.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The users by name.</returns>
public async Task<IReadOnlyList<CompanyUser>> ListAsync(string companyCode, CancellationToken cancellationToken = default)
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<CompanyUser, long>().ListAsync(Query.For<CompanyUser>().OrderBy(u => u.UserName), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Finds a user by sign-in name.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="userName">The name, in any case.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user, or <see langword="null"/>.</returns>
public async Task<CompanyUser?> 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<CompanyUser, long>().FindAsync(Query.For<CompanyUser>().Where(u => u.UserName == name), cancellationToken).ConfigureAwait(false);
}
/// <summary>Finds a user.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user, or <see langword="null"/>.</returns>
public async Task<CompanyUser?> 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<CompanyUser, long>().GetAsync(id, cancellationToken).ConfigureAwait(false);
}
/// <summary>Creates a user with a temporary password (people) or none (technical users).</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="request">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The user and its temporary password (<see langword="null"/> for technical users).</returns>
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<CompanyUser, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
if (await users.CountAsync(Query.For<CompanyUser>().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);
}
/// <summary>Replaces the roles of a user.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="roleCodes">The role codes.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetRolesAsync(Actor actor, string companyCode, long userId, IReadOnlyList<string> 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);
}
/// <summary>Grants or denies single permissions to a user over its roles. Denials win.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="overrides">Permission code and whether it is allowed.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task SetOverridesAsync(Actor actor, string companyCode, long userId, IReadOnlyDictionary<string, bool> 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<UserPermissionOverride, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
foreach (var old in (await repository.ListAsync(Query.For<UserPermissionOverride>().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);
}
/// <summary>Changes name, e-mail, flags and state of a user.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="displayName">The name.</param>
/// <param name="email">The e-mail.</param>
/// <param name="flags">The flags.</param>
/// <param name="isActive">Whether it can sign in.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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);
}
/// <summary>Gives a user a new temporary password.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The temporary password.</returns>
public async Task<string> 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!;
}
/// <summary>Turns off the two-step verification of a user who lost the phone.</summary>
/// <param name="actor">Who acts.</param>
/// <param name="companyCode">The company.</param>
/// <param name="userId">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task ResetTotpAsync(Actor actor, string companyCode, long userId, CancellationToken cancellationToken = default) =>
ChangeAsync(actor, companyCode, userId, "user.totp-reset", AccountSecurity.ResetTotp, cancellationToken);
/// <summary>Saves a user changed by the sign-in flow.</summary>
/// <param name="companyCode">The company.</param>
/// <param name="user">The user.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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<CompanyUser, long>().UpdateAsync(user, cancellationToken).ConfigureAwait(false);
}
private async Task ChangeAsync(Actor actor, string companyCode, long userId, string action, Action<CompanyUser> 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<CompanyUser, long>();
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<string> roleCodes, CancellationToken cancellationToken)
{
var codes = roleCodes.Select(r => r.Trim().ToUpperInvariant()).Distinct(StringComparer.Ordinal).ToArray();
var found = codes.Length == 0
? []
: (await unitOfWork.Repository<Role, long>().ListAsync(Query.For<Role>().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<RoleGrant, long>().ListAsync(Query.For<RoleGrant>().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<UserRole, long>();
foreach (var old in (await userRoles.ListAsync(Query.For<UserRole>().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);
}
}
}
@@ -0,0 +1,80 @@
namespace Khaemhat.Core.Caching;
/// <summary>
/// The application cache (SPEC §9): in memory, or Redis when <c>KHAEMHAT_REDIS</c> is set. Values are stored as JSON
/// in both cases, so the behaviour is the same with and without Redis. Keys follow <see cref="CacheKeys.For"/>.
/// </summary>
public interface ICacheProvider
{
/// <summary>Whether the cache is shared between instances (Redis reachable).</summary>
bool IsDistributed { get; }
/// <summary>Reads a value.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value, or <see langword="default"/> when missing or expired.</returns>
ValueTask<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default);
/// <summary>Stores a value.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="timeToLive">How long it stays.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask SetAsync<T>(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default);
/// <summary>Removes a value.</summary>
/// <param name="key">The key.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default);
/// <summary>Removes every key that starts with <paramref name="prefix"/>.</summary>
/// <param name="prefix">The prefix, for example <c>kh:DEMO:permissions:</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask RemoveByPrefixAsync(string prefix, CancellationToken cancellationToken = default);
/// <summary>Reads a value, or creates and stores it.</summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="factory">Creates the value when missing.</param>
/// <param name="timeToLive">How long it stays.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The value.</returns>
ValueTask<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, ValueTask<T>> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default);
/// <summary>
/// Removes the keys with <paramref name="prefix"/> here and tells the other instances to do the same (Redis pub/sub).
/// </summary>
/// <param name="prefix">The prefix.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default);
}
/// <summary>Cache keys: <c>kh:{company}:{area}:{key}</c>, with <c>_</c> for the instance (SPEC §9).</summary>
public static class CacheKeys
{
/// <summary>The instance scope.</summary>
public const string Instance = "_";
/// <summary>A key.</summary>
/// <param name="company">The company code, or <see langword="null"/> for the instance.</param>
/// <param name="area">The area, for example <c>permissions</c>.</param>
/// <param name="key">The key inside the area.</param>
/// <returns>The full key.</returns>
public static string For(string? company, string area, string key) => Prefix(company, area) + key;
/// <summary>The prefix of an area, for <see cref="ICacheProvider.RemoveByPrefixAsync"/>.</summary>
/// <param name="company">The company code, or <see langword="null"/> for the instance.</param>
/// <param name="area">The area.</param>
/// <returns>The prefix, ending with a colon.</returns>
public static string Prefix(string? company, string area)
{
ArgumentException.ThrowIfNullOrWhiteSpace(area);
return "kh:" + (string.IsNullOrEmpty(company) ? Instance : company) + ":" + area + ":";
}
}
@@ -0,0 +1,349 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Instance;
/// <summary>Where an installed licence comes from.</summary>
public enum LicenseSource
{
/// <summary>A signed <c>.khl</c> instance licence.</summary>
File = 0,
/// <summary>A signed activation code for one module.</summary>
ActivationCode = 1,
/// <summary>A fictitious code of SPEC §8.3, accepted only in test mode.</summary>
TestCode = 2,
}
/// <summary>An installed licence or activation code (<c>sys_licenses</c>).</summary>
public sealed class LicenseRecord : Entity<long>
{
/// <summary>Where the licence comes from.</summary>
public LicenseSource Source { get; set; }
/// <summary>The licence text (<c>.khl</c> content or code), as installed.</summary>
public string Payload { get; set; } = string.Empty;
/// <summary>The licence holder.</summary>
public string? Licensee { get; set; }
/// <summary>The module codes, comma separated.</summary>
public string Modules { get; set; } = string.Empty;
/// <summary>Concurrent users granted (0 = not stated by this licence).</summary>
public int MaxConcurrentUsers { get; set; }
/// <summary>Companies granted (0 = not stated by this licence).</summary>
public int MaxCompanies { get; set; }
/// <summary>When the licence was issued.</summary>
public DateTime? IssuedAt { get; set; }
/// <summary>When the licence expires; <see langword="null"/> for no expiry.</summary>
public DateTime? ExpiresAt { get; set; }
/// <summary>Days of full use after the expiry.</summary>
public int GracePeriodDays { get; set; }
/// <summary>Whether the licence counts (a removed licence stays for the history).</summary>
public bool IsActive { get; set; } = true;
}
/// <summary>One step in the history of licences (<c>sys_license_activations</c>).</summary>
public sealed class LicenseActivation : Entity<long>
{
/// <summary>What happened: <c>activated</c>, <c>deactivated</c>, <c>rejected</c>, <c>verified</c>, <c>expired</c>.</summary>
public string Action { get; set; } = string.Empty;
/// <summary>The licence source.</summary>
public LicenseSource Source { get; set; }
/// <summary>The modules concerned, comma separated.</summary>
public string? Modules { get; set; }
/// <summary>The outcome code, for example <c>ok</c>, <c>license_test_only</c>, <c>signature_invalid</c>.</summary>
public string Outcome { get; set; } = string.Empty;
/// <summary>A short explanation.</summary>
public string? Message { get; set; }
}
/// <summary>An ASP.NET Core DataProtection key kept in the system database (<c>sys_data_protection_keys</c>).</summary>
public sealed class DataProtectionKey : Entity<long>
{
/// <summary>The key name given by DataProtection.</summary>
public string FriendlyName { get; set; } = string.Empty;
/// <summary>The key XML. The key material inside is encrypted with the instance key.</summary>
public string Xml { get; set; } = string.Empty;
}
/// <summary>One event of the application log (<c>sys_log</c>, SPEC §9.5).</summary>
public sealed class LogEntry : IEntity<long>
{
/// <inheritdoc />
public long Id { get; set; }
/// <summary>When the event happened (UTC).</summary>
public DateTime At { get; set; }
/// <summary>The level: Trace, Debug, Information, Warning, Error, Critical.</summary>
public string Level { get; set; } = string.Empty;
/// <summary>The section (SPEC §9.5), for example <c>Authentication</c>.</summary>
public string Section { get; set; } = string.Empty;
/// <summary>The logger category.</summary>
public string Source { get; set; } = string.Empty;
/// <summary>The message.</summary>
public string Message { get; set; } = string.Empty;
/// <summary>The exception with its stack, if any.</summary>
public string? Exception { get; set; }
/// <summary>The user name.</summary>
public string? UserName { get; set; }
/// <summary>The company code.</summary>
public string? CompanyCode { get; set; }
/// <summary>The trace identifier shown to the user as the error code.</summary>
public string? TraceId { get; set; }
/// <summary>The request (method and path).</summary>
public string? Request { get; set; }
/// <summary>The entity concerned.</summary>
public string? Entity { get; set; }
/// <summary>The identifier of the entity concerned.</summary>
public string? EntityId { get; set; }
/// <summary>Further structured data as JSON.</summary>
public string? Data { get; set; }
}
/// <summary>
/// A security or instance action (<c>sys_security_audit</c>): 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.
/// </summary>
public sealed class SecurityAuditEntry : IEntity<long>
{
/// <inheritdoc />
public long Id { get; set; }
/// <summary>When it happened (UTC).</summary>
public DateTime At { get; set; }
/// <summary>The action code, for example <c>login.succeeded</c>.</summary>
public string Action { get; set; } = string.Empty;
/// <summary>Who acted.</summary>
public string? UserName { get; set; }
/// <summary>The company concerned.</summary>
public string? CompanyCode { get; set; }
/// <summary>The client address.</summary>
public string? IpAddress { get; set; }
/// <summary>What the action was about (a user, a module, a database...).</summary>
public string? Target { get; set; }
/// <summary>Details as JSON (never secrets).</summary>
public string? Details { get; set; }
/// <summary>The hash of the previous row (empty for the first).</summary>
public string PreviousHash { get; set; } = string.Empty;
/// <summary>SHA-256 of this row's content and <see cref="PreviousHash"/>.</summary>
public string Hash { get; set; } = string.Empty;
}
/// <summary>A change to company data (<c>audit_log</c>, SPEC §7.3), shown in the "Storico" of a record.</summary>
public sealed class AuditEntry : IEntity<long>
{
/// <inheritdoc />
public long Id { get; set; }
/// <summary>When it happened (UTC).</summary>
public DateTime At { get; set; }
/// <summary>The entity (table) changed.</summary>
public string Entity { get; set; } = string.Empty;
/// <summary>The identifier of the record.</summary>
public string EntityId { get; set; } = string.Empty;
/// <summary><c>insert</c>, <c>update</c> or <c>delete</c>.</summary>
public string Action { get; set; } = string.Empty;
/// <summary>Who changed it.</summary>
public string? UserName { get; set; }
/// <summary>The changed fields as JSON: <c>{"field": {"old": ..., "new": ...}}</c>.</summary>
public string? Diff { get; set; }
/// <summary>The trace of the request that made the change.</summary>
public string? TraceId { get; set; }
}
/// <summary>The outcome of a job run.</summary>
public enum JobOutcome
{
/// <summary>Still running.</summary>
Running = 0,
/// <summary>Completed.</summary>
Succeeded = 1,
/// <summary>Failed after the retries.</summary>
Failed = 2,
/// <summary>Stopped by the timeout.</summary>
TimedOut = 3,
/// <summary>Not started because another run held the lock.</summary>
Skipped = 4,
}
/// <summary>A scheduled task (<c>sys_scheduled_tasks</c>): a system job or an activity set up by administrators.</summary>
public sealed class ScheduledTask : Entity<long>
{
/// <summary>The task code, unique, for example <c>system.log-retention</c>.</summary>
public string Code { get; set; } = string.Empty;
/// <summary>The name shown in the interface.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>The job type that runs it.</summary>
public string JobType { get; set; } = string.Empty;
/// <summary>The company it works on; <see langword="null"/> for the instance.</summary>
public string? CompanyCode { get; set; }
/// <summary>The cron expression (five fields).</summary>
public string Cron { get; set; } = string.Empty;
/// <summary>The time zone of the cron expression (IANA name).</summary>
public string TimeZone { get; set; } = "Europe/Rome";
/// <summary>The longest a run may last, in seconds.</summary>
public int TimeoutSeconds { get; set; } = 600;
/// <summary>How many times a failed run is retried.</summary>
public int MaxRetries { get; set; }
/// <summary>Whether the task runs.</summary>
public bool IsEnabled { get; set; } = true;
/// <summary>A system job, which administrators can suspend but not delete.</summary>
public bool IsSystem { get; set; }
/// <summary>The parameters as JSON.</summary>
public string? Parameters { get; set; }
/// <summary>The last start.</summary>
public DateTime? LastRunAt { get; set; }
/// <summary>The next planned start.</summary>
public DateTime? NextRunAt { get; set; }
/// <summary>The outcome of the last run.</summary>
public JobOutcome? LastOutcome { get; set; }
}
/// <summary>One run of a scheduled task (<c>sys_job_runs</c>).</summary>
public sealed class JobRun : IEntity<long>
{
/// <inheritdoc />
public long Id { get; set; }
/// <summary>The task code.</summary>
public string TaskCode { get; set; } = string.Empty;
/// <summary>When the run started (UTC).</summary>
public DateTime StartedAt { get; set; }
/// <summary>When the run ended.</summary>
public DateTime? FinishedAt { get; set; }
/// <summary>The outcome.</summary>
public JobOutcome Outcome { get; set; }
/// <summary>The attempt number, from 1.</summary>
public int Attempt { get; set; } = 1;
/// <summary>A short result or error message.</summary>
public string? Message { get; set; }
/// <summary>The trace identifier of the run, to find its log.</summary>
public string? TraceId { get; set; }
}
/// <summary>
/// A lock held by a job run (<c>sys_job_locks</c>): a row per running task, with an expiry so that a process that died
/// does not block the task for ever.
/// </summary>
public sealed class JobLock : IEntity<string>
{
/// <summary>The lock key (the task code).</summary>
public string Id { get; set; } = string.Empty;
/// <summary>The process that holds the lock.</summary>
public string Owner { get; set; } = string.Empty;
/// <summary>When the lock was taken.</summary>
public DateTime AcquiredAt { get; set; }
/// <summary>When the lock lapses.</summary>
public DateTime ExpiresAt { get; set; }
}
/// <summary>The weight of a notification.</summary>
public enum NotificationSeverity
{
/// <summary>Information.</summary>
Info = 0,
/// <summary>Something completed.</summary>
Success = 1,
/// <summary>Needs attention.</summary>
Warning = 2,
/// <summary>Something failed.</summary>
Error = 3,
}
/// <summary>An in-app notification (SPEC §9; mockup 010).</summary>
public abstract class NotificationRecord : Entity<long>
{
/// <summary>The recipient; <see langword="null"/> for every user of the scope (all administrators, all users).</summary>
public long? RecipientUserId { get; set; }
/// <summary>The area: <c>security</c>, <c>jobs</c>, <c>system</c>, <c>licenses</c>...</summary>
public string Category { get; set; } = string.Empty;
/// <summary>The weight.</summary>
public NotificationSeverity Severity { get; set; }
/// <summary>The title.</summary>
public string Title { get; set; } = string.Empty;
/// <summary>The text.</summary>
public string? Body { get; set; }
/// <summary>A link inside the application.</summary>
public string? Link { get; set; }
/// <summary>When the recipient read it.</summary>
public DateTime? ReadAt { get; set; }
}
/// <summary>A notification for instance accounts (<c>sys_notifications</c>).</summary>
public sealed class SystemNotification : NotificationRecord;
/// <summary>A notification for company users (<c>notifications</c>).</summary>
public sealed class Notification : NotificationRecord;
+131
View File
@@ -0,0 +1,131 @@
namespace Khaemhat.Core.Logging;
/// <summary>The sections of the application log (SPEC §9.5; mockup 084). Each module writes to its own.</summary>
public enum LogSection
{
/// <summary>Sistema.</summary>
System = 0,
/// <summary>Autenticazione.</summary>
Authentication = 1,
/// <summary>Database.</summary>
Database = 2,
/// <summary>Migrazioni.</summary>
Migrations = 3,
/// <summary>Documenti.</summary>
Documents = 4,
/// <summary>Contabilità.</summary>
Accounting = 5,
/// <summary>Magazzino.</summary>
Inventory = 6,
/// <summary>SDI/e-invoicing.</summary>
EInvoicing = 7,
/// <summary>CRM.</summary>
Crm = 8,
/// <summary>Automazioni.</summary>
Automation = 9,
/// <summary>Attività programmate.</summary>
ScheduledJobs = 10,
/// <summary>Backup.</summary>
Backup = 11,
/// <summary>API/MCP.</summary>
Api = 12,
/// <summary>E-mail/PEC.</summary>
Email = 13,
/// <summary>Integrazioni (VIES, BCE, intermediari).</summary>
Integrations = 14,
/// <summary>UI/circuiti.</summary>
Ui = 15,
/// <summary>Prestazioni.</summary>
Performance = 16,
}
/// <summary>Names, labels and the scope key of <see cref="LogSection"/>.</summary>
public static class LogSections
{
/// <summary>The scope key that carries the section (<c>using (logger.BeginScope(LogSections.Scope(...)))</c>).</summary>
public const string ScopeKey = "Section";
/// <summary>The scope key of the trace identifier.</summary>
public const string TraceIdKey = "TraceId";
/// <summary>The scope key of the user name.</summary>
public const string UserKey = "UserName";
/// <summary>The scope key of the company code.</summary>
public const string CompanyKey = "CompanyCode";
/// <summary>The scope key of the request (method and path).</summary>
public const string RequestKey = "Request";
/// <summary>The scope key of the entity concerned.</summary>
public const string EntityKey = "Entity";
/// <summary>The scope key of the entity identifier.</summary>
public const string EntityIdKey = "EntityId";
/// <summary>The Italian label shown in the log page.</summary>
/// <param name="section">The section.</param>
/// <returns>The label.</returns>
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(),
};
/// <summary>A scope state that sets the section of the events logged inside it.</summary>
/// <param name="section">The section.</param>
/// <returns>The scope state.</returns>
public static IReadOnlyList<KeyValuePair<string, object?>> Scope(LogSection section) =>
[new(ScopeKey, section.ToString())];
/// <summary>
/// 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.
/// </summary>
/// <param name="category">The logger category.</param>
/// <returns>The section.</returns>
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,
};
}
@@ -0,0 +1,203 @@
using System.Globalization;
namespace Khaemhat.Core.Scheduling;
/// <summary>
/// A five-field cron expression (<c>minute hour day-of-month month day-of-week</c>) for scheduled tasks (SPEC §9.4):
/// <c>*</c>, lists (<c>1,15</c>), ranges (<c>1-5</c>), steps (<c>*/10</c>, <c>8-18/2</c>); 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).
/// </summary>
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]);
}
}
/// <summary>The expression as written.</summary>
public string Text { get; }
/// <summary>Parses an expression.</summary>
/// <param name="text">The expression.</param>
/// <returns>The parsed expression.</returns>
/// <exception cref="FormatException">The expression is not valid.</exception>
public static CronExpression Parse(string text) =>
TryParse(text, out var result, out var error) ? result : throw new FormatException(error);
/// <summary>Tries to parse an expression.</summary>
/// <param name="text">The expression.</param>
/// <param name="result">The parsed expression.</param>
/// <param name="error">Why it is not valid.</param>
/// <returns><see langword="true"/> when valid.</returns>
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;
}
}
/// <summary>The first occurrence strictly after a moment.</summary>
/// <param name="afterUtc">The moment (UTC).</param>
/// <param name="zone">The time zone of the schedule.</param>
/// <returns>The next occurrence in UTC, or <see langword="null"/> when none exists in the next five years.</returns>
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;
}
/// <inheritdoc />
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}.");
}
+237
View File
@@ -0,0 +1,237 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Security;
/// <summary>
/// The three access levels of SPEC §7.1, ordered: a higher value can do everything a lower one can.
/// <see cref="SystemUser"/> rows hold <see cref="Administrator"/> or <see cref="SuperUser"/>; company users are
/// <see cref="Standard"/>.
/// </summary>
public enum UserLevel
{
/// <summary>A company user, limited by the permissions of the roles.</summary>
Standard = 0,
/// <summary>An instance administrator, created by the super user.</summary>
Administrator = 1,
/// <summary>The only super user, created from the container variables at first start.</summary>
SuperUser = 2,
}
/// <summary>The kind of a company user.</summary>
public enum UserKind
{
/// <summary>A person who signs in with a password.</summary>
Human = 0,
/// <summary>A technical user for the API: no password, used only through API keys.</summary>
Technical = 1,
}
/// <summary>
/// The credential fields shared by instance accounts (<c>sys_users</c>) and company users (<c>users</c>), so that
/// password, lockout, TOTP and recovery rules are written once.
/// </summary>
public interface IAccount
{
/// <summary>The identifier.</summary>
long Id { get; }
/// <summary>The sign-in name, unique in its database (compared case-insensitively, stored lower-case).</summary>
string UserName { get; set; }
/// <summary>The name shown in the interface.</summary>
string DisplayName { get; set; }
/// <summary>The e-mail address for recovery and notifications.</summary>
string? Email { get; set; }
/// <summary>The password hash (<c>pbkdf2-sha256$...</c>); <see langword="null"/> for technical users.</summary>
string? PasswordHash { get; set; }
/// <summary>The previous password hashes, newest first, as a JSON array (policy: no reuse of the last five).</summary>
string? PasswordHistory { get; set; }
/// <summary>When the password was last set.</summary>
DateTime? PasswordChangedAt { get; set; }
/// <summary>Whether the next sign-in must change the password (first access, temporary password, expiry).</summary>
bool MustChangePassword { get; set; }
/// <summary>When a temporary password stops working; <see langword="null"/> for a normal password.</summary>
DateTime? TemporaryPasswordExpiresAt { get; set; }
/// <summary>Consecutive failed sign-ins since the last success.</summary>
int FailedLoginCount { get; set; }
/// <summary>The account is locked until this moment after too many failures.</summary>
DateTime? LockedUntil { get; set; }
/// <summary>The TOTP secret, encrypted with the instance key.</summary>
string? TotpSecret { get; set; }
/// <summary>Whether the two-step verification is active.</summary>
bool TotpEnabled { get; set; }
/// <summary>The last accepted TOTP time step: a code is never accepted twice.</summary>
long? TotpLastStep { get; set; }
/// <summary>The SHA-256 hashes of the unused recovery codes, as a JSON array.</summary>
string? TotpRecoveryCodes { get; set; }
/// <summary>The SHA-256 hash of the pending password-recovery token.</summary>
string? RecoveryTokenHash { get; set; }
/// <summary>When the recovery token expires.</summary>
DateTime? RecoveryTokenExpiresAt { get; set; }
/// <summary>Whether the account can sign in.</summary>
bool IsActive { get; set; }
/// <summary>The last successful sign-in.</summary>
DateTime? LastLoginAt { get; set; }
}
/// <summary>An instance account (<c>sys_users</c>): the super user or an administrator (SPEC §7.1).</summary>
public sealed class SystemUser : Entity<long>, IAccount
{
/// <inheritdoc />
public string UserName { get; set; } = string.Empty;
/// <inheritdoc />
public string DisplayName { get; set; } = string.Empty;
/// <inheritdoc />
public string? Email { get; set; }
/// <summary><see cref="UserLevel.SuperUser"/> or <see cref="UserLevel.Administrator"/>.</summary>
public UserLevel Level { get; set; }
/// <inheritdoc />
public string? PasswordHash { get; set; }
/// <inheritdoc />
public string? PasswordHistory { get; set; }
/// <inheritdoc />
public DateTime? PasswordChangedAt { get; set; }
/// <inheritdoc />
public bool MustChangePassword { get; set; }
/// <inheritdoc />
public DateTime? TemporaryPasswordExpiresAt { get; set; }
/// <inheritdoc />
public int FailedLoginCount { get; set; }
/// <inheritdoc />
public DateTime? LockedUntil { get; set; }
/// <inheritdoc />
public string? TotpSecret { get; set; }
/// <inheritdoc />
public bool TotpEnabled { get; set; }
/// <inheritdoc />
public long? TotpLastStep { get; set; }
/// <inheritdoc />
public string? TotpRecoveryCodes { get; set; }
/// <inheritdoc />
public string? RecoveryTokenHash { get; set; }
/// <inheritdoc />
public DateTime? RecoveryTokenExpiresAt { get; set; }
/// <inheritdoc />
public bool IsActive { get; set; } = true;
/// <inheritdoc />
public DateTime? LastLoginAt { get; set; }
/// <summary>The company of the linked user, for an administrator who works as a company user without a second sign-in.</summary>
public string? LinkedCompanyCode { get; set; }
/// <summary>The linked company user.</summary>
public long? LinkedUserId { get; set; }
}
/// <summary>A company user (<c>users</c> in the company database).</summary>
public sealed class CompanyUser : Entity<long>, IAccount
{
/// <inheritdoc />
public string UserName { get; set; } = string.Empty;
/// <inheritdoc />
public string DisplayName { get; set; } = string.Empty;
/// <inheritdoc />
public string? Email { get; set; }
/// <summary>A person or a technical user for the API.</summary>
public UserKind Kind { get; set; }
/// <inheritdoc />
public string? PasswordHash { get; set; }
/// <inheritdoc />
public string? PasswordHistory { get; set; }
/// <inheritdoc />
public DateTime? PasswordChangedAt { get; set; }
/// <inheritdoc />
public bool MustChangePassword { get; set; }
/// <inheritdoc />
public DateTime? TemporaryPasswordExpiresAt { get; set; }
/// <inheritdoc />
public int FailedLoginCount { get; set; }
/// <inheritdoc />
public DateTime? LockedUntil { get; set; }
/// <inheritdoc />
public string? TotpSecret { get; set; }
/// <inheritdoc />
public bool TotpEnabled { get; set; }
/// <summary>Whether this user must set up the two-step verification (configurable per user).</summary>
public bool TotpRequired { get; set; }
/// <inheritdoc />
public long? TotpLastStep { get; set; }
/// <inheritdoc />
public string? TotpRecoveryCodes { get; set; }
/// <inheritdoc />
public string? RecoveryTokenHash { get; set; }
/// <inheritdoc />
public DateTime? RecoveryTokenExpiresAt { get; set; }
/// <inheritdoc />
public bool IsActive { get; set; } = true;
/// <inheritdoc />
public DateTime? LastLoginAt { get; set; }
/// <summary>Sees only the customers assigned to the user (agents).</summary>
public bool OwnCustomersOnly { get; set; }
/// <summary>Sees costs and margins.</summary>
public bool CanSeeCosts { get; set; }
/// <summary>Can export lists and reports.</summary>
public bool CanExport { get; set; }
/// <summary>Can use the API.</summary>
public bool CanUseApi { get; set; }
}
+136
View File
@@ -0,0 +1,136 @@
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.Security;
/// <summary>How far a sign-in has gone. Only <see cref="Active"/> sessions open the application.</summary>
public enum SessionState
{
/// <summary>The password was right; the TOTP code is still missing.</summary>
PendingTotp = 0,
/// <summary>The two-step verification must be set up before going on (mandatory for instance accounts).</summary>
PendingTotpSetup = 1,
/// <summary>The password must be changed before going on.</summary>
PendingPasswordChange = 2,
/// <summary>A complete session.</summary>
Active = 3,
}
/// <summary>
/// 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.
/// </summary>
public abstract class SessionRecord : Entity<long>
{
/// <summary>The SHA-256 hash of the token, in lower-case hexadecimal.</summary>
public string TokenHash { get; set; } = string.Empty;
/// <summary>The account.</summary>
public long UserId { get; set; }
/// <summary>The state of the sign-in.</summary>
public SessionState State { get; set; }
/// <summary>The company the session works in (chosen at sign-in, changeable by instance accounts).</summary>
public string? CompanyCode { get; set; }
/// <summary>The client address.</summary>
public string? IpAddress { get; set; }
/// <summary>The browser, as sent by the client (truncated).</summary>
public string? UserAgent { get; set; }
/// <summary>Whether the cookie survives the browser ("remember me on this device").</summary>
public bool Persistent { get; set; }
/// <summary>The last request seen (updated at most once a minute).</summary>
public DateTime LastSeenAt { get; set; }
/// <summary>When the session expires unless used again (sliding expiry).</summary>
public DateTime ExpiresAt { get; set; }
/// <summary>When the session was revoked.</summary>
public DateTime? RevokedAt { get; set; }
/// <summary>Why the session was revoked (sign-out, administrator, password change, maintenance...).</summary>
public string? RevokedReason { get; set; }
}
/// <summary>A session of an instance account (<c>sys_sessions</c>).</summary>
public sealed class SystemSession : SessionRecord;
/// <summary>A session of a company user (<c>user_sessions</c>).</summary>
public sealed class UserSession : SessionRecord;
/// <summary>A predefined role kept in the system database and copied into each company (<c>sys_roles_templates</c>).</summary>
public sealed class RoleTemplate : Entity<long>
{
/// <summary>The role code, for example <c>ACCOUNTING</c>.</summary>
public string Code { get; set; } = string.Empty;
/// <summary>The name shown in the interface.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>What the role is for.</summary>
public string? Description { get; set; }
/// <summary>The permission codes as a JSON array; <c>*</c> grants every permission.</summary>
public string Permissions { get; set; } = "[]";
/// <summary>The order in lists.</summary>
public int SortOrder { get; set; }
}
/// <summary>A role of a company (<c>roles</c>).</summary>
public sealed class Role : Entity<long>
{
/// <summary>The role code, unique in the company.</summary>
public string Code { get; set; } = string.Empty;
/// <summary>The name shown in the interface.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>What the role is for.</summary>
public string? Description { get; set; }
/// <summary>A predefined role copied from a template: it can be cloned but not changed.</summary>
public bool IsPredefined { get; set; }
/// <summary>The template the role comes from, or the role it was cloned from.</summary>
public string? TemplateCode { get; set; }
}
/// <summary>A permission granted by a role (<c>role_permissions</c>).</summary>
public sealed class RoleGrant : Entity<long>
{
/// <summary>The role.</summary>
public long RoleId { get; set; }
/// <summary>The permission code, or <c>*</c>.</summary>
public string Permission { get; set; } = string.Empty;
}
/// <summary>A role assigned to a company user (<c>user_roles</c>).</summary>
public sealed class UserRole : Entity<long>
{
/// <summary>The user.</summary>
public long UserId { get; set; }
/// <summary>The role.</summary>
public long RoleId { get; set; }
}
/// <summary>A permission granted or denied to one user over the roles (<c>user_permission_overrides</c>). Denials win.</summary>
public sealed class UserPermissionOverride : Entity<long>
{
/// <summary>The user.</summary>
public long UserId { get; set; }
/// <summary>The permission code.</summary>
public string Permission { get; set; } = string.Empty;
/// <summary><see langword="true"/> grants, <see langword="false"/> denies.</summary>
public bool Allowed { get; set; }
}
@@ -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;
/// <c>foreign_keys=ON</c> and <c>busy_timeout=5000</c>; file databases use <c>journal_mode=WAL</c>. Databases are files
/// under <c>KHAEMHAT_DATA_DIR</c>, or in-memory databases shared by the connections of the process (tests).
/// </summary>
/// <remarks>
/// An in-memory database disappears with its last connection: <see cref="EnsureDatabaseExistsAsync"/> opens one that
/// stays open for the life of the process (or until <see cref="DropDatabaseAsync"/>), so the database lives as long as
/// the instance that created it.
/// </remarks>
public sealed class SqliteProvider : IDbProvider
{
private const int BusyTimeoutMilliseconds = 5000;
private static readonly ConcurrentDictionary<string, SqliteConnection> MemoryKeepers = new(StringComparer.Ordinal);
/// <inheritdoc />
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;
}
@@ -0,0 +1,97 @@
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.SystemDatabase;
namespace Khaemhat.Data.CompanyDatabase;
/// <summary>Map of <see cref="CompanyUser"/> to <c>users</c>.</summary>
public sealed class CompanyUserMap : EntityMap<CompanyUser>
{
/// <summary>Creates the map.</summary>
public CompanyUserMap()
{
ToTable("users");
AccountColumns.Configure(this);
}
}
/// <summary>Map of <see cref="UserSession"/> to <c>user_sessions</c>.</summary>
public sealed class UserSessionMap : EntityMap<UserSession>
{
/// <summary>Creates the map.</summary>
public UserSessionMap()
{
ToTable("user_sessions");
SessionColumns.Configure(this);
}
}
/// <summary>Map of <see cref="Role"/> to <c>roles</c>.</summary>
public sealed class RoleMap : EntityMap<Role>
{
/// <summary>Creates the map.</summary>
public RoleMap()
{
ToTable("roles");
Map(x => x.Code).MaxLength(50);
Map(x => x.Name).MaxLength(100);
Map(x => x.TemplateCode).MaxLength(50);
}
}
/// <summary>Map of <see cref="RoleGrant"/> to <c>role_permissions</c>.</summary>
public sealed class RoleGrantMap : EntityMap<RoleGrant>
{
/// <summary>Creates the map.</summary>
public RoleGrantMap()
{
ToTable("role_permissions");
Map(x => x.Permission).MaxLength(100);
}
}
/// <summary>Map of <see cref="UserRole"/> to <c>user_roles</c>.</summary>
public sealed class UserRoleMap : EntityMap<UserRole>
{
/// <summary>Creates the map.</summary>
public UserRoleMap() => ToTable("user_roles");
}
/// <summary>Map of <see cref="UserPermissionOverride"/> to <c>user_permission_overrides</c>.</summary>
public sealed class UserPermissionOverrideMap : EntityMap<UserPermissionOverride>
{
/// <summary>Creates the map.</summary>
public UserPermissionOverrideMap()
{
ToTable("user_permission_overrides");
Map(x => x.Permission).MaxLength(100);
}
}
/// <summary>Map of <see cref="AuditEntry"/> to <c>audit_log</c>.</summary>
public sealed class AuditEntryMap : EntityMap<AuditEntry>
{
/// <summary>Creates the map.</summary>
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);
}
}
/// <summary>Map of <see cref="Notification"/> to <c>notifications</c>.</summary>
public sealed class NotificationMap : EntityMap<Notification>
{
/// <summary>Creates the map.</summary>
public NotificationMap()
{
ToTable("notifications");
NotificationColumns.Configure(this);
}
}
@@ -0,0 +1,45 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>The company users (SPEC §7.1).</summary>
[Migration(20261111_001, "create_users")]
public sealed class M20261111_001_CreateUsers : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,34 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>The sessions of the company users (SPEC §7.3).</summary>
[Migration(20261111_002, "create_user_sessions")]
public sealed class M20261111_002_CreateUserSessions : IMigration
{
/// <inheritdoc />
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);
});
}
}
@@ -0,0 +1,58 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>Roles, their permissions, the roles of each user and the per-user overrides (SPEC §7.2).</summary>
[Migration(20261111_003, "create_roles")]
public sealed class M20261111_003_CreateRoles : IMigration
{
/// <inheritdoc />
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);
});
}
}
@@ -0,0 +1,28 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>The history of changes to company data (SPEC §7.3).</summary>
[Migration(20261111_004, "create_audit_log")]
public sealed class M20261111_004_CreateAuditLog : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,28 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>The notifications of the company users (SPEC §9).</summary>
[Migration(20261111_005, "create_notifications")]
public sealed class M20261111_005_CreateNotifications : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -33,6 +33,15 @@ public sealed class DataAccessContext
/// <summary>The current user name, or <see langword="null"/>.</summary>
public string? CurrentUser => _currentUser();
/// <summary>Statements slower than this are reported to <see cref="SlowQueryObserver"/> (SPEC §9.5: 500 ms).</summary>
public TimeSpan SlowQueryThreshold { get; init; } = TimeSpan.FromMilliseconds(500);
/// <summary>
/// Receives the statements slower than <see cref="SlowQueryThreshold"/>: the host writes them to the log section
/// <i>Prestazioni</i>. The SQL text carries no values: they are always parameters.
/// </summary>
public Action<SlowQuery>? SlowQueryObserver { get; init; }
/// <summary>The current UTC time, truncated to microseconds (the precision of PostgreSQL and of SQLite storage).</summary>
public DateTime UtcNow => Truncate(Clock.GetUtcNow().UtcDateTime);
@@ -41,3 +50,9 @@ public sealed class DataAccessContext
/// <returns>The truncated timestamp.</returns>
public static DateTime Truncate(DateTime value) => new(value.Ticks - (value.Ticks % 10), value.Kind);
}
/// <summary>A statement that took longer than <see cref="DataAccessContext.SlowQueryThreshold"/>.</summary>
/// <param name="Database">The database name.</param>
/// <param name="Sql">The SQL text (parameters, never values).</param>
/// <param name="Duration">How long it took.</param>
public sealed record SlowQuery(string Database, string Sql, TimeSpan Duration);
+42 -3
View File
@@ -218,6 +218,20 @@ public sealed class UnitOfWork : IUnitOfWork
string text, IEnumerable<SqlParameterValue> parameters, Func<DbCommand, CancellationToken, Task<T>> 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<T> WriteCoreAsync<T>(
string text, IEnumerable<SqlParameterValue> parameters, Func<DbCommand, CancellationToken, Task<T>> 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()
+1 -1
View File
@@ -156,7 +156,7 @@ public abstract class EntityMap<T> : IEntityMap
/// <typeparam name="TProperty">The property type.</typeparam>
/// <param name="property">The property, for example <c>x =&gt; x.Code</c>.</param>
/// <returns>The column map to configure.</returns>
protected ColumnMap Map<TProperty>(Expression<Func<T, TProperty>> property)
protected internal ColumnMap Map<TProperty>(Expression<Func<T, TProperty>> property)
{
if (_columns is not null)
{
@@ -0,0 +1,42 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>The instance accounts (SPEC §7.1): the super user and the administrators.</summary>
[Migration(20261111_003, "create_sys_users", Target = MigrationTarget.System)]
public sealed class M20261111_003_CreateSysUsers : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,34 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>The sessions of the instance accounts (SPEC §7.3).</summary>
[Migration(20261111_004, "create_sys_sessions", Target = MigrationTarget.System)]
public sealed class M20261111_004_CreateSysSessions : IMigration
{
/// <inheritdoc />
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);
});
}
}
@@ -0,0 +1,26 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>The predefined roles copied into each company (SPEC §7.2).</summary>
[Migration(20261111_005, "create_sys_roles_templates", Target = MigrationTarget.System)]
public sealed class M20261111_005_CreateSysRolesTemplates : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,41 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>The installed licences and their history (SPEC §8.2).</summary>
[Migration(20261111_006, "create_sys_licenses", Target = MigrationTarget.System)]
public sealed class M20261111_006_CreateSysLicenses : IMigration
{
/// <inheritdoc />
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();
});
}
}
@@ -0,0 +1,23 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>The DataProtection keys of the cookies and antiforgery tokens (SPEC §5.4).</summary>
[Migration(20261111_007, "create_sys_data_protection_keys", Target = MigrationTarget.System)]
public sealed class M20261111_007_CreateSysDataProtectionKeys : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,35 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>The application log by section (SPEC §9.5).</summary>
[Migration(20261111_008, "create_sys_log", Target = MigrationTarget.System)]
public sealed class M20261111_008_CreateSysLog : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,29 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>The immutable, hash-chained audit of security and instance actions (SPEC §7.3).</summary>
[Migration(20261111_009, "create_sys_security_audit", Target = MigrationTarget.System)]
public sealed class M20261111_009_CreateSysSecurityAudit : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,57 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>Scheduled tasks, their runs and the locks that keep a task from running twice (SPEC §9).</summary>
[Migration(20261111_010, "create_sys_scheduler", Target = MigrationTarget.System)]
public sealed class M20261111_010_CreateSysScheduler : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,28 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.SystemDatabase.Migrations;
/// <summary>The notifications of the instance accounts (SPEC §9).</summary>
[Migration(20261111_011, "create_sys_notifications", Target = MigrationTarget.System)]
public sealed class M20261111_011_CreateSysNotifications : IMigration
{
/// <inheritdoc />
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");
});
}
}
@@ -0,0 +1,210 @@
using Khaemhat.Core.Instance;
using Khaemhat.Core.Security;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.SystemDatabase;
/// <summary>The account columns shared by <c>sys_users</c> and <c>users</c>.</summary>
internal static class AccountColumns
{
public static void Configure<T>(EntityMap<T> 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);
}
}
/// <summary>Map of <see cref="SystemUser"/> to <c>sys_users</c>.</summary>
public sealed class SystemUserMap : EntityMap<SystemUser>
{
/// <summary>Creates the map.</summary>
public SystemUserMap()
{
ToTable("sys_users");
AccountColumns.Configure(this);
Map(x => x.LinkedCompanyCode).MaxLength(20);
}
}
/// <summary>Map of <see cref="SystemSession"/> to <c>sys_sessions</c>.</summary>
public sealed class SystemSessionMap : EntityMap<SystemSession>
{
/// <summary>Creates the map.</summary>
public SystemSessionMap()
{
ToTable("sys_sessions");
SessionColumns.Configure(this);
}
}
/// <summary>The session columns shared by <c>sys_sessions</c> and <c>user_sessions</c>.</summary>
internal static class SessionColumns
{
public static void Configure<T>(EntityMap<T> 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);
}
}
/// <summary>Map of <see cref="RoleTemplate"/> to <c>sys_roles_templates</c>.</summary>
public sealed class RoleTemplateMap : EntityMap<RoleTemplate>
{
/// <summary>Creates the map.</summary>
public RoleTemplateMap()
{
ToTable("sys_roles_templates");
Map(x => x.Code).MaxLength(50);
Map(x => x.Name).MaxLength(100);
Map(x => x.Permissions).Json();
}
}
/// <summary>Map of <see cref="LicenseRecord"/> to <c>sys_licenses</c>.</summary>
public sealed class LicenseRecordMap : EntityMap<LicenseRecord>
{
/// <summary>Creates the map.</summary>
public LicenseRecordMap()
{
ToTable("sys_licenses");
Map(x => x.Licensee).MaxLength(200);
Map(x => x.Modules).MaxLength(400);
}
}
/// <summary>Map of <see cref="LicenseActivation"/> to <c>sys_license_activations</c>.</summary>
public sealed class LicenseActivationMap : EntityMap<LicenseActivation>
{
/// <summary>Creates the map.</summary>
public LicenseActivationMap()
{
ToTable("sys_license_activations");
Map(x => x.Action).MaxLength(40);
Map(x => x.Modules).MaxLength(400);
Map(x => x.Outcome).MaxLength(60);
}
}
/// <summary>Map of <see cref="DataProtectionKey"/> to <c>sys_data_protection_keys</c>.</summary>
public sealed class DataProtectionKeyMap : EntityMap<DataProtectionKey>
{
/// <summary>Creates the map.</summary>
public DataProtectionKeyMap()
{
ToTable("sys_data_protection_keys");
Map(x => x.FriendlyName).MaxLength(200);
}
}
/// <summary>Map of <see cref="LogEntry"/> to <c>sys_log</c>.</summary>
public sealed class LogEntryMap : EntityMap<LogEntry>
{
/// <summary>Creates the map.</summary>
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();
}
}
/// <summary>Map of <see cref="SecurityAuditEntry"/> to <c>sys_security_audit</c>.</summary>
public sealed class SecurityAuditEntryMap : EntityMap<SecurityAuditEntry>
{
/// <summary>Creates the map.</summary>
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);
}
}
/// <summary>Map of <see cref="ScheduledTask"/> to <c>sys_scheduled_tasks</c>.</summary>
public sealed class ScheduledTaskMap : EntityMap<ScheduledTask>
{
/// <summary>Creates the map.</summary>
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();
}
}
/// <summary>Map of <see cref="JobRun"/> to <c>sys_job_runs</c>.</summary>
public sealed class JobRunMap : EntityMap<JobRun>
{
/// <summary>Creates the map.</summary>
public JobRunMap()
{
ToTable("sys_job_runs");
Map(x => x.TaskCode).MaxLength(100);
Map(x => x.TraceId).MaxLength(64);
}
}
/// <summary>Map of <see cref="JobLock"/> to <c>sys_job_locks</c>.</summary>
public sealed class JobLockMap : EntityMap<JobLock>
{
/// <summary>Creates the map.</summary>
public JobLockMap()
{
ToTable("sys_job_locks");
HasKey(x => x.Id, identity: false);
Map(x => x.Id).MaxLength(100);
Map(x => x.Owner).MaxLength(100);
}
}
/// <summary>Map of <see cref="SystemNotification"/> to <c>sys_notifications</c>.</summary>
public sealed class SystemNotificationMap : EntityMap<SystemNotification>
{
/// <summary>Creates the map.</summary>
public SystemNotificationMap()
{
ToTable("sys_notifications");
NotificationColumns.Configure(this);
}
}
/// <summary>The notification columns shared by <c>sys_notifications</c> and <c>notifications</c>.</summary>
internal static class NotificationColumns
{
public static void Configure<T>(EntityMap<T> 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);
}
}
@@ -0,0 +1,128 @@
using System.Collections.Concurrent;
using System.Text.Json;
using Khaemhat.Core.Caching;
namespace Khaemhat.Infrastructure.Caching;
/// <summary>
/// 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.
/// </summary>
/// <param name="clock">The clock.</param>
public sealed class MemoryCacheProvider(TimeProvider clock) : ICacheProvider
{
private const int SweepEvery = 512;
private readonly ConcurrentDictionary<string, Entry> _entries = new(StringComparer.Ordinal);
private int _writes;
/// <summary>Creates a cache on the system clock.</summary>
public MemoryCacheProvider()
: this(TimeProvider.System)
{
}
/// <inheritdoc />
public bool IsDistributed => false;
/// <summary>The number of entries, expired ones included until swept.</summary>
public int Count => _entries.Count;
/// <inheritdoc />
public ValueTask<T?> GetAsync<T>(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<T>(entry.Json));
}
_entries.TryRemove(new KeyValuePair<string, Entry>(key, entry));
}
return ValueTask.FromResult(default(T));
}
/// <summary>Reads the raw JSON of a value (the Redis fallback uses it).</summary>
/// <param name="key">The key.</param>
/// <returns>The JSON, or <see langword="null"/>.</returns>
public byte[]? GetRaw(string key) =>
_entries.TryGetValue(key, out var entry) && entry.ExpiresAt > clock.GetUtcNow() ? entry.Json : null;
/// <inheritdoc />
public ValueTask SetAsync<T>(string key, T value, TimeSpan timeToLive, CancellationToken cancellationToken = default)
{
SetRaw(key, JsonSerializer.SerializeToUtf8Bytes(value), timeToLive);
return ValueTask.CompletedTask;
}
/// <summary>Stores raw JSON.</summary>
/// <param name="key">The key.</param>
/// <param name="json">The JSON.</param>
/// <param name="timeToLive">How long it stays.</param>
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();
}
}
/// <inheritdoc />
public ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(key);
_entries.TryRemove(key, out _);
return ValueTask.CompletedTask;
}
/// <inheritdoc />
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;
}
/// <inheritdoc />
public async ValueTask<T> GetOrCreateAsync<T>(
string key, Func<CancellationToken, ValueTask<T>> factory, TimeSpan timeToLive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(factory);
if (GetRaw(key) is { } json)
{
return JsonSerializer.Deserialize<T>(json)!;
}
var value = await factory(cancellationToken).ConfigureAwait(false);
await SetAsync(key, value, timeToLive, cancellationToken).ConfigureAwait(false);
return value;
}
/// <inheritdoc />
public ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default) =>
RemoveByPrefixAsync(prefix, cancellationToken);
/// <summary>Removes everything (used when Redis comes back, so stale local values are not served).</summary>
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);
}
@@ -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;
/// <summary>
/// Where Redis is (<c>KHAEMHAT_REDIS</c>, SPEC §6): <c>redis://[[user]:password@]host[:6379][/db]</c>, or
/// <c>rediss://</c> for TLS. The password never appears in <see cref="ToString"/>.
/// </summary>
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;
}
/// <summary>The host.</summary>
public string Host { get; }
/// <summary>The port.</summary>
public int Port { get; }
/// <summary>Whether to use TLS.</summary>
public bool UseTls { get; }
/// <summary>The ACL user, if any.</summary>
public string? User { get; }
/// <summary>The password, if any.</summary>
public string? Password { get; }
/// <summary>The database number.</summary>
public int Database { get; }
/// <summary>Parses the URL.</summary>
/// <param name="url">The URL.</param>
/// <returns>The endpoint.</returns>
/// <exception cref="FormatException">The URL is not valid (the message does not repeat it).</exception>
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);
}
/// <inheritdoc />
public override string ToString() => (UseTls ? "rediss://" : "redis://") + (Password is null ? string.Empty : "***@") + Host + ":" + Port.ToString(CultureInfo.InvariantCulture) + "/" + Database.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="endpoint">Where Redis is.</param>
public sealed class RedisClient(RedisEndpoint endpoint) : IAsyncDisposable
{
private readonly SemaphoreSlim _gate = new(1, 1);
private TcpClient? _tcp;
private Stream? _stream;
private BufferedReader? _reader;
/// <summary>The endpoint.</summary>
public RedisEndpoint Endpoint { get; } = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
/// <summary>The time allowed to connect and for each command.</summary>
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(2);
/// <summary>Sends a command and reads its reply.</summary>
/// <param name="arguments">The command and its arguments.</param>
/// <returns>The reply.</returns>
/// <exception cref="RedisException">Redis answered with an error.</exception>
/// <exception cref="IOException">The connection failed.</exception>
public Task<RespValue> ExecuteAsync(params IReadOnlyList<object> arguments) => ExecuteAsync(arguments, CancellationToken.None);
/// <summary>Sends a command and reads its reply.</summary>
/// <param name="arguments">The command and its arguments.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reply.</returns>
public async Task<RespValue> ExecuteAsync(IReadOnlyList<object> 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();
}
}
/// <inheritdoc />
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<RespValue> SendAsync(IReadOnlyList<object> 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;
}
}
/// <summary>
/// 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.
/// </summary>
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<RedisCacheProvider> _logger;
private DateTimeOffset _lastWarning = DateTimeOffset.MinValue;
private volatile bool _healthy = true;
/// <summary>Creates the cache.</summary>
/// <param name="client">The Redis client.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log.</param>
public RedisCacheProvider(RedisClient client, TimeProvider clock, ILogger<RedisCacheProvider> logger)
{
ArgumentNullException.ThrowIfNull(client);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_client = client;
_clock = clock;
_logger = logger;
_fallback = new MemoryCacheProvider(clock);
}
/// <inheritdoc />
public bool IsDistributed => _healthy;
/// <inheritdoc />
public async ValueTask<T?> GetAsync<T>(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<T>(key, cancellationToken).ConfigureAwait(false);
}
return reply.Bytes is { } bytes ? JsonSerializer.Deserialize<T>(bytes) : default;
}
/// <inheritdoc />
public async ValueTask SetAsync<T>(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);
}
}
/// <inheritdoc />
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);
}
/// <inheritdoc />
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");
}
/// <inheritdoc />
public async ValueTask<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, ValueTask<T>> 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<T>(bytes)!;
}
var value = await factory(cancellationToken).ConfigureAwait(false);
await SetAsync(key, value, timeToLive, cancellationToken).ConfigureAwait(false);
return value;
}
/// <inheritdoc />
/// <remarks>Keys live only in Redis, so deleting them is enough; the message lets future local copies follow.</remarks>
public async ValueTask PublishInvalidationAsync(string prefix, CancellationToken cancellationToken = default)
{
await RemoveByPrefixAsync(prefix, cancellationToken).ConfigureAwait(false);
await TryAsync(["PUBLISH", InvalidationChannel, prefix], cancellationToken).ConfigureAwait(false);
}
/// <summary>Checks the connection (<c>PING</c>), for the start log and the system page.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when Redis answered.</returns>
public async Task<bool> PingAsync(CancellationToken cancellationToken = default) =>
(await TryAsync(["PING"], cancellationToken).ConfigureAwait(false))?.Text == "PONG";
/// <inheritdoc />
public ValueTask DisposeAsync() => _client.DisposeAsync();
/// <summary>Escapes the glob characters of a key prefix for <c>SCAN MATCH</c>.</summary>
/// <param name="prefix">The prefix.</param>
/// <returns>The escaped prefix.</returns>
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<RespValue?> TryAsync(IReadOnlyList<object> 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);
}
+222
View File
@@ -0,0 +1,222 @@
using System.Buffers;
using System.Globalization;
using System.Text;
namespace Khaemhat.Infrastructure.Caching;
/// <summary>The kinds of RESP2 replies.</summary>
public enum RespKind
{
/// <summary><c>+OK</c>.</summary>
SimpleString = 0,
/// <summary><c>-ERR ...</c>.</summary>
Error = 1,
/// <summary><c>:42</c>.</summary>
Number = 2,
/// <summary><c>$5 hello</c>.</summary>
BulkString = 3,
/// <summary><c>*2 ...</c>.</summary>
Array = 4,
/// <summary><c>$-1</c> or <c>*-1</c>.</summary>
Null = 5,
}
/// <summary>A reply of the Redis protocol (RESP2).</summary>
/// <param name="Kind">The kind.</param>
/// <param name="Bytes">The bytes of a string or error.</param>
/// <param name="Number">The value of an integer.</param>
/// <param name="Items">The elements of an array.</param>
public sealed record RespValue(RespKind Kind, byte[]? Bytes = null, long Number = 0, IReadOnlyList<RespValue>? Items = null)
{
/// <summary>The null reply.</summary>
public static RespValue Null { get; } = new(RespKind.Null);
/// <summary>The text of a string or error reply.</summary>
public string? Text => Bytes is null ? null : Encoding.UTF8.GetString(Bytes);
}
/// <summary>A Redis error reply.</summary>
public sealed class RedisException : Exception
{
/// <summary>Creates the exception.</summary>
public RedisException()
{
}
/// <summary>Creates the exception with a message.</summary>
/// <param name="message">The message.</param>
public RedisException(string message) : base(message)
{
}
/// <summary>Creates the exception with a message and a cause.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public RedisException(string message, Exception innerException) : base(message, innerException)
{
}
}
/// <summary>Encodes commands and decodes replies of RESP2 (https://redis.io/docs/reference/protocol-spec/).</summary>
public static class Resp
{
private static readonly byte[] CrLf = "\r\n"u8.ToArray();
/// <summary>Encodes a command as an array of bulk strings.</summary>
/// <param name="arguments">The command and its arguments.</param>
/// <returns>The bytes to send.</returns>
public static byte[] Command(params IReadOnlyList<object> arguments)
{
ArgumentNullException.ThrowIfNull(arguments);
var buffer = new ArrayBufferWriter<byte>();
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();
}
/// <summary>Reads one reply.</summary>
/// <param name="stream">The connection.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The reply.</returns>
/// <exception cref="IOException">The connection closed or sent something that is not RESP.</exception>
public static async Task<RespValue> 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<byte> buffer, string text)
{
buffer.Write(Encoding.ASCII.GetBytes(text));
buffer.Write(CrLf);
}
}
/// <summary>Reads lines and fixed-size blocks from a stream, with its own buffer.</summary>
/// <param name="stream">The stream.</param>
public sealed class BufferedReader(Stream stream)
{
private readonly byte[] _buffer = new byte[16 * 1024];
private int _start;
private int _end;
/// <summary>Reads up to <c>\r\n</c> (not included), as ASCII.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The line.</returns>
public async Task<string> ReadLineAsync(CancellationToken cancellationToken)
{
var line = new List<byte>();
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);
}
}
/// <summary>Reads exactly <paramref name="count"/> bytes.</summary>
/// <param name="count">How many.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The bytes.</returns>
public async Task<byte[]> 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.");
}
}
}
@@ -4,6 +4,11 @@
<RootNamespace>Khaemhat.Infrastructure</RootNamespace>
</PropertyGroup>
<!-- The ASP.NET Core shared framework (logging, options, DataProtection, hosting): part of .NET, not a package. -->
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Khaemhat.Core/Khaemhat.Core.csproj" />
<ProjectReference Include="../Khaemhat.Data/Khaemhat.Data.csproj" />
@@ -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;
/// <summary>
/// An instance licence (SPEC §8.2). It travels as a <c>.khl</c> file: a JSON object with the licence and an ECDSA
/// P-256 signature over its canonical form (<see cref="CanonicalBytes"/>).
/// </summary>
public sealed record LicenseDocument
{
/// <summary>The licence identifier.</summary>
public string Id { get; init; } = string.Empty;
/// <summary>The licence holder.</summary>
public string Licensee { get; init; } = string.Empty;
/// <summary>The instance the licence is bound to; <see langword="null"/> for any instance.</summary>
public string? InstanceId { get; init; }
/// <summary>When it was issued (UTC).</summary>
public DateTime IssuedAt { get; init; }
/// <summary>When it expires (UTC); <see langword="null"/> for no expiry.</summary>
public DateTime? ExpiresAt { get; init; }
/// <summary>Concurrent users across all companies.</summary>
public int MaxConcurrentUsers { get; init; }
/// <summary>Companies on the instance.</summary>
public int MaxCompanies { get; init; }
/// <summary>The module codes.</summary>
public IReadOnlyList<string> Modules { get; init; } = [];
/// <summary>Days of full use after the expiry, before read-only.</summary>
public int GracePeriodDays { get; init; }
/// <summary>
/// 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.
/// </summary>
/// <returns>The UTF-8 bytes.</returns>
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);
}
/// <summary>The JSON settings of licence files.</summary>
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 };
}
/// <summary>The outcome of a licence check. <see cref="Error"/> is <c>format_invalid</c> or <c>signature_invalid</c>.</summary>
/// <param name="Document">The licence, when valid.</param>
/// <param name="Error">The error code otherwise.</param>
public sealed record LicenseVerification(LicenseDocument? Document, string? Error)
{
/// <summary>Whether the licence is authentic.</summary>
public bool IsValid => Document is not null;
}
/// <summary>Signs licences and activation codes. Used only by <c>tools/Khaemhat.LicenseTool</c>, with the private key.</summary>
public static class LicenseSigner
{
/// <summary>The format marker of <c>.khl</c> files.</summary>
public const string Format = "khl1";
/// <summary>Creates a key pair.</summary>
/// <returns>The private key (PKCS#8 PEM) and the public key (SubjectPublicKeyInfo, base64).</returns>
public static (string PrivateKeyPem, string PublicKeyBase64) CreateKeyPair()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
return (key.ExportPkcs8PrivateKeyPem(), Convert.ToBase64String(key.ExportSubjectPublicKeyInfo()));
}
/// <summary>Signs a licence.</summary>
/// <param name="document">The licence.</param>
/// <param name="privateKey">The private key.</param>
/// <returns>The <c>.khl</c> text.</returns>
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);
}
/// <summary>Creates a signed activation code for one module (see <see cref="ModuleActivationCode"/>).</summary>
/// <param name="module">The module code.</param>
/// <param name="expiresMonth">The last month of validity.</param>
/// <param name="instanceId">The instance it is bound to, or <see langword="null"/> for any instance.</param>
/// <param name="privateKey">The private key.</param>
/// <returns>The code.</returns>
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);
}
/// <summary>Checks licences and activation codes with the public key built into the product (SPEC §8.2).</summary>
public sealed class LicenseVerifier
{
/// <summary>
/// The public key of the BalboSoft licences (SubjectPublicKeyInfo, base64). The private key never enters the repository.
/// </summary>
public const string ProductPublicKey =
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEE4ybLR3rfbtmjS7vRBg8WQOz6qNOPG8itlFy9MufvWrT/qoOfxCLwehR9DnKE77GXvqD2J+ZM0Fs6ccS84YBDw==";
private readonly byte[] _publicKey;
/// <summary>Creates a verifier.</summary>
/// <param name="publicKeyBase64">The public key (SubjectPublicKeyInfo, base64).</param>
public LicenseVerifier(string publicKeyBase64)
{
ArgumentException.ThrowIfNullOrWhiteSpace(publicKeyBase64);
_publicKey = Convert.FromBase64String(publicKeyBase64);
}
/// <summary>A verifier with <see cref="ProductPublicKey"/>.</summary>
public static LicenseVerifier Product { get; } = new(ProductPublicKey);
/// <summary>Checks a <c>.khl</c> file.</summary>
/// <param name="text">The file content.</param>
/// <returns>The licence when the signature is valid.</returns>
public LicenseVerification Verify(string text)
{
LicenseSigner.LicenseFile? file;
try
{
file = JsonSerializer.Deserialize<LicenseSigner.LicenseFile>(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);
}
/// <summary>Checks a module activation code.</summary>
/// <param name="code">The code.</param>
/// <returns>The parsed code when the signature is valid, or the error code.</returns>
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;
}
}
}
/// <summary>
/// An activation code for one module: <c>KH1-&lt;MODULE&gt;-&lt;YYYYMM&gt;-&lt;payload base32&gt;-&lt;signature base32&gt;</c>
/// (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 <c>YYYYMM</c>.
/// </summary>
public sealed record ModuleActivationCode(string Module, DateOnly ExpiresMonth, string Payload)
{
/// <summary>The format version.</summary>
public const string Prefix = "KH1";
/// <summary>The text that is signed (everything before the signature).</summary>
public string SignedBody => Body(Module, ExpiresMonth, Payload);
/// <summary>The last moment of validity: the end of <see cref="ExpiresMonth"/> (UTC).</summary>
public DateTime ExpiresAt => new DateTime(ExpiresMonth.Year, ExpiresMonth.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddTicks(-10);
/// <summary>Whether the code works on an instance.</summary>
/// <param name="instanceId">The instance identifier.</param>
/// <returns><see langword="true"/> if the code is for any instance or for this one.</returns>
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;
}
}
/// <summary>The error codes of licences.</summary>
public static class LicenseErrors
{
/// <summary>The text is not a licence or a code.</summary>
public const string FormatInvalid = "format_invalid";
/// <summary>The signature does not match: changed or not issued by BalboSoft.</summary>
public const string SignatureInvalid = "signature_invalid";
/// <summary>A fictitious code outside test mode (SPEC §8.3).</summary>
public const string TestOnly = "license_test_only";
/// <summary>The licence or code has expired.</summary>
public const string Expired = "license_expired";
/// <summary>The licence or code belongs to another instance.</summary>
public const string WrongInstance = "license_wrong_instance";
/// <summary>The module code is unknown.</summary>
public const string UnknownModule = "module_unknown";
}
@@ -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;
/// <summary>
/// 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 <c>sys_log</c>. Events are queued and written in batches by <see cref="DbLogSink"/>; until the
/// system database is ready (<see cref="DbLogSink.Start"/>) they wait in the queue. Section, trace, user, company and
/// request come from the logging scopes.
/// </summary>
[ProviderAlias("Database")]
public sealed class DbLoggerProvider : ILoggerProvider, ISupportExternalScope
{
private readonly DbLogSink _sink;
private IExternalScopeProvider _scopes = new LoggerExternalScopeProvider();
/// <summary>Creates the provider.</summary>
/// <param name="sink">The queue that writes the events.</param>
public DbLoggerProvider(DbLogSink sink)
{
ArgumentNullException.ThrowIfNull(sink);
_sink = sink;
}
/// <inheritdoc />
public ILogger CreateLogger(string categoryName) => new DbLogger(categoryName, this);
/// <inheritdoc />
public void SetScopeProvider(IExternalScopeProvider scopeProvider) => _scopes = scopeProvider ?? new LoggerExternalScopeProvider();
/// <inheritdoc />
public void Dispose()
{
}
private sealed class DbLogger(string category, DbLoggerProvider provider) : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => provider._scopes.Push(state);
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None && !DbLogSink.IsWriting;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> 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<string, object?>(StringComparer.Ordinal);
if (state is IEnumerable<KeyValuePair<string, object?>> 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<KeyValuePair<string, object?>> 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];
}
}
/// <summary>
/// Writes queued log events to <c>sys_log</c> 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.
/// </summary>
public sealed class DbLogSink : IAsyncDisposable
{
private const int BatchSize = 200;
private static readonly AsyncLocal<bool> Writing = new();
private readonly Channel<LogEntry> _queue = Channel.CreateBounded<LogEntry>(
new BoundedChannelOptions(20_000) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
private IUnitOfWorkFactory? _factory;
private Task? _writer;
private CancellationTokenSource? _stopping;
/// <summary>Whether the current flow is the sink writing (its own events are not logged to the database).</summary>
public static bool IsWriting => Writing.Value;
/// <summary>Events written since the start.</summary>
public long Written { get; private set; }
/// <summary>Events lost because the database failed.</summary>
public long Failed { get; private set; }
/// <summary>Queues an event.</summary>
/// <param name="entry">The event.</param>
public void Enqueue(LogEntry entry) => _queue.Writer.TryWrite(entry);
/// <summary>Starts writing, once the system database is migrated.</summary>
/// <param name="factory">Opens the system database.</param>
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));
}
/// <summary>Writes what is queued now (tests, shutdown).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task FlushAsync(CancellationToken cancellationToken = default)
{
var batch = new List<LogEntry>();
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);
}
}
/// <inheritdoc />
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<LogEntry> 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<LogEntry, long>();
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;
}
}
}
@@ -0,0 +1,69 @@
using System.Text;
namespace Khaemhat.Infrastructure.Security;
/// <summary>Base32 of RFC 4648 (alphabet <c>A-Z2-7</c>), used by TOTP secrets and activation codes. No padding is written.</summary>
public static class Base32
{
private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/// <summary>Encodes bytes.</summary>
/// <param name="data">The bytes.</param>
/// <returns>The text, without padding.</returns>
public static string Encode(ReadOnlySpan<byte> 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();
}
/// <summary>Decodes text; spaces, dashes and padding are ignored, letters may be lower-case.</summary>
/// <param name="text">The text.</param>
/// <returns>The bytes.</returns>
/// <exception cref="FormatException">A character is not in the alphabet.</exception>
public static byte[] Decode(string text)
{
ArgumentNullException.ThrowIfNull(text);
var output = new List<byte>(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];
}
}
@@ -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;
/// <summary>
/// The ASP.NET Core DataProtection key ring in <c>sys_data_protection_keys</c> (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 <see cref="SecretKeyXmlEncryptor"/>.
/// </summary>
/// <param name="factory">Opens the system database.</param>
public sealed class DataProtectionKeyStore(IUnitOfWorkFactory factory) : IXmlRepository
{
/// <inheritdoc />
public IReadOnlyCollection<XElement> GetAllElements() =>
Task.Run(async () =>
{
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.System).ConfigureAwait(false);
var rows = await unitOfWork.Repository<DataProtectionKey, long>().ListAsync(Query.For<DataProtectionKey>().OrderBy(k => k.Id)).ConfigureAwait(false);
return (IReadOnlyCollection<XElement>)[.. rows.Items.Select(k => XElement.Parse(k.Xml))];
}).GetAwaiter().GetResult();
/// <inheritdoc />
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<DataProtectionKey, long>().InsertAsync(new DataProtectionKey
{
FriendlyName = friendlyName.Length > 200 ? friendlyName[..200] : friendlyName,
Xml = element.ToString(SaveOptions.DisableFormatting),
}).ConfigureAwait(false);
}).GetAwaiter().GetResult();
}
}
/// <summary>Encrypts DataProtection keys with the instance key (<c>KHAEMHAT_SECRET_KEY</c>).</summary>
/// <param name="protector">The instance key.</param>
public sealed class SecretKeyXmlEncryptor(ISecretProtector protector) : IXmlEncryptor
{
/// <summary>The purpose of the encryption.</summary>
public const string Purpose = "dataprotection:keys";
/// <inheritdoc />
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));
}
}
/// <summary>Decrypts what <see cref="SecretKeyXmlEncryptor"/> wrote; created by DataProtection with the service provider.</summary>
public sealed class SecretKeyXmlDecryptor : IXmlDecryptor
{
private readonly ISecretProtector _protector;
/// <summary>Creates the decryptor.</summary>
/// <param name="services">The services, holding the instance key.</param>
public SecretKeyXmlDecryptor(IServiceProvider services) => _protector = services.GetRequiredService<ISecretProtector>();
/// <inheritdoc />
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));
}
}
@@ -0,0 +1,112 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Khaemhat.Infrastructure.Security;
/// <summary>The result of checking a password against a stored hash.</summary>
public enum PasswordVerification
{
/// <summary>The password does not match (or the hash is not readable).</summary>
Failed = 0,
/// <summary>The password matches.</summary>
Succeeded = 1,
/// <summary>The password matches, but the hash uses older parameters: store a new hash.</summary>
SucceededRehashNeeded = 2,
}
/// <summary>
/// Password hashes with PBKDF2-HMAC-SHA256 (SPEC §7.3): 600,000 iterations, a random 16-byte salt and a 32-byte
/// result, stored as <c>pbkdf2-sha256$600000$&lt;salt base64&gt;$&lt;hash base64&gt;</c>. The comparison runs in
/// constant time.
/// </summary>
public static class PasswordHasher
{
/// <summary>The algorithm prefix of the stored format.</summary>
public const string Algorithm = "pbkdf2-sha256";
/// <summary>The iterations of new hashes (OWASP 2023 recommendation for PBKDF2-HMAC-SHA256).</summary>
public const int Iterations = 600_000;
private const int SaltLength = 16;
private const int HashLength = 32;
/// <summary>Hashes a password with a new random salt.</summary>
/// <param name="password">The password.</param>
/// <returns>The stored form.</returns>
public static string Hash(string password) => Hash(password, Iterations);
/// <summary>Hashes a password with the given iterations (tests use fewer to stay fast).</summary>
/// <param name="password">The password.</param>
/// <param name="iterations">The PBKDF2 iterations.</param>
/// <returns>The stored form.</returns>
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));
}
/// <summary>Checks a password against a stored hash.</summary>
/// <param name="storedHash">The stored form; <see langword="null"/> never matches.</param>
/// <param name="password">The password typed.</param>
/// <returns>The outcome.</returns>
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;
}
}
@@ -0,0 +1,64 @@
using System.Security.Cryptography;
using System.Text;
namespace Khaemhat.Infrastructure.Security;
/// <summary>
/// Random tokens for sessions, password recovery and recovery codes. Tokens are URL-safe base64 without padding; the
/// database stores only <see cref="Hash"/>, so a copy of a table does not reveal a usable token.
/// </summary>
public static class SecureTokenGenerator
{
/// <summary>A token of <paramref name="bytes"/> random bytes (32 = 256 bits).</summary>
/// <param name="bytes">The entropy in bytes.</param>
/// <returns>The token.</returns>
public static string Create(int bytes = 32)
{
ArgumentOutOfRangeException.ThrowIfLessThan(bytes, 16);
return Base64Url(RandomNumberGenerator.GetBytes(bytes));
}
/// <summary>A short code for people: groups of letters and digits without look-alikes, for example <c>K7QM-2XRP</c>.</summary>
/// <param name="groups">The number of groups of four characters.</param>
/// <returns>The code.</returns>
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();
}
/// <summary>The SHA-256 hash of a token in lower-case hexadecimal, as stored in the database.</summary>
/// <param name="token">The token.</param>
/// <returns>64 hexadecimal digits.</returns>
public static string Hash(string token)
{
ArgumentNullException.ThrowIfNull(token);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
}
/// <summary>Compares two token hashes in constant time.</summary>
/// <param name="a">A hash.</param>
/// <param name="b">Another hash.</param>
/// <returns>Whether they are equal.</returns>
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('/', '_');
}
@@ -0,0 +1,106 @@
using System.Buffers.Binary;
using System.Globalization;
using System.Security.Cryptography;
namespace Khaemhat.Infrastructure.Security;
/// <summary>
/// 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.
/// </summary>
public static class TotpGenerator
{
/// <summary>The length of a step in seconds.</summary>
public const int StepSeconds = 30;
/// <summary>The number of digits.</summary>
public const int Digits = 6;
/// <summary>The length of new secrets in bytes (160 bits, as RFC 4226 recommends).</summary>
public const int SecretLength = 20;
/// <summary>A new random secret in base32, to show to the user and store encrypted.</summary>
/// <returns>The secret.</returns>
public static string CreateSecret() => Base32.Encode(RandomNumberGenerator.GetBytes(SecretLength));
/// <summary>The time step of a moment.</summary>
/// <param name="time">The moment.</param>
/// <returns>The step number.</returns>
public static long StepOf(DateTimeOffset time) => time.ToUnixTimeSeconds() / StepSeconds;
/// <summary>The code of a step.</summary>
/// <param name="secret">The secret bytes.</param>
/// <param name="step">The step number.</param>
/// <returns>The code, zero-padded to six digits.</returns>
public static string Compute(ReadOnlySpan<byte> secret, long step)
{
Span<byte> counter = stackalloc byte[8];
BinaryPrimitives.WriteInt64BigEndian(counter, step);
Span<byte> 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);
}
/// <summary>Checks a code.</summary>
/// <param name="secretBase32">The secret in base32.</param>
/// <param name="code">The code typed (spaces are ignored).</param>
/// <param name="now">The current time.</param>
/// <param name="lastUsedStep">The last step accepted for this account, or <see langword="null"/>.</param>
/// <returns>The matching step, to store as the last used one; <see langword="null"/> if the code is not valid.</returns>
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);
}
}
/// <summary>
/// The <c>otpauth://</c> address that authenticator apps read (key URI format), for the QR code or a link.
/// </summary>
/// <param name="secretBase32">The secret in base32.</param>
/// <param name="account">The account label, for example <c>root@DEMO</c>.</param>
/// <param name="issuer">The issuer shown by the app.</param>
/// <returns>The address.</returns>
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}";
}
}
+11 -3
View File
@@ -12,14 +12,22 @@
<ResourcePreloader />
<link rel="stylesheet" href="@Assets["app.css"]" />
<link rel="stylesheet" href="@Assets["Khaemhat.Web.styles.css"]" />
<ImportMap />
<HeadOutlet @rendermode="InteractiveServer" />
@* No <ImportMap />: it is an inline script, and the content security policy allows none (no JS modules yet). *@
<HeadOutlet @rendermode="PageRenderMode" />
</head>
<body>
<Routes @rendermode="InteractiveServer" />
<Routes @rendermode="PageRenderMode" />
<ReconnectModal />
<script src="@Assets["_framework/blazor.web.js"]"></script>
</body>
</html>
@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;
}
@@ -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. *@
<div class="kh-auth">
<aside class="brand">
<div class="brand-top">
<img class="mark" src="icon.svg" alt="" width="56" height="56" />
<h2>Khaemhat</h2>
<p>Gestionale ERP + CRM per PMI italiane: documenti, magazzino, contabilità e fatturazione elettronica in un'unica applicazione web.</p>
</div>
<ul class="features">
<li><strong>Contabilità italiana completa</strong> prima nota, IVA, registri, bilancio CEE</li>
<li><strong>Fatturazione elettronica</strong> SDI, conservazione, bollo, autofatture</li>
<li><strong>CRM</strong> lead, opportunità, attività, campagne</li>
<li><strong>Più aziende</strong> un database per azienda, backup integrati</li>
</ul>
</aside>
<main class="panel">
<section class="card">
@Body
</section>
<footer>Khaemhat @Version.Version · <a href="https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki">Documentazione</a></footer>
</main>
</div>
@@ -0,0 +1,12 @@
@page "/accesso-negato"
@attribute [ExcludeFromInteractiveRouting]
<PageTitle>Khaemhat · accesso negato</PageTitle>
<main class="kh-construction">
<section class="hero">
<h1>Accesso negato</h1>
<p class="lead">Il tuo profilo non ha il permesso per questa pagina, oppure il modulo non è compreso nella licenza.</p>
<ul class="links"><li><a href="/">Torna alla pagina iniziale</a></li></ul>
</section>
</main>
+30 -9
View File
@@ -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. *@
<PageTitle>Khaemhat · in costruzione</PageTitle>
@* 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. *@
<PageTitle>Khaemhat</PageTitle>
<main class="kh-construction">
<section class="hero">
<img class="mark" src="icon.svg" alt="" width="96" height="96" />
<h1>Khaemhat <span class="ver">v @Version.MajorMinor</span></h1>
<p class="lead">Gestionale ERP + CRM per piccole e medie imprese italiane.</p>
<p class="state">Installazione in costruzione: le funzioni arrivano milestone dopo milestone.</p>
<ul class="links">
<li><a href="https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Roadmap">Roadmap</a></li>
<li><a href="https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki">Documentazione</a></li>
</ul>
<AuthorizeView>
<p class="lead">Benvenuto, <strong>@context.User.FindFirst(SessionCookie.DisplayNameClaim)?.Value</strong>
(@LevelLabel(context.User.FindFirst(SessionCookie.LevelClaim)?.Value))
@if (context.User.FindFirst(SessionCookie.CompanyClaim)?.Value is { } company)
{
<span> · azienda <strong>@company</strong></span>
}
</p>
</AuthorizeView>
<p class="state">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())</p>
<form method="post" action="/logout" class="links">
<AntiforgeryToken />
<button type="submit" class="kh-btn ghost">Esci</button>
</form>
<p class="build">Versione @Version.Full</p>
</section>
</main>
@code {
private static string LevelLabel(string? level) => level switch
{
"SuperUser" => "super utente",
"Administrator" => "amministratore",
_ => "utente",
};
}
@@ -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
<PageTitle>Accedi · Khaemhat</PageTitle>
<h1>Accedi</h1>
<p class="sub">Scegli l'azienda e inserisci le credenziali.</p>
@foreach (var message in Errors)
{
<div class="kh-alert err" role="alert">@message</div>
}
<EditForm Model="Input" method="post" FormName="login" OnSubmit="SubmitAsync" class="kh-form">
<label for="company">Azienda</label>
<InputSelect id="company" @bind-Value="Input.CompanyCode">
<option value="">Nessuna (account di istanza)</option>
@foreach (var company in AvailableCompanies)
{
<option value="@company.Code">@company.Name (@company.Code)</option>
}
</InputSelect>
<label for="user">Nome utente</label>
<InputText id="user" @bind-Value="Input.UserName" autocomplete="username" autofocus required />
<label for="password">Password</label>
<InputText id="password" type="password" @bind-Value="Input.Password" autocomplete="current-password" required />
<label class="check"><InputCheckbox @bind-Value="Input.Remember" /> Ricordami su questo dispositivo</label>
<button type="submit" class="kh-btn primary">Accedi</button>
</EditForm>
@if (TrialNotice is not null)
{
<div class="kh-alert warn">@TrialNotice</div>
}
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm]
private LoginInput Input { get; set; } = default!;
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
private IReadOnlyList<Company> AvailableCompanies { get; set; } = [];
private IReadOnlyList<string> Errors { get; set; } = [];
private string? TrialNotice { get; set; }
/// <inheritdoc />
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; }
}
}
@@ -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
<PageTitle>Cambio password · Khaemhat</PageTitle>
<h1>Scegli una nuova password</h1>
<p class="sub">Al primo accesso, o dopo una password provvisoria, serve una password personale.</p>
@foreach (var message in Errors)
{
<div class="kh-alert err" role="alert">@message</div>
}
<EditForm Model="Input" method="post" FormName="password-change" OnSubmit="SubmitAsync" class="kh-form">
<label for="current">Password attuale o provvisoria</label>
<InputText id="current" type="password" @bind-Value="Input.Current" autocomplete="current-password" autofocus required />
<label for="new">Nuova password</label>
<InputText id="new" type="password" @bind-Value="Input.New" autocomplete="new-password" required />
<label for="confirm">Ripeti la nuova password</label>
<InputText id="confirm" type="password" @bind-Value="Input.Confirm" autocomplete="new-password" required />
<ul class="kh-rules">
<li>Almeno @Policy.MinimumLength caratteri</li>
<li>Almeno tre tipi tra minuscole, maiuscole, cifre e simboli</li>
<li>Diversa dal nome utente e dalle ultime @Policy.HistorySize password</li>
</ul>
<button type="submit" class="kh-btn primary">Salva e continua</button>
</EditForm>
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm]
private PasswordInput Input { get; set; } = default!;
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
private IReadOnlyList<string> Errors { get; set; } = [];
private SessionIdentity? Identity { get; set; }
/// <inheritdoc />
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; }
}
}
@@ -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
<PageTitle>Verifica in due passaggi · Khaemhat</PageTitle>
<h1>Verifica in due passaggi</h1>
<p class="sub">Inserisci il codice a 6 cifre dell'app di autenticazione.</p>
@foreach (var message in Errors)
{
<div class="kh-alert err" role="alert">@message</div>
}
<EditForm Model="Input" method="post" FormName="totp" OnSubmit="SubmitAsync" class="kh-form">
<label for="code">Codice</label>
<InputText id="code" class="otp" @bind-Value="Input.Code" inputmode="numeric" autocomplete="one-time-code" maxlength="20" autofocus required />
<div class="row">
<button type="submit" class="kh-btn primary">Verifica</button>
<span class="hint">Oppure un codice di recupero (XXXX-XXXX)</span>
</div>
</EditForm>
<div class="kh-alert info">Il codice cambia ogni 30 secondi. L'autenticazione a due fattori è obbligatoria per amministratori e super utente.</div>
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm]
private CodeInput Input { get; set; } = default!;
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
private IReadOnlyList<string> Errors { get; set; } = [];
private SessionIdentity? Identity { get; set; }
/// <inheritdoc />
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; }
}
}
@@ -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
<PageTitle>Configura la verifica in due passaggi · Khaemhat</PageTitle>
@if (RecoveryCodes is not null)
{
<h1>Codici di recupero</h1>
<p class="sub">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.</p>
<ul class="kh-codes">
@foreach (var recovery in RecoveryCodes)
{
<li><code>@recovery</code></li>
}
</ul>
<a class="kh-btn primary" href="@NextUrl">Ho salvato i codici, continua</a>
}
else
{
<h1>Configura la verifica in due passaggi</h1>
<p class="sub">Aggiungi l'account a un'app di autenticazione (Google Authenticator, Microsoft Authenticator, Aegis, 2FAS...) e inserisci il primo codice.</p>
@foreach (var message in Errors)
{
<div class="kh-alert err" role="alert">@message</div>
}
@if (Setup is not null)
{
<dl class="kh-secret">
<dt>Chiave da inserire nell'app</dt>
<dd><code>@Grouped(Setup.Secret)</code></dd>
<dt>Sul telefono</dt>
<dd><a href="@Setup.ProvisioningUri">Apri nell'app di autenticazione</a></dd>
</dl>
}
<EditForm Model="Input" method="post" FormName="totp-setup" OnSubmit="SubmitAsync" class="kh-form">
<label for="code">Primo codice dell'app</label>
<InputText id="code" class="otp" @bind-Value="Input.Code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" autofocus required />
<button type="submit" class="kh-btn primary">Attiva</button>
</EditForm>
}
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm]
private CodeInput Input { get; set; } = default!;
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
private IReadOnlyList<string> Errors { get; set; } = [];
private SessionIdentity? Identity { get; set; }
private TotpSetup? Setup { get; set; }
private IReadOnlyList<string>? RecoveryCodes { get; set; }
private string NextUrl { get; set; } = "/";
/// <inheritdoc />
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; }
}
}
@@ -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>? AuthenticationState { get; set; }
/// <inheritdoc />
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);
}
}
+5 -1
View File
@@ -1,6 +1,10 @@
<Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)">
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
</Router>
@@ -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
@@ -0,0 +1,81 @@
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Instance;
using Khaemhat.Data.Migrations;
using Khaemhat.Infrastructure.Logging;
namespace Khaemhat.Web.Hosting;
/// <summary>
/// Runs the start sequence in the background, so that <c>/health/live</c> answers at once and <c>/health/ready</c>
/// 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.
/// </summary>
/// <param name="orchestrator">The start sequence.</param>
/// <param name="state">The start state.</param>
/// <param name="logSink">The database log, flushed at shutdown.</param>
/// <param name="lifetime">Stops the host on failure.</param>
/// <param name="logger">The log.</param>
internal sealed partial class BootstrapService(
StartupOrchestrator orchestrator, BootstrapState state, DbLogSink logSink, IHostApplicationLifetime lifetime, ILogger<BootstrapService> logger)
: BackgroundService
{
/// <summary>
/// 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.
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
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);
}
/// <inheritdoc />
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken).ConfigureAwait(false);
await logSink.DisposeAsync().ConfigureAwait(false);
}
/// <inheritdoc />
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);
}
+15 -9
View File
@@ -1,3 +1,4 @@
using Khaemhat.Application.Instance;
using Khaemhat.Core.Common;
namespace Khaemhat.Web.Hosting;
@@ -5,13 +6,14 @@ namespace Khaemhat.Web.Hosting;
/// <summary>
/// Health endpoints for Docker and reverse proxies (SPEC §16.1, ADR 0012):
/// <c>/health/live</c> says the process answers (the image HEALTHCHECK), <c>/health/ready</c> says it can serve
/// requests (from M1 it also checks the system database), <c>/health</c> summarises both with the version.
/// requests (the start sequence completed: databases migrated), <c>/health</c> summarises both with the version.
/// They carry no personal or configuration data and need no authentication.
/// </summary>
public static class HealthEndpoints
{
/// <summary>Maps the three health endpoints.</summary>
/// <param name="endpoints">The application's route builder.</param>
/// <returns>The route builder.</returns>
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;
}
/// <summary>The body of <c>/health</c>.</summary>
/// <param name="Status"><c>ok</c> when the instance is live and ready.</param>
/// <param name="Status"><c>ok</c> when the instance is live and ready, <c>starting</c> or <c>failed</c> otherwise.</param>
/// <param name="Live">Whether the process answers.</param>
/// <param name="Ready">Whether the instance can serve requests.</param>
/// <param name="Version">Product version (SemVer).</param>
+72 -23
View File
@@ -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
{
/// <summary>Creates the configured application, ready to run.</summary>
/// <param name="args">Command-line arguments (ASP.NET Core host conventions, e.g. <c>--urls</c>).</param>
/// <param name="args">Command-line arguments (ASP.NET Core host conventions, e.g. <c>--urls</c>; also <c>--KHAEMHAT_*=value</c>).</param>
/// <returns>The application.</returns>
/// <exception cref="ConfigurationException">The <c>KHAEMHAT_*</c> variables are missing or not valid.</exception>
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<DbLoggerProvider>("Microsoft", LogLevel.Warning);
builder.Logging.AddFilter<DbLoggerProvider>("System", LogLevel.Warning);
builder.Logging.AddFilter<DbLoggerProvider>(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<IConfigureOptions<KeyManagementOptions>>(sp => new ConfigureOptions<KeyManagementOptions>(o =>
{
o.XmlRepository = new DataProtectionKeyStore(sp.GetRequiredService<Data.IUnitOfWorkFactory>());
o.XmlEncryptor = new SecretKeyXmlEncryptor(sp.GetRequiredService<Core.Security.ISecretProtector>());
}));
// Sign-in with the session cookie (SPEC §7.3) and policies for permissions, levels and modules.
builder.Services.AddAuthentication(SessionCookie.Scheme)
.AddScheme<AuthenticationSchemeOptions, SessionAuthenticationHandler>(SessionCookie.Scheme, null);
builder.Services.AddAuthorization();
builder.Services.AddSingleton<IAuthorizationPolicyProvider, KhaemhatPolicyProvider>();
builder.Services.AddSingleton<IAuthorizationHandler, KhaemhatAuthorizationHandler>();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<AuthenticationStateProvider, SessionRevalidatingStateProvider>();
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<App>()
.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<LogLevel>(options.LogLevel, ignoreCase: true, out var level))
{
if (!Enum.TryParse<LogLevel>(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");
});
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal static class KhaemhatServices
{
/// <summary>Registers every service of the instance.</summary>
/// <param name="services">The container.</param>
/// <param name="options">The validated variables.</param>
/// <param name="logSink">The database log queue, already plugged into the logging pipeline.</param>
/// <returns>The container.</returns>
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<BootstrapState>();
services.AddHttpContextAccessor();
services.AddSingleton<CurrentUserName>();
// Secrets and data access.
services.AddSingleton(SecretKey.FromBase64(options.SecretKey!));
services.AddSingleton<SecretProtector>();
services.AddSingleton<ISecretProtector>(sp => sp.GetRequiredService<SecretProtector>());
services.AddSingleton(new DbProviderCatalog(new SqliteProvider(), new PostgresProvider()));
services.AddSingleton(new MapRegistry().AddFromAssembly(dataAssembly));
services.AddSingleton(sp =>
{
var slow = sp.GetRequiredService<ILoggerFactory>().CreateLogger("Khaemhat.Performance.SlowQueries");
var user = sp.GetRequiredService<CurrentUserName>();
return new DataAccessContext(sp.GetRequiredService<TimeProvider>(), 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<DbProviderCatalog>().Resolve(options.SystemDatabase));
services.AddSingleton<ICompanyRegistry>(sp => new CompanyRegistry(
sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<ISecretProtector>(),
sp.GetRequiredService<MapRegistry>(), sp.GetRequiredService<DataAccessContext>()));
services.AddSingleton<IDatabaseLocator>(sp => new DatabaseLocator(sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<ICompanyRegistry>()));
services.AddSingleton<IUnitOfWorkFactory, UnitOfWorkFactory>();
services.AddSingleton<MigrationRunner>();
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<ICacheProvider>(sp => new RedisCacheProvider(
sp.GetRequiredService<RedisClient>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<RedisCacheProvider>>()));
}
else
{
services.AddSingleton<ICacheProvider>(sp => new MemoryCacheProvider(sp.GetRequiredService<TimeProvider>()));
}
// Security.
services.AddSingleton(new SecurityPolicyOptions());
services.AddSingleton<PasswordPolicy>();
services.AddSingleton<AccountSecurity>();
services.AddSingleton<ISecurityAuditLog, SecurityAuditLog>();
services.AddSingleton<SystemSettingsStore>();
services.AddSingleton(ModuleRegistry.Default);
services.AddSingleton(LicenseVerifier.Product);
services.AddSingleton(new LicenseSettings(options.License, options.Mode));
services.AddSingleton<LicenseGate>();
services.AddSingleton<ILicenseGate>(sp => sp.GetRequiredService<LicenseGate>());
services.AddSingleton<ILicenseActivationService, OfflineActivationService>();
services.AddSingleton<PermissionService>();
services.AddSingleton<RoleService>();
services.AddSingleton<SystemUserService>();
services.AddSingleton<UserService>();
services.AddSingleton<SessionStore>();
services.AddSingleton<NotificationDispatcher>();
services.AddSingleton<SignInService>();
// Companies and start.
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
services.AddSingleton(sp => new StartupOrchestrator(
sp.GetRequiredService<InstanceDatabases>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<MigrationRunner>(),
sp.GetRequiredService<SystemSettingsStore>(), sp.GetRequiredService<RoleService>(), sp.GetRequiredService<ILicenseGate>(),
sp.GetRequiredService<SystemUserService>(), sp.GetRequiredService<CompanyService>(), options, sp.GetRequiredService<IUnitOfWorkFactory>(),
logSink, sp.GetRequiredService<BootstrapState>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<StartupOrchestrator>>()));
services.AddHostedService<BootstrapService>();
// History of the records and scheduled tasks.
services.AddSingleton<AuditTrail>();
services.AddSingleton<IScheduledJob, SessionCleanupJob>();
services.AddSingleton<IScheduledJob, LicenseCheckJob>();
services.AddSingleton<IScheduledJob, LogRetentionJob>();
services.AddSingleton<JobScheduler>();
services.AddHostedService<JobSchedulerService>();
return services;
}
}
/// <summary>The user name written in the audit columns: the signed-in user of the current request, else <c>system</c>.</summary>
/// <param name="accessor">The current request.</param>
internal sealed class CurrentUserName(IHttpContextAccessor accessor)
{
/// <summary>The name.</summary>
/// <returns>The user name, or <see langword="null"/> outside requests.</returns>
public string? Get() => accessor.HttpContext?.User.Identity is { IsAuthenticated: true, Name: { } name } ? name : null;
}
+186
View File
@@ -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;
/// <summary>The middleware of the instance, in pipeline order.</summary>
internal static class KhaemhatMiddleware
{
/// <summary>
/// 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.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
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);
});
/// <summary>
/// While the start sequence runs (migrations), every request except health checks and static files gets a 503 page
/// that refreshes itself.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseStartingPage(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
var state = context.RequestServices.GetRequiredService<BootstrapState>();
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);
});
/// <summary>
/// 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 <c>X-Company</c> names another company
/// than the account's own gets 403. Sign-in, health checks and static files are never blocked.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
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<CompanyContextResolver>();
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);
});
/// <summary>
/// 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 <c>X-Trace-Id</c>.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
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<ILoggerFactory>().CreateLogger("Khaemhat.Web.Requests");
var actor = SessionCookie.ActorOf(context.User);
using var scope = logger.BeginScope(new Dictionary<string, object?>
{
[LogSections.TraceIdKey] = traceId,
[LogSections.RequestKey] = context.Request.Method + " " + context.Request.Path,
[LogSections.UserKey] = actor?.UserName,
[LogSections.CompanyKey] = actor?.CompanyCode,
});
await next(context).ConfigureAwait(false);
});
/// <summary>
/// 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.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseLoginRateLimit(this IApplicationBuilder app)
{
var limiter = PartitionedRateLimiter.Create<HttpContext, string>(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 = "<meta http-equiv=\"refresh\" content=\"" + text + "\">";
}
return context.Response.WriteAsync(
"<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\">" + refresh +
"<title>Khaemhat</title><link rel=\"stylesheet\" href=\"/app.css\"></head><body><main class=\"kh-construction\"><section class=\"hero\">" +
"<img class=\"mark\" src=\"/icon.svg\" alt=\"\" width=\"96\" height=\"96\"><h1>Khaemhat</h1><p class=\"state\">" + WebUtility.HtmlEncode(message) +
"</p></section></main></body></html>",
context.RequestAborted);
}
}
+25 -1
View File
@@ -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;
+120
View File
@@ -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;
/// <summary>Requires a permission (SPEC §7.2), checked with the licence: <c>[RequirePermission("sales.invoices.create")]</c>.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequirePermissionAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="code">The permission code.</param>
public RequirePermissionAttribute(string code)
: base(KhaemhatPolicies.PermissionPrefix + code) => Code = code;
/// <summary>The permission code.</summary>
public string Code { get; }
}
/// <summary>Requires a level: <c>[RequireLevel(UserLevel.Administrator)]</c> for instance administration.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class RequireLevelAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="level">The minimum level.</param>
public RequireLevelAttribute(UserLevel level)
: base(KhaemhatPolicies.LevelPrefix + level) => Level = level;
/// <summary>The minimum level.</summary>
public UserLevel Level { get; }
}
/// <summary>Requires a licensed module: <c>[RequireModule("CRM")]</c>.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequireModuleAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="moduleCode">The module code.</param>
public RequireModuleAttribute(string moduleCode)
: base(KhaemhatPolicies.ModulePrefix + moduleCode) => ModuleCode = moduleCode;
/// <summary>The module code.</summary>
public string ModuleCode { get; }
}
/// <summary>The policy names built from the attributes.</summary>
public static class KhaemhatPolicies
{
/// <summary>Prefix of permission policies.</summary>
public const string PermissionPrefix = "perm:";
/// <summary>Prefix of level policies.</summary>
public const string LevelPrefix = "level:";
/// <summary>Prefix of module policies.</summary>
public const string ModulePrefix = "module:";
}
/// <summary>A requirement built from a policy name.</summary>
/// <param name="Kind">The prefix.</param>
/// <param name="Value">The permission, level or module.</param>
internal sealed record KhaemhatRequirement(string Kind, string Value) : IAuthorizationRequirement;
/// <summary>Builds the policies named by <see cref="KhaemhatPolicies"/> on demand; other names go to the default provider.</summary>
/// <param name="options">The authorization options.</param>
internal sealed class KhaemhatPolicyProvider(IOptions<AuthorizationOptions> options) : IAuthorizationPolicyProvider
{
private readonly DefaultAuthorizationPolicyProvider _fallback = new(options);
/// <inheritdoc />
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => _fallback.GetDefaultPolicyAsync();
/// <inheritdoc />
public Task<AuthorizationPolicy?> GetFallbackPolicyAsync() => _fallback.GetFallbackPolicyAsync();
/// <inheritdoc />
public Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
{
foreach (var prefix in (string[])[KhaemhatPolicies.PermissionPrefix, KhaemhatPolicies.LevelPrefix, KhaemhatPolicies.ModulePrefix])
{
if (policyName.StartsWith(prefix, StringComparison.Ordinal))
{
return Task.FromResult<AuthorizationPolicy?>(new AuthorizationPolicyBuilder(SessionCookie.Scheme)
.RequireAuthenticatedUser()
.AddRequirements(new KhaemhatRequirement(prefix, policyName[prefix.Length..]))
.Build());
}
}
return _fallback.GetPolicyAsync(policyName);
}
}
/// <summary>Evaluates <see cref="KhaemhatRequirement"/> with the permission service and the licence.</summary>
/// <param name="permissions">The permissions.</param>
/// <param name="licenses">The licence.</param>
internal sealed class KhaemhatAuthorizationHandler(PermissionService permissions, ILicenseGate licenses) : AuthorizationHandler<KhaemhatRequirement>
{
/// <inheritdoc />
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<UserLevel>(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);
}
}
}
+70
View File
@@ -0,0 +1,70 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
namespace Khaemhat.Web.Security;
/// <summary>The pages of the sign-in flow and the messages shown for the error codes of <see cref="SecurityErrors"/>.</summary>
public static class LoginFlow
{
/// <summary>The login page (mockup 001).</summary>
public const string LoginPage = "/login";
/// <summary>The TOTP page (mockup 002).</summary>
public const string TotpPage = "/login/verifica";
/// <summary>The TOTP setup page.</summary>
public const string TotpSetupPage = "/login/configura-verifica";
/// <summary>The forced password change (mockup 003).</summary>
public const string PasswordChangePage = "/login/cambio-password";
/// <summary>Where a session in a state goes next.</summary>
/// <param name="state">The state reached.</param>
/// <param name="returnUrl">Where the user wanted to go.</param>
/// <returns>The local address.</returns>
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,
};
/// <summary>A return address only when it stays on this site.</summary>
/// <param name="returnUrl">The address asked for.</param>
/// <returns>The address, or <c>/</c>.</returns>
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
: "/";
/// <summary>The Italian message of an error code (several codes may be joined by commas).</summary>
/// <param name="error">The code(s).</param>
/// <returns>The messages.</returns>
public static IReadOnlyList<string> 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;
}
@@ -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;
/// <summary>The session cookie and the claims built from it.</summary>
public static class SessionCookie
{
/// <summary>The authentication scheme.</summary>
public const string Scheme = "KhaemhatSession";
/// <summary>The cookie name.</summary>
public const string Name = "khaemhat_session";
/// <summary>Claim: the session row.</summary>
public const string SessionIdClaim = "kh:session";
/// <summary>Claim: the database holding the account (<c>_</c> for instance accounts).</summary>
public const string OwnerClaim = "kh:owner";
/// <summary>Claim: the account row.</summary>
public const string UserIdClaim = "kh:user";
/// <summary>Claim: the level.</summary>
public const string LevelClaim = "kh:level";
/// <summary>Claim: the company the session works in.</summary>
public const string CompanyClaim = "kh:company";
/// <summary>Claim: the linked company user of an administrator.</summary>
public const string LinkedUserClaim = "kh:linked";
/// <summary>Claim: the name shown.</summary>
public const string DisplayNameClaim = "kh:display";
/// <summary>Sets the cookie.</summary>
/// <param name="context">The request.</param>
/// <param name="value">The cookie value.</param>
/// <param name="persistentUntil">Expiry for "remember me"; <see langword="null"/> for a browser-session cookie.</param>
public static void Write(HttpContext context, string value, DateTimeOffset? persistentUntil = null)
{
ArgumentNullException.ThrowIfNull(context);
context.Response.Cookies.Append(Name, value, Options(context, persistentUntil));
}
/// <summary>Removes the cookie.</summary>
/// <param name="context">The request.</param>
public static void Clear(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.Response.Cookies.Delete(Name, Options(context, null));
}
/// <summary>The cookie of the request.</summary>
/// <param name="context">The request.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
public static string? Read(HttpContext context) => context?.Request.Cookies[Name];
/// <summary>The claims of a signed-in session.</summary>
/// <param name="identity">The session.</param>
/// <returns>The principal.</returns>
public static ClaimsPrincipal Principal(SessionIdentity identity)
{
ArgumentNullException.ThrowIfNull(identity);
var claims = new List<Claim>
{
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));
}
/// <summary>The actor of a principal built by <see cref="Principal"/>.</summary>
/// <param name="user">The principal.</param>
/// <returns>The actor, or <see langword="null"/> when not signed in.</returns>
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<UserLevel>(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);
}
/// <summary>The account of a principal.</summary>
/// <param name="user">The principal.</param>
/// <returns>The owner, or <see langword="null"/>.</returns>
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;
}
/// <summary>The session row of a principal.</summary>
/// <param name="user">The principal.</param>
/// <returns>The session id, or <see langword="null"/>.</returns>
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<KhaemhatOptions>()?.PublicUrl;
return new CookieOptions
{
HttpOnly = true,
IsEssential = true,
SameSite = SameSiteMode.Lax,
Path = "/",
Secure = context.Request.IsHttps || (publicUrl?.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ?? false),
Expires = persistentUntil,
};
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="options">The scheme options.</param>
/// <param name="logger">The log factory.</param>
/// <param name="encoder">The URL encoder.</param>
/// <param name="signIn">Resolves sessions.</param>
internal sealed class SessionAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, SignInService signIn)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
/// <summary>The key of the resolved identity in <see cref="HttpContext.Items"/>.</summary>
public const string IdentityItem = "kh:identity";
/// <inheritdoc />
protected override async Task<AuthenticateResult> 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();
}
/// <inheritdoc />
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;
}
/// <inheritdoc />
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.Redirect("/accesso-negato");
return Task.CompletedTask;
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="loggerFactory">The log factory.</param>
/// <param name="sessions">The sessions.</param>
internal sealed class SessionRevalidatingStateProvider(ILoggerFactory loggerFactory, SessionStore sessions)
: RevalidatingServerAuthenticationStateProvider(loggerFactory)
{
/// <inheritdoc />
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1);
/// <inheritdoc />
protected override async Task<bool> 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);
}
}
@@ -0,0 +1,46 @@
using System.Security.Claims;
using Khaemhat.Application.Instance;
using Microsoft.AspNetCore.Components.Authorization;
namespace Khaemhat.Web.Security;
/// <summary>
/// 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 <c>X-Company</c>.
/// </summary>
/// <param name="authentication">The authentication state of the circuit.</param>
/// <param name="http">The current request, outside circuits.</param>
/// <param name="resolver">The rules.</param>
internal sealed class WebCompanyContext(AuthenticationStateProvider authentication, IHttpContextAccessor http, CompanyContextResolver resolver) : ICompanyContext
{
private CompanyContextResult? _result;
/// <inheritdoc />
public async ValueTask<CompanyContextResult> 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;
}
}
+51
View File
@@ -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; }
}
@@ -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;
/// <summary>Configuration, password policy, company context and record history (SPEC §5, §6, §7).</summary>
[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<ConfigurationException>(() => 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<ConfigurationException>(() => 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<InvalidOperationException>(() => 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<Role>(null, after).ContainsKey("Code"));
}
private static Dictionary<string, string> 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<Company> _companies = [.. companies.Select((c, i) => new Company { Id = i + 1, Code = c.Code, Name = c.Code, Status = c.Status })];
public Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default) => Task.FromResult<IReadOnlyList<Company>>(_companies);
public Task<Company?> FindAsync(string code, CancellationToken cancellationToken = default) =>
Task.FromResult(_companies.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase)));
public Task<Company> RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task<DatabaseTarget> ResolveAsync(string code, CancellationToken cancellationToken = default) => throw new NotSupportedException();
public Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default) => throw new NotSupportedException();
}
}
@@ -0,0 +1,77 @@
using Khaemhat.Core.Logging;
using Khaemhat.Core.Scheduling;
namespace Khaemhat.Core.Tests.Common;
/// <summary>The five-field cron of the scheduled tasks (SPEC §9.6) and the log sections (SPEC §9.5).</summary>
[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);
}
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more