From bd7fbff61877c5f0134b07c1baaa9fd61641c80c Mon Sep 17 00:00:00 2001 From: Imani Manyara Date: Tue, 10 Nov 2026 06:14:35 -0500 Subject: [PATCH 1/4] feat: services namespace, history and rollback, events, listeners and alerts (phase 4a) Move every service class into Services\ (19 classes, old names kept through class_alias until 1.0). Add settings_history behind the history.enabled schema switch, written in each change's transaction, with history(), rollback() and historyDiff() on the Settings contract and the laranail::settings.history and prune-history commands. Add lock, rollback, category, maintenance and refusal events, the built-in alert and log listeners, and rule-based, throttled alerts through Laravel notifications that never carry a value. --- CHANGELOG.md | 72 ++++ README.md | 7 +- benchmarks/ReadBench.php | 2 +- composer.json | 5 +- config/settings.php | 64 +++ .../create_laranail_settings_tables.php | 74 +++- docs/architecture.md | 45 +- docs/configuration.md | 12 +- docs/recipes/listening-to-settings-events.md | 46 ++ docs/recipes/rolling-back-a-setting.md | 40 ++ docs/tools/alerts.md | 77 ++++ docs/tools/commands.md | 17 +- docs/tools/database.md | 7 +- docs/tools/definitions.md | 2 +- docs/tools/drivers.md | 2 +- docs/tools/events.md | 56 +++ docs/tools/history.md | 73 ++++ docs/tools/schema-switches.md | 16 +- docs/tools/settings-api.md | 5 +- src/Actions/Categories/CategoryActions.php | 2 +- src/Actions/Categories/CategoryGuard.php | 13 +- src/Actions/Categories/CreateCategory.php | 2 +- src/Actions/Categories/DeleteCategory.php | 2 +- src/Actions/Categories/MoveCategory.php | 5 +- src/Actions/Categories/RenameCategory.php | 5 +- src/Actions/ClearCache.php | 4 +- src/Actions/DiagnoseSettings.php | 6 +- src/Actions/DiffHistory.php | 84 ++++ src/Actions/FindForeignTables.php | 4 +- src/Actions/FindOrphans.php | 2 +- src/Actions/FlushScope.php | 2 +- src/Actions/ForgetSetting.php | 8 +- src/Actions/HistoryActions.php | 18 + src/Actions/LockSetting.php | 6 +- src/Actions/MakeStore.php | 2 +- src/Actions/PromoteStore.php | 4 +- src/Actions/PruneAudit.php | 10 +- src/Actions/PruneHistory.php | 71 +++ src/Actions/PruneOrphans.php | 8 +- src/Actions/QueryAudit.php | 6 +- src/Actions/QueryHistory.php | 47 ++ src/Actions/RollbackSetting.php | 70 +++ src/Actions/SetSetting.php | 10 +- src/Actions/SettingActions.php | 4 +- src/Actions/SyncDefinitions.php | 12 +- src/Actions/UnlockSetting.php | 6 +- src/Actions/WarmCache.php | 2 +- src/Actions/WriteGuard.php | 4 +- src/Audit/DatabaseAuditSink.php | 4 +- src/Categories/CategoryManager.php | 4 +- src/Console/ClearCacheCommand.php | 2 +- src/Console/HistoryCommand.php | 142 ++++++ src/Console/PruneHistoryCommand.php | 69 +++ src/Console/WarmCacheCommand.php | 2 +- src/Contracts/Settings.php | 35 +- src/Data/AlertContext.php | 85 ++++ src/Data/AlertRule.php | 142 ++++++ src/Data/HistoryDiff.php | 32 ++ src/Data/HistoryEntry.php | 77 ++++ src/Data/HistoryFilter.php | 48 +++ src/Data/HistoryPage.php | 25 ++ src/Database/SchemaNames.php | 15 +- src/Database/SchemaShape.php | 13 +- src/Definitions/DefinitionBuilder.php | 1 + src/Drivers/CachingDriver.php | 2 +- src/Drivers/DatabaseDriver.php | 14 + src/Enums/HistoryOperation.php | 33 ++ src/Events/AccessWasDenied.php | 28 ++ src/Events/AuditPruned.php | 18 + src/Events/CategoryMoved.php | 20 + src/Events/CategoryRenamed.php | 19 + src/Events/DefinitionsSynced.php | 20 + src/Events/HistoryPruned.php | 20 + src/Events/OrphansPruned.php | 18 + src/Events/SettingLocked.php | 22 + src/Events/SettingRolledBack.php | 23 + src/Events/SettingUnlocked.php | 22 + src/Events/VerificationWasRequired.php | 22 + src/Exceptions/HistoryUnavailable.php | 12 + src/Facades/Settings.php | 14 +- src/History/HistoryQuery.php | 137 ++++++ src/Listeners/LogSettingsEvent.php | 35 ++ src/Listeners/SendSettingsAlert.php | 179 ++++++++ src/Logging/OperationalLogger.php | 2 +- src/Notifications/SettingsAlert.php | 122 ++++++ src/Providers/SettingsServiceProvider.php | 131 +++++- .../Access}/AccessGuard.php | 22 +- src/{Audit => Services/Access}/Auditor.php | 4 +- .../Cache}/SettingsCache.php | 2 +- src/{ => Services}/Casting/CasterRegistry.php | 9 +- .../Configuration/RuntimeConfiguration.php | 10 +- .../Database/AuditRepository.php | 4 +- .../Database/CategoryRepository.php | 2 +- .../Database/DefinitionsRepository.php | 2 +- src/Services/Database/HistoryRepository.php | 248 +++++++++++ .../Database/SchemaInspector.php | 2 +- .../Database/SchemaShapeRepository.php | 4 +- .../Definitions/DatabaseDefinitions.php | 6 +- .../Definitions/DefinitionRegistry.php | 5 +- src/{ => Services}/Drivers/DriverFactory.php | 8 +- .../Resolution/PreloadedRecords.php | 2 +- src/{ => Services}/Resolution/Resolver.php | 7 +- src/{ => Services}/Stores/SettingWriter.php | 102 ++++- src/{ => Services}/Stores/StoreRegistry.php | 11 +- .../Tenancy/TenantDiscriminators.php | 4 +- .../Values}/ValuePipeline.php | 5 +- src/SettingsManager.php | 63 ++- src/Support/AuditedTransaction.php | 2 +- src/Support/EventSummary.php | 55 +++ src/Testing/SettingsFake.php | 19 +- src/deprecated-aliases.php | 63 +++ tests/Arch/ArchitectureTest.php | 2 +- tests/Arch/LayeringTest.php | 11 +- tests/Arch/ServicesTest.php | 155 +++++++ tests/Feature/AccessEventsTest.php | 83 ++++ tests/Feature/AlertsTest.php | 261 +++++++++++ tests/Feature/AuditAndLoggingTest.php | 2 +- tests/Feature/Database/AlertsDatabaseTest.php | 89 ++++ tests/Feature/Database/AuditTableTest.php | 2 +- .../Database/BootstrapAndPromotionTest.php | 4 +- tests/Feature/Database/CachingTest.php | 6 +- tests/Feature/Database/CategoriesTest.php | 2 +- tests/Feature/Database/CommandsTest.php | 2 +- tests/Feature/Database/DatabaseLayerTest.php | 4 +- tests/Feature/Database/DedicatedStoreTest.php | 2 +- .../Feature/Database/DefinitionsTableTest.php | 2 +- .../Feature/Database/GovernanceEventsTest.php | 59 +++ tests/Feature/Database/HandlesTest.php | 4 +- tests/Feature/Database/HistoryTest.php | 406 ++++++++++++++++++ tests/Feature/Database/MigrationTest.php | 4 +- tests/Feature/Database/OwnersTest.php | 6 + tests/Feature/Database/SchemaMatrixTest.php | 24 +- tests/Feature/Database/SchemaShapeTest.php | 2 +- tests/Feature/Database/SchemaSwitchesTest.php | 2 +- tests/Feature/Database/TenancyTest.php | 2 +- tests/Feature/Database/WriteRetryTest.php | 4 +- tests/Feature/DefinitionsTest.php | 4 +- tests/Feature/DriverContractTest.php | 2 +- tests/Feature/FakeTest.php | 2 +- tests/Feature/GuardedSettingsTest.php | 2 +- tests/Feature/OwnersTest.php | 2 +- tests/Feature/RuntimeConfigurationTest.php | 10 +- tests/Feature/SettingsCacheTest.php | 2 +- tests/Fixtures/Stubs/legacy-slack-message.php | 23 + tests/Pest.php | 2 +- tests/Unit/EventSummaryTest.php | 38 ++ tests/Unit/SupportTest.php | 2 +- tests/Unit/ValuesTest.php | 2 +- 148 files changed, 4316 insertions(+), 226 deletions(-) create mode 100644 docs/recipes/listening-to-settings-events.md create mode 100644 docs/recipes/rolling-back-a-setting.md create mode 100644 docs/tools/alerts.md create mode 100644 docs/tools/events.md create mode 100644 docs/tools/history.md create mode 100644 src/Actions/DiffHistory.php create mode 100644 src/Actions/HistoryActions.php create mode 100644 src/Actions/PruneHistory.php create mode 100644 src/Actions/QueryHistory.php create mode 100644 src/Actions/RollbackSetting.php create mode 100644 src/Console/HistoryCommand.php create mode 100644 src/Console/PruneHistoryCommand.php create mode 100644 src/Data/AlertContext.php create mode 100644 src/Data/AlertRule.php create mode 100644 src/Data/HistoryDiff.php create mode 100644 src/Data/HistoryEntry.php create mode 100644 src/Data/HistoryFilter.php create mode 100644 src/Data/HistoryPage.php create mode 100644 src/Enums/HistoryOperation.php create mode 100644 src/Events/AccessWasDenied.php create mode 100644 src/Events/AuditPruned.php create mode 100644 src/Events/CategoryMoved.php create mode 100644 src/Events/CategoryRenamed.php create mode 100644 src/Events/DefinitionsSynced.php create mode 100644 src/Events/HistoryPruned.php create mode 100644 src/Events/OrphansPruned.php create mode 100644 src/Events/SettingLocked.php create mode 100644 src/Events/SettingRolledBack.php create mode 100644 src/Events/SettingUnlocked.php create mode 100644 src/Events/VerificationWasRequired.php create mode 100644 src/Exceptions/HistoryUnavailable.php create mode 100644 src/History/HistoryQuery.php create mode 100644 src/Listeners/LogSettingsEvent.php create mode 100644 src/Listeners/SendSettingsAlert.php create mode 100644 src/Notifications/SettingsAlert.php rename src/{Authorization => Services/Access}/AccessGuard.php (87%) rename src/{Audit => Services/Access}/Auditor.php (95%) rename src/{Caching => Services/Cache}/SettingsCache.php (99%) rename src/{ => Services}/Casting/CasterRegistry.php (79%) rename src/{ => Services}/Configuration/RuntimeConfiguration.php (96%) rename src/{ => Services}/Database/AuditRepository.php (98%) rename src/{ => Services}/Database/CategoryRepository.php (99%) rename src/{ => Services}/Database/DefinitionsRepository.php (98%) create mode 100644 src/Services/Database/HistoryRepository.php rename src/{ => Services}/Database/SchemaInspector.php (97%) rename src/{ => Services}/Database/SchemaShapeRepository.php (96%) rename src/{ => Services}/Definitions/DatabaseDefinitions.php (96%) rename src/{ => Services}/Definitions/DefinitionRegistry.php (96%) rename src/{ => Services}/Drivers/DriverFactory.php (94%) rename src/{ => Services}/Resolution/PreloadedRecords.php (97%) rename src/{ => Services}/Resolution/Resolver.php (96%) rename src/{ => Services}/Stores/SettingWriter.php (70%) rename src/{ => Services}/Stores/StoreRegistry.php (96%) rename src/{ => Services}/Tenancy/TenantDiscriminators.php (95%) rename src/{Support => Services/Values}/ValuePipeline.php (90%) create mode 100644 src/Support/EventSummary.php create mode 100644 src/deprecated-aliases.php create mode 100644 tests/Arch/ServicesTest.php create mode 100644 tests/Feature/AccessEventsTest.php create mode 100644 tests/Feature/AlertsTest.php create mode 100644 tests/Feature/Database/AlertsDatabaseTest.php create mode 100644 tests/Feature/Database/GovernanceEventsTest.php create mode 100644 tests/Feature/Database/HistoryTest.php create mode 100644 tests/Fixtures/Stubs/legacy-slack-message.php create mode 100644 tests/Unit/EventSummaryTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cab254..c79d1e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Value history (design §4.3, Phase 4): a `settings_history` table, one per connection like the + audit table, created by the one migration when the new schema switch `history.enabled` is on + (the default; recorded in the schema file as `history_table`, and read as off from a file + recorded before it existed). Every set, forget, lock, unlock and rollback on a database layer + appends the payload before and after exactly as stored (encrypted values stay encrypted), the + operation, the version, the causer (the actor; `system` without one), the reason and the row's + `uid` (or id) as `setting_ref`, in the same transaction as the change, so a failed history + insert rolls the change back. A forget writes a tombstone, and a key set again continues its + version from the history. Column-mode tenancy adds a `tenant` column. New config + `tables.history`, `history.enabled`, `history.keep_days` (365) and `history.keep_versions` + (null). +- `$settings->history()` (`History\HistoryQuery`: `key()`, `for()`, `global()`, `store()`, + `locale()`, `since()`, `until()`, `versions()`, then `get()`, `cursor()` or `paginate()`), + gated by `view_history`; payloads of encrypted or sensitive settings are removed for an actor + without `view_sensitive`. `$settings->rollback($key, $toVersion)` writes an earlier value as a + new version through the normal write pipeline (gated by `rollback`, step-up verification per + `verification.abilities`, audited as `rollback`) and returns the new version. + `$settings->historyDiff($key, $from, $to)` returns a `Data\HistoryDiff`, decrypting only for an + actor holding `view_sensitive` (or a trusted call). Actions `QueryHistory`, `RollbackSetting`, + `DiffHistory`, `PruneHistory` and the bundle `HistoryActions`; `Services\Database\HistoryRepository`; + `Data\HistoryEntry`, `HistoryFilter`, `HistoryPage`, `HistoryDiff`; `Enums\HistoryOperation`; + `Exceptions\HistoryUnavailable`; `DatabaseDriver::reference()`; `SettingWriter::causedBy()` and + `rollback()`. +- `laranail::settings.history {key}` (`--store`, `--owner=alias:id`, `--locale`, + `--diff=FROM..TO`, `--rollback=`, `--reveal`, `--limit`) and `laranail::settings.prune-history` + (`--days`, `--versions`; gated by `prune`, audited). +- Events: `SettingLocked`, `SettingUnlocked`, `SettingRolledBack`, `CategoryMoved`, + `CategoryRenamed`, `DefinitionsSynced`, `AuditPruned`, `HistoryPruned`, `OrphansPruned` (all + after commit), and `AccessWasDenied` and `VerificationWasRequired`, dispatched at once by the + access guard when it refuses (the refusal throws, so its transaction rolls back). None carries + a value. +- Built-in listeners, switchable under `listeners.*`: `Listeners\SendSettingsAlert` (on, but + needs `alerts.enabled`) and `Listeners\LogSettingsEvent` (off; every event to the operational + log, refusals at `warning`). +- Alerts (`alerts.enabled`, default `false`): Laravel notifications (`Notifications\SettingsAlert`) + sent when an event matches a rule in `alerts.rules` (events, key globs, stores, + `sensitive_only`, outcomes; `notify.mail`, `notify.slack` when + laravel/slack-notification-channel is installed, `notify.database`; `queue`), throttled per + rule and key for `alerts.throttle` seconds in `alerts.cache`. An alert carries identifiers only + (`Data\AlertContext`), never a value; a test renders every channel of alerts about a seeded + secret and fails if it appears. An alert that cannot be sent is logged, never thrown. + `Data\AlertRule`, `Support\EventSummary`. +- `CategoryGuard::run()` takes an optional list of further events to dispatch after commit. - The settings cache (design phase 3, §7.5): `Drivers\CachingDriver` puts each database layer behind `Caching\SettingsCache`, which caches every scope's raw rows (a "bag", every locale, misses as empty bags) keyed by a hashed, length-prefixed tuple of connection, database, tenant, @@ -82,6 +125,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- Every service now lives under `Services\` (Phase 4 plan §1), moved verbatim: + `Services\Database\{AuditRepository, CategoryRepository, DefinitionsRepository, SchemaInspector, + SchemaShapeRepository}`, `Services\Stores\{SettingWriter, StoreRegistry}`, + `Services\Resolution\{Resolver, PreloadedRecords}`, `Services\Access\{AccessGuard, Auditor}`, + `Services\Configuration\RuntimeConfiguration`, + `Services\Definitions\{DefinitionRegistry, DatabaseDefinitions}`, + `Services\Tenancy\TenantDiscriminators`, `Services\Casting\CasterRegistry`, + `Services\Values\ValuePipeline`, `Services\Drivers\DriverFactory` and + `Services\Cache\SettingsCache`. The package's own code uses the new names. Architecture tests + keep contract implementations out of `Services\` and every `*Repository` / `*Registry` in it. +- The `Settings` contract gains `history()`, `rollback()` and `historyDiff()`. A third-party + implementation must add them (pre-1.0; `SettingsManager` and the fake implement them). +- With history on, a key set again after a forget continues its version (previously it started + again at 1), so "version N" names one value. +- The access guard dispatches `AccessWasDenied` / `VerificationWasRequired` when given a + dispatcher (the container's guard is); `PruneAudit`, `PruneOrphans` and `SyncDefinitions` + take an optional dispatcher for their new events. +- The schema-switch matrix covers `history.enabled`: 11 pairwise shapes for 217 pairs per pull + request, 2,304 shapes in the weekly full product. - The code is layered entry points → actions → services → support, held by architecture tests. Database work moved out of actions into `Database\AuditRepository` (the audit sink, query and prune), `Database\DefinitionsRepository` (definitions sync and reads) and @@ -101,6 +163,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Deprecated +- The old names of the 19 classes moved into `Services\` (listed under Changed): + `Database\AuditRepository`, `Database\CategoryRepository`, `Database\DefinitionsRepository`, + `Database\SchemaInspector`, `Database\SchemaShapeRepository`, `Stores\SettingWriter`, + `Stores\StoreRegistry`, `Resolution\Resolver`, `Resolution\PreloadedRecords`, + `Authorization\AccessGuard`, `Audit\Auditor`, `Configuration\RuntimeConfiguration`, + `Definitions\DefinitionRegistry`, `Definitions\DatabaseDefinitions`, + `Tenancy\TenantDiscriminators`, `Casting\CasterRegistry`, `Support\ValuePipeline`, + `Drivers\DriverFactory` and `Caching\SettingsCache`. Each still resolves to the moved class + through `class_alias` in `src/deprecated-aliases.php` (Composer `autoload.files`), so imports, + type declarations, container bindings and `instanceof` keep working; removed in 1.0. - `PruneOrphans::find()`: use `FindOrphans::handle()`. It forwards; removed in 1.0. - `DatabaseDefinitions::localised()`: use `Support\Translations::nullableText()`. It forwards; removed in 1.0. diff --git a/README.md b/README.md index 082cd91..bf876ba 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ The hosted docs live at 'settings_categories', 'audit' => 'settings_audit', 'definitions' => 'settings_definitions', + 'history' => 'settings_history', ], /* @@ -354,4 +355,67 @@ 'level' => env('LARANAIL_SETTINGS_LOG_LEVEL', 'info'), ], + /* + |-------------------------------------------------------------------------- + | History (§4.3) + |-------------------------------------------------------------------------- + | + | `enabled` is a schema switch: it decides whether the migration creates + | the settings_history table (one per connection, like the audit table), + | and is recorded in the schema file with the others. With it, every set, + | forget, lock, unlock and rollback appends the value before and after, as + | stored (encrypted values stay encrypted), in the same transaction as the + | change. `keep_days` / `keep_versions` are the retention prune-history + | applies; null switches that rule off. + */ + 'history' => [ + 'enabled' => env('LARANAIL_SETTINGS_HISTORY', true), + 'keep_days' => 365, + 'keep_versions' => null, + ], + + /* + |-------------------------------------------------------------------------- + | Built-in listeners + |-------------------------------------------------------------------------- + | + | `alerts`: send the alerts below (they still need alerts.enabled). + | `log`: write every settings event to the logging channel above. Off by + | default, because the audit trail already records the actions. + */ + 'listeners' => [ + 'alerts' => true, + 'log' => false, + ], + + /* + |-------------------------------------------------------------------------- + | Alerts: notifications on changes + |-------------------------------------------------------------------------- + | + | Laravel notifications sent when an event matches a rule. Alerts carry + | the store, key, scope, actor, outcome and time, never a value. Each rule: + | + | 'events' => ['SettingSaved', 'AccessWasDenied'], // short names or classes + | 'keys' => ['mail.*'], // globs; null for any + | 'stores' => ['settings'], // null for any + | 'sensitive_only' => false, // only sensitive or encrypted keys + | 'outcomes' => ['allowed'], // allowed, denied; null for any + | 'notify' => [ + | 'mail' => ['ops@example.com'], + | 'slack' => env('SETTINGS_ALERTS_SLACK_WEBHOOK'), // needs laravel/slack-notification-channel + | 'database' => ['type' => App\Models\User::class, 'id' => 1], + | ], + | 'queue' => null, // a queue name, or null to send at once + | + | `throttle`: seconds a rule stays quiet about one key after alerting + | about it (0 for never), kept in `cache` (null for the default store). + */ + 'alerts' => [ + 'enabled' => env('LARANAIL_SETTINGS_ALERTS', false), + 'cache' => null, + 'throttle' => 300, + 'rules' => [], + ], + ]; diff --git a/database/migrations/create_laranail_settings_tables.php b/database/migrations/create_laranail_settings_tables.php index a30e61b..4af0ff0 100644 --- a/database/migrations/create_laranail_settings_tables.php +++ b/database/migrations/create_laranail_settings_tables.php @@ -15,7 +15,7 @@ use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Database\StoreSchema; use Simtabi\Laranail\Settings\Enums\TranslationsMode; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /* * laranail/settings: every table the package uses, in dependency order. @@ -24,6 +24,7 @@ * 2. definitions optional (definitions.table), on the default store's connection * 3. values one table per database store * 4. audit actions and denials, never values + * 5. history every value by version (history.enabled), encrypted values still encrypted * * The shape (key type, identity mode, owner keys, dedicated stores, soft deletes, translations, * tenancy, table names, connections) comes from the recorded schema file @@ -33,7 +34,7 @@ * * `laranail::settings.make-store` copies this file for one new store by rewriting the $only line * (and, with --connection, the $pinnedConnection line): the copy creates that store's values table - * and, on a connection of its own, that connection's categories and audit tables. + * and, on a connection of its own, that connection's categories, audit and history tables. */ return new class extends Migration { @@ -71,6 +72,10 @@ public function up(): void if ($tables['shared'] && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->audit()))) { $this->createAudit($connection, $shape); } + + if ($tables['shared'] && $shape->historyTable && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->history()))) { + $this->createHistory($connection, $shape); + } } } @@ -81,6 +86,10 @@ public function down(): void foreach (array_reverse($this->plan(), true) as $connection => $tables) { $schema = Schema::connection($connection); + if ($tables['shared'] && $shape->historyTable) { + $schema->dropIfExists($shape->names->history()); + } + if ($tables['shared']) { $schema->dropIfExists($shape->names->audit()); } @@ -200,11 +209,7 @@ private function createValues(string $connection, SchemaShape $shape, StoreSchem $name = $shape->names->store($store->name, $store->table); $categories = $shape->names->categories(); $index = substr($name, 0, 40); - $binary = match (DB::connection($connection)->getDriverName()) { - 'mysql', 'mariadb' => 'utf8mb4_bin', - 'pgsql' => 'C', - default => null, - }; + $binary = $this->binaryCollation($connection); Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $categories, $index, $shape, $store): void { $collate = static fn (ColumnDefinition $column): ColumnDefinition => $binary === null ? $column : $column->collation($binary); @@ -318,6 +323,51 @@ private function createAudit(string $connection, SchemaShape $shape): void }); } + /** + * The value history (§4.3): one row per version of a setting, with the payload before and + * after exactly as the values table stores it (an encrypted value stays encrypted). Queried + * by (store, scope, key, locale), so a forget followed by a set keeps one trail; `setting_ref` + * is the row's uid (or id), kept as a string so the table never depends on `ids.type`. + * Identity columns are binary-collated like the values table's. + */ + private function createHistory(string $connection, SchemaShape $shape): void + { + $name = $shape->names->history(); + $binary = $this->binaryCollation($connection); + + Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $name, $shape): void { + $collate = static fn (ColumnDefinition $column): ColumnDefinition => $binary === null ? $column : $column->collation($binary); + + $table->char('id', 26)->primary(); + + if ($shape->tenancy === TenancyMode::Column) { + $collate($table->string('tenant', 64)->default('')); + } + + $table->string('store', 64); + $table->string('setting_ref', 36)->nullable(); + $collate($table->string('scope', 128)); + $collate($table->string('key', 191)); + $collate($table->string('locale', 16)->default('')); + $table->string('operation', 16); + $table->longText('old_value')->nullable(); + $table->longText('new_value')->nullable(); + $table->string('old_type', 64)->nullable(); + $table->string('new_type', 64)->nullable(); + $table->boolean('old_encrypted')->default(false); + $table->boolean('new_encrypted')->default(false); + $table->unsignedInteger('version'); + $table->string('causer_type', 16); + $table->string('causer_alias', 64)->nullable(); + $table->string('causer_id', 64)->nullable(); + $table->text('reason')->nullable(); + $table->timestamp('created_at'); + + $table->index([...$this->tenantColumns($shape), 'store', 'scope', 'key', 'locale', 'version'], $name . '_subject_index'); + $table->index('created_at', $name . '_created_index'); + }); + } + /** * A key column typed per `ids.type`. The primary key is an explicit command, not the fluent * ->primary(): Laravel appends fluent indexes after every other command, so PostgreSQL would @@ -354,6 +404,16 @@ private function translatable(Blueprint $table, string $column, SchemaShape $sha } } + /** The binary collation of the identity columns on this connection's driver (G-38). */ + private function binaryCollation(string $connection): ?string + { + return match (DB::connection($connection)->getDriverName()) { + 'mysql', 'mariadb' => 'utf8mb4_bin', + 'pgsql' => 'C', + default => null, + }; + } + /** The tenant column of column-mode tenancy: '' is the central (no tenant) partition. */ private function tenant(Blueprint $table, SchemaShape $shape): void { diff --git a/docs/architecture.md b/docs/architecture.md index 7b797e8..26c7942 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,9 +20,11 @@ How `laranail/settings` is shaped, and why. | Layer | Holds | Examples | |---|---|---| -| Entry points | resolve inputs and delegate; no work of their own | `SettingsManager`, `CategoryManager`, `AuditQuery`, the console commands, the facade | -| Actions (`Actions/`) | one intent each, `handle()` only, final and readonly | `SetSetting`, `PromoteStore`, `SyncDefinitions`, `FindOrphans` | -| Services | the database, the files, a body of rules | `Database\AuditRepository`, `Database\DefinitionsRepository`, `Database\SchemaInspector`, `Database\CategoryRepository`, the drivers, `Stores\SettingWriter`, `Resolution\Resolver`, `Authorization\AccessGuard`, `Tenancy\TenantDiscriminators`, `Caching\SettingsCache` | +| Entry points | resolve inputs and delegate; no work of their own | `SettingsManager`, `CategoryManager`, `AuditQuery`, `HistoryQuery`, the console commands, the facade | +| Actions (`Actions/`) | one intent each, `handle()` only, final and readonly | `SetSetting`, `RollbackSetting`, `PromoteStore`, `SyncDefinitions`, `FindOrphans` | +| Services (`Services/`) | the database, the files, a body of rules | `Services\Database\AuditRepository`, `Services\Database\HistoryRepository`, `Services\Database\CategoryRepository`, `Services\Stores\SettingWriter`, `Services\Resolution\Resolver`, `Services\Access\AccessGuard`, `Services\Tenancy\TenantDiscriminators`, `Services\Cache\SettingsCache` | +| Contract implementations | one per kind, beside its kind | the drivers, the audit sinks, the authorizers, the casters, the verifiers, the actor resolvers | +| Listeners (`Listeners/`) and notifications | react to events | `SendSettingsAlert`, `LogSettingsEvent`, `Notifications\SettingsAlert` | | Support (`Support/`) | stateless logic shared by several classes | `AuditedTransaction`, `Translations`, `Json`, `DatabaseValues`, `ConfigValues`, `ValueEncoder`, `BagCodec` | An action never builds a query or reads the schema itself; it asks a repository, so the table, @@ -32,6 +34,41 @@ audits the same way. Only entry points depend on actions. Architecture tests hol and each exemption (the guards the actions run through, the action bundles, `QueryAudit`'s three result shapes) carries its reason and fails when it is no longer needed. +## Why a Services namespace? + +The layering above names a service as a stateful collaborator that owns I/O or a body of rules, +but until 0.1 the services sat beside whatever they served: `Database\AuditRepository` next to the +schema value objects, `Stores\SettingWriter` next to `Store` and `Layer`, `Support\ValuePipeline` +among the stateless helpers it is not one of. Reading a directory did not say which kind of class +it held. Every service now lives under `Services\` (`Database`, `Stores`, `Resolution`, `Access`, +`Configuration`, `Definitions`, `Tenancy`, `Casting`, `Values`, `Drivers`, `Cache`), +and the classes left in their old directories are value objects, contract implementations and +entry points. + +Two architecture tests keep it so: nothing under `Services\` implements a plug-in contract (a +driver, sink, authorizer, caster, verifier, resolver or discriminator stays beside its kind, where +a reader looking for "the drivers" finds them), and no class named `*Repository` or `*Registry` +lives anywhere else. The 19 classes that moved keep their old names through `class_alias` in +`src/deprecated-aliases.php`, loaded by Composer, until 1.0. The aliases are declared eagerly: +PHP does not autoload a class for a type check, so a lazily declared alias would make +`function f(Stores\SettingWriter $w)` refuse the object it accepted before. A third test asserts the +alias file names exactly the moved classes. + +## Why history and audit are separate tables + +They answer different questions. The audit trail records **actions**, every allowed change and +every refusal, with who asked, through which channel and why; it never holds a value, so it can be +read by anyone allowed `view_audit` and shipped to a log. The history records **values by +version**: what a setting held before and after each change, as stored (an encrypted value stays +encrypted), so a version can be compared or returned to. One table cannot do both: values in the +audit would put secrets in front of every auditor, and refusals in the history would put entries +that changed nothing between the versions a rollback counts. + +They also keep different retention (`audit.keep_days`; `history.keep_days` and +`history.keep_versions`), and they are read with different abilities (`view_audit`; +`view_history`, plus `view_sensitive` before a protected value is decrypted). Both are written in +the change's transaction, so a failure of either rolls the change back. + ## Why build rather than adopt? No existing package combines polymorphic owners, per-store categories, multiple tables and a @@ -104,7 +141,7 @@ on SQLite, MySQL and PostgreSQL, and the full product weekly. ## Why one migration? Every table the package uses is created by one migration file, in dependency order (categories, -definitions, each store's values, audit), with a `down()` that drops them in reverse. Four +definitions, each store's values, audit, history), with a `down()` that drops them in reverse. Four migration stubs used to do this, each repeating the same connection and shape lookups, and a new store meant copying a stub. Nothing in the migration varies per application any more (the shape comes from the schema file), so it ships as a real PHP file. Its table definitions stay inline, diff --git a/docs/configuration.md b/docs/configuration.md index 89d9f04..c723c7d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -64,12 +64,22 @@ Every key in `config/laranail/settings.php`, read at `config('laranail.settings. | `cache.prefix` | `laranail-settings` | the start of every cache key | | `cache.ttl` | `3600` | seconds a cached bag is fresh (at least 1) | | `cache.stale` | `300` | seconds after `ttl` a stale bag is still answered while it is refreshed (`Cache::flexible()`); `0` for none | +| `tables.history` | `settings_history` | the history table's name (after `tables.prefix`) | +| `history.enabled` | `true` (`LARANAIL_SETTINGS_HISTORY`) | schema switch: create the history table and record every change in it | +| `history.keep_days` | `365` | how long `prune-history` keeps history entries; null for no age limit | +| `history.keep_versions` | `null` | how many versions of each setting `prune-history` keeps; null for all | +| `listeners.alerts` | `true` | register the alert listener (alerts still need `alerts.enabled`) | +| `listeners.log` | `false` | write every settings event to the logging channel | +| `alerts.enabled` | `false` (`LARANAIL_SETTINGS_ALERTS`) | send alerts | +| `alerts.cache` | `null` | the cache store holding the alert throttle; null for the default | +| `alerts.throttle` | `300` | seconds a rule stays quiet about one key after alerting; `0` for never | +| `alerts.rules` | `[]` | which events alert whom; see [Alerts](tools/alerts.md) | Store names, keys, locales and owner aliases are validated, and a misconfiguration (an unknown driver, sink, verifier, resolver, level or ability included) raises `InvalidConfiguration` naming the config path on first use. The `password_confirmation` verifier also reads Laravel's own `auth.password_timeout`. Migration-time switches (`tenancy.mode` among them) are read by `install` and `make-store` and recorded in the schema file; after that the package reads the file, and `doctor` reports configuration that differs from it. See [Schema switches](tools/schema-switches.md). -The cache is described in [Caching](tools/caching.md). Access, audit and logging are described in [Access control](tools/access-control.md) and [Audit and logging](tools/audit-and-logging.md); per-request changes in [Runtime configuration](tools/runtime-configuration.md). +History is described in [History](tools/history.md), events and the built-in listeners in [Events](tools/events.md), alerts in [Alerts](tools/alerts.md). The cache is described in [Caching](tools/caching.md). Access, audit and logging are described in [Access control](tools/access-control.md) and [Audit and logging](tools/audit-and-logging.md); per-request changes in [Runtime configuration](tools/runtime-configuration.md). ## Publishing diff --git a/docs/recipes/listening-to-settings-events.md b/docs/recipes/listening-to-settings-events.md new file mode 100644 index 0000000..b170cd7 --- /dev/null +++ b/docs/recipes/listening-to-settings-events.md @@ -0,0 +1,46 @@ +# Listen to settings events + +React to changes with your own listener, using Laravel's event dispatcher. + +## A listener + +```php +use Illuminate\Support\Facades\Event; +use Simtabi\Laranail\Settings\Events\SettingSaved; + +Event::listen(SettingSaved::class, function (SettingSaved $event): void { + if ($event->store === 'settings' && str_starts_with($event->key, 'mail.')) { + Mail::purge(); // rebuild the mailer with the new settings + } +}); +``` + +Register it in a service provider's `boot()`. A queued listener (`ShouldQueue`) is safe: events carry identifiers only, so no value reaches the jobs table. + +## Reading the new value + +Events never carry the value. Read it through the API, as the actor the listener works for: + +```php +Event::listen(SettingSaved::class, function (SettingSaved $event): void { + $value = settings()->store($event->store)->asSystem('mail listener')->get($event->key); +}); +``` + +An owner's change has a scope such as `user:42`; `Scope::fromString($event->scope)?->owner()` gives back the `OwnerRef` to pass to `for()`. + +## Watching refusals + +```php +use Simtabi\Laranail\Settings\Events\AccessWasDenied; + +Event::listen(AccessWasDenied::class, function (AccessWasDenied $event): void { + report(new RuntimeException(sprintf('Settings refused [%s] on [%s] (%s).', $event->ability->value, $event->subject->key, $event->refusal))); +}); +``` + +For notifications without code, configure [alerts](../tools/alerts.md). Every event is listed in [Events](../tools/events.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/rolling-back-a-setting.md b/docs/recipes/rolling-back-a-setting.md new file mode 100644 index 0000000..9a27c9e --- /dev/null +++ b/docs/recipes/rolling-back-a-setting.md @@ -0,0 +1,40 @@ +# Roll back a setting + +Return a setting to an earlier value with `rollback()`, after looking at its history and comparing two versions. + +## From PHP + +```php +$settings = settings()->as($admin)->because('INC-42: wrong sender'); + +// 1. Find the version to return to. +foreach ($settings->history()->key('mail.from_address')->get(10) as $entry) { + echo "{$entry->version} {$entry->operation->value} by {$entry->causerType->value} at {$entry->createdAt}\n"; +} + +// 2. Check what it held. +$diff = $settings->historyDiff('mail.from_address', 4, 6); + +// 3. Roll back: written as a new version, audited, announced with SettingRolledBack. +$version = $settings->rollback('mail.from_address', 4); +``` + +The actor needs `view_history` for steps 1 and 2 and `rollback` for step 3. `rollback` needs step-up verification by default (`verification.abilities`): confirm the password first, or use the `actor` verifier with a fresh `verifiedAt`. + +## From the console + +```bash +php artisan laranail::settings.history mail.from_address +php artisan laranail::settings.history mail.from_address --diff=4..6 +php artisan laranail::settings.history mail.from_address --rollback=4 +``` + +Add `--owner=user:42`, `--store=` or `--locale=` for another scope. The command runs as the system actor and is audited under its name. An encrypted value prints as `[protected]` unless `--reveal` is given. + +A locked setting refuses the rollback like any other write; unlock it first, or roll back as an actor holding `override_lock` on a store whose locks are overridable. + +See [History](../tools/history.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/alerts.md b/docs/tools/alerts.md new file mode 100644 index 0000000..7e8ffef --- /dev/null +++ b/docs/tools/alerts.md @@ -0,0 +1,77 @@ +# Alerts + +Laravel notifications sent when a settings event matches a rule: mail, the database channel and Slack, throttled, and never carrying a value. + +## Turning them on + +Alerts are off by default. Turn them on and add rules in `config/laranail/settings.php`: + +```php +'alerts' => [ + 'enabled' => true, + 'cache' => null, // the throttle's cache store; null for the default + 'throttle' => 300, // seconds a rule stays quiet about one key; 0 for never + 'rules' => [ + [ + 'events' => ['SettingSaved', 'SettingForgotten', 'SettingRolledBack'], + 'keys' => ['mail.*', 'billing.*'], + 'stores' => null, + 'sensitive_only' => false, + 'outcomes' => null, + 'notify' => [ + 'mail' => ['ops@example.com'], + 'slack' => env('SETTINGS_ALERTS_SLACK_WEBHOOK'), + 'database' => ['type' => App\Models\User::class, 'id' => 1], + ], + 'queue' => 'notifications', + ], + [ + 'events' => ['AccessWasDenied', 'VerificationWasRequired'], + 'outcomes' => ['denied'], + 'notify' => ['mail' => ['security@example.com']], + ], + ], +], +``` + +`listeners.alerts` (on by default) can switch the listener off without removing the rules. + +## Rules + +| Key | Meaning | +|---|---| +| `events` | event short names (`SettingSaved`) or classes; required. Any event in the [events](events.md) tables except the `-ing` ones and `LayerSkipped` | +| `keys` | globs matched against the key (`mail.*`); null for any. An event without a key never matches a rule with `keys` | +| `stores` | store names; null for any | +| `sensitive_only` | only keys whose definition is sensitive or encrypted | +| `outcomes` | `allowed` (changes) or `denied` (refusals); null for any | +| `notify.mail` | addresses, sent as an on-demand notification | +| `notify.slack` | an incoming-webhook URL; used only when `laravel/slack-notification-channel` is installed | +| `notify.database` | a model class using `Notifiable` and its key; the alert goes to its `notifications` | +| `queue` | the queue to send on; null sends at once | + +A malformed rule raises `InvalidConfiguration` naming its config path (`laranail.settings.alerts.rules.0.events`) when the first event fires. + +## What an alert says + +`Notifications\SettingsAlert` carries an `AlertContext`: the event, store, key, scope, locale, actor (`user::`, `system`), outcome, time and the event's counts. It is built from the event's identifiers, so no channel can show a setting's value; the mail ends by saying so. `toArray()` / `toDatabase()` return the context as an array. + +## Throttling + +After a rule alerts about one setting (one store, for events without a key) it stays quiet about it for `alerts.throttle` seconds, so a burst of writes sends one alert. The throttle is an atomic `add()` in the configured cache. When the cache fails, the alert is sent anyway and the failure is logged. + +## Testing + +```php +Notification::fake(); + +settings()->set('mail.host', 'smtp.example.com'); + +Notification::assertSentOnDemand(SettingsAlert::class, fn (SettingsAlert $alert) => $alert->context->key === 'mail.host'); +``` + +Rules are read when the listener is first built; listeners are registered at boot, so set `alerts.enabled` in configuration (or `.env`, `LARANAIL_SETTINGS_ALERTS`) rather than at runtime. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/commands.md b/docs/tools/commands.md index 717d02c..4f5103d 100644 --- a/docs/tools/commands.md +++ b/docs/tools/commands.md @@ -1,6 +1,6 @@ # Commands -Ten Artisan commands, all named `laranail::settings.`. +Eleven Artisan commands, all named `laranail::settings.`. ## The commands @@ -13,6 +13,8 @@ Ten Artisan commands, all named `laranail::settings.`. | `laranail::settings.sync-definitions` | copies code and config definitions into the definitions table as system rows | | `laranail::settings.prune-orphans [--dry-run]` | removes the settings of owners that no longer exist | | `laranail::settings.prune-audit [--days=]` | removes audit rows older than `audit.keep_days` | +| `laranail::settings.history {key} [--store=] [--owner=] [--locale=] [--diff=FROM..TO] [--rollback=] [--reveal] [--limit=20]` | lists a setting's versions, compares two, or rolls it back | +| `laranail::settings.prune-history [--days=] [--versions=]` | removes history entries `history.keep_days` / `history.keep_versions` no longer keep | | `laranail::settings.warm [--store=*]` | loads each cached store's global scope into the cache | | `laranail::settings.clear-cache [--store=*]` | resets the cached settings of every store, or the named ones, for every tenant | @@ -70,6 +72,19 @@ touches stored values or the application's other cache entries, and both do noth `Actions\ClearCache`, need `manage_stores` when called with an actor. See [Caching](caching.md) and [Warm the cache after a deploy](../recipes/warming-the-cache.md). +## `history` + +```bash +php artisan laranail::settings.history mail.from_address +php artisan laranail::settings.history theme --owner=user:42 --diff=3..5 +php artisan laranail::settings.history mail.from_address --rollback=3 +``` + +Without an option it lists the newest versions (operation, scope, causer, reason, time; no +values). `--diff` prints the value at two versions; an encrypted or sensitive value prints as +`[protected]` unless `--reveal` is given. `--rollback` writes the value of that version as a new +version, through the same action as `rollback()`. See [History](history.md). + ## Pruning and access Both prune commands run as the system actor and are audited (a `prune` entry recording what was diff --git a/docs/tools/database.md b/docs/tools/database.md index 93b7823..8d32c26 100644 --- a/docs/tools/database.md +++ b/docs/tools/database.md @@ -10,12 +10,13 @@ The `database` driver keeps a store's values in a table, through the query build | `settings_categories` | categories of every store on the connection | | `settings_audit` | the audit trail of every store on the connection | | `settings_definitions` | optional (`definitions.table`): definitions synced from code and edited at runtime | +| `settings_history` | `history.enabled`: every value by version, of every store on the connection; see [History](history.md) | `tables.prefix` goes in front of all of them. Every connection a store uses has its own -categories and audit tables, so a store's foreign keys and transactions never cross connections. +categories, audit and history tables, so a store's foreign keys and transactions never cross connections. One migration creates them all, in that order (`down()` in reverse): see -[Installation](../installation.md). In column-mode [tenancy](tenancy.md) the values, categories -and audit tables have a `tenant` column that leads their unique keys. +[Installation](../installation.md). In column-mode [tenancy](tenancy.md) the values, categories, +audit and history tables have a `tenant` column that leads their keys. The values table, in the default shape (polymorphic owners, identity mode `slug_uid`, bigint ids, string owner key). Every other shape is a [schema switch](schema-switches.md): `uuid` / `ulid` diff --git a/docs/tools/definitions.md b/docs/tools/definitions.md index 6cec34e..62bdeff 100644 --- a/docs/tools/definitions.md +++ b/docs/tools/definitions.md @@ -7,7 +7,7 @@ A definition says what a key is: its type, default, rules, flags and who may ove In code, from a service provider's `boot()`: ```php -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; app(DefinitionRegistry::class)->define('mail.from.address') ->ofType('string') diff --git a/docs/tools/drivers.md b/docs/tools/drivers.md index 8eae978..39bf2ca 100644 --- a/docs/tools/drivers.md +++ b/docs/tools/drivers.md @@ -43,7 +43,7 @@ A missing file is an empty layer. The file is read once per process and opcache Register a closure on the factory, in a service provider's `boot()`. Built-in names cannot be replaced, and a driver name never becomes a class or method name. ```php -use Simtabi\Laranail\Settings\Drivers\DriverFactory; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Data\LayerConfig; app(DriverFactory::class)->extend('dynamo', fn (LayerConfig $layer) => new DynamoDriver(/* ... */)); diff --git a/docs/tools/events.md b/docs/tools/events.md new file mode 100644 index 0000000..c1e19e3 --- /dev/null +++ b/docs/tools/events.md @@ -0,0 +1,56 @@ +# Events + +Twenty-four events, all `final readonly` classes in `Simtabi\Laranail\Settings\Events`, carrying identifiers and counts, never a value. + +## Changes + +| Event | Dispatched | Carries | +|---|---|---| +| `SettingSaving` / `SettingSaved` | around a set (and the write a rollback makes) | `store`, `scope`, `key`, `locale`, `version` | +| `SettingForgetting` / `SettingForgotten` | around a forget | the same; `version` is the removed one | +| `SettingLocked` / `SettingUnlocked` | after a lock or unlock | the same, with the new `version` | +| `SettingRolledBack` | after a rollback | the same, plus `toVersion` (the version returned to) and `version` (the new one) | +| `ScopeFlushing` / `ScopeFlushed` | around `flush()` | `store`, `scope` | +| `StorePromoting` / `StorePromoted` | around a promotion | counts, the archive path | +| `CategorySaving` / `CategorySaved` | around a category create, rename or move | `store`, `slug` | +| `CategoryMoved` | after a move, besides `CategorySaved` | `store`, `slug`, `parent` (null: top level) | +| `CategoryRenamed` | after a rename, besides `CategorySaved` | `store`, `slug` | +| `CategoryDeleting` / `CategoryDeleted` | around a delete | `store`, `slug` | + +## Refusals + +| Event | Dispatched | Carries | +|---|---|---| +| `AccessWasDenied` | an actor is refused an ability, or a call is refused for want of an actor | `ability`, `subject` (store, key, owner, locale, flags), `actor` (null when none), `refusal` (`access_denied`, `approval_unavailable`, `actor_required`), `reason` | +| `VerificationWasRequired` | an allowed actor still needs step-up verification | `ability`, `subject`, `actor` | + +A refusal is dispatched at once, not after commit: the refusal throws, so any transaction around the call rolls back, and a listener watching for refusals must still hear of it. The refusal is also audited and logged. + +## Maintenance + +| Event | Carries | +|---|---| +| `DefinitionsSynced` | `synced`, `removed`, `conflicts`, `skipped` | +| `AuditPruned` | `removed`, `keepDays` | +| `HistoryPruned` | `removed`, `keepDays`, `keepVersions` (null where that rule was off) | +| `OrphansPruned` | `owners`, `rows` | +| `LayerSkipped` | `store`, `layer`, `reason`, when bootstrap mode skips a database layer | + +## Delivery + +Every event that announces a change implements `ShouldDispatchAfterCommit`: inside a transaction it waits for the commit, and a rolled-back change announces nothing. Only the refusals (above) and `LayerSkipped` are dispatched at once. There are no read events; reads are the hot path. + +Because events never carry a value, a queued listener cannot write a secret into the jobs table. A listener that needs the value reads it through the settings API, as the actor it acts for. + +## Built-in listeners + +| Key | Listener | Default | +|---|---|---| +| `listeners.alerts` | `Listeners\SendSettingsAlert`: [alerts](alerts.md) | on, but alerts need `alerts.enabled` | +| `listeners.log` | `Listeners\LogSettingsEvent`: every event to the [operational log](audit-and-logging.md), refusals at `warning` | off (the audit already records the actions) | + +Both are registered by class at boot, so nothing is built until an event fires. The cache needs no listener: writes invalidate it themselves. To add your own, see [Listen to settings events](../recipes/listening-to-settings-events.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/history.md b/docs/tools/history.md new file mode 100644 index 0000000..9825616 --- /dev/null +++ b/docs/tools/history.md @@ -0,0 +1,73 @@ +# History + +Every change to a setting on a database layer appends one history entry: the value before and after, as stored, in the same transaction as the change. + +## What is recorded + +`set`, `forget`, `lock`, `unlock` and `rollback` each append an entry to `settings_history` (one table per connection, like the audit table). An entry holds: + +| Field | Meaning | +|---|---| +| `store`, `scope`, `key`, `locale` | which setting; the history is always looked up by these four | +| `setting_ref` | the row's `uid` (or its id where the identity mode has no uid), as a string | +| `operation` | `set`, `forget`, `lock`, `unlock` or `rollback` | +| `old_value`, `new_value` | the payloads exactly as the values table stored them: encoded JSON, and still encrypted for an encrypted setting | +| `old_type`, `new_type`, `old_encrypted`, `new_encrypted` | what is needed to read the payloads back | +| `version` | the row's version after the change; for `forget`, the version that was removed | +| `causer_type`, `causer_alias`, `causer_id`, `reason` | the actor (`system` when there was none) and the reason given with `because()` | +| `created_at` | from `now()` | + +A failed history insert rolls the change back with it, so the history never misses a change. + +A `forget` writes a tombstone (no new value). Setting the key again continues its version from the history, so "version 3" always means one value: `set:1`, `forget:1`, `set:2`. `flush()` and promotion are audited but write no history entries. History is not written for file layers, or when the schema was recorded with `history.enabled` off. + +## Reading the history + +```php +$entries = $settings->as($admin)->history() + ->key('mail.from_address') + ->global() // or ->for($user); a handle's own owner is applied already + ->since(now()->subMonth()) + ->versions(3, 8) // inclusive; either end may be null + ->get(); // list, newest version first + +$page = $settings->history()->key('mail.from_address')->paginate(50); +$next = $settings->history()->key('mail.from_address')->paginate(50, $page->nextCursor); +``` + +`history()` starts from the handle's store, owner and locale. It needs `view_history` when the handle carries an actor. For an actor without `view_sensitive`, entries of encrypted or sensitive settings come back with their payloads removed (`HistoryEntry::redacted()`); `HistoryEntry::toArray()` never includes an encrypted payload. + +## Comparing two versions + +```php +$diff = $settings->as($admin)->historyDiff('mail.password', 3, 5); + +$diff->from; // the value at version 3, or null +$diff->to; // the value at version 5, or null +$diff->changed; // whether the stored payloads differ +$diff->redacted; // true: the actor may not view this value, so from and to are null +``` + +`historyDiff()` needs `view_history`. It decrypts an encrypted or sensitive value only for an actor holding `view_sensitive`, or for a trusted call without an actor (which reads every value, as `get()` does). Nothing is decrypted before that decision. A version that is not in the history raises `HistoryUnavailable`. + +## Rolling back + +```php +$version = $settings->as($admin)->because('INC-42')->rollback('mail.from_address', 3); +``` + +The value of version 3 is read back from the history, decrypted and decoded, then written as a new version through the normal write pipeline: validation, casting, encryption, lock rules, the version check against the current row, history and audit. It needs `rollback`, which `verification.abilities` lists by default, so step-up verification applies. It returns the new version and dispatches `SettingRolledBack`. See [Roll back a setting](../recipes/rolling-back-a-setting.md). + +## Retention + +`history.keep_days` drops entries older than that many days; `history.keep_versions` keeps only that many versions of each setting. Either may be null; `laranail::settings.prune-history` applies them (needs `prune`, audited, dispatches `HistoryPruned`). Retention covers every tenant. + +## Switching it off + +`history.enabled` is a [schema switch](schema-switches.md): it decides whether the migration creates the table, and the package reads the recorded value, not live configuration. With it off, `history()`, `rollback()` and `historyDiff()` raise `HistoryUnavailable`, and a key set again after a forget starts at version 1. + +`reencrypt` (rewriting payloads after a key rotation, history included) is not part of this release. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/schema-switches.md b/docs/tools/schema-switches.md index fd92367..c5e6f13 100644 --- a/docs/tools/schema-switches.md +++ b/docs/tools/schema-switches.md @@ -1,6 +1,6 @@ # Schema switches -Seven schema switches choose the shape of the package's tables at migration time; the defaults are the recommended shape, and the package then reads the recorded shape, never live configuration. +Eight schema switches choose the shape of the package's tables at migration time; the defaults are the recommended shape, and the package then reads the recorded shape, never live configuration. ## The switches @@ -13,10 +13,11 @@ Seven schema switches choose the shape of the package's tables at migration time | `stores..soft_deletes` | `false`, `true` | forgotten rows are trashed, and restored by the next write | | `translations.mode` | `lang`, `json` | titles, labels and descriptions as text, or as per-locale JSON maps | | `definitions.table` | `false`, `true` | creates the optional `settings_definitions` table | +| `history.enabled` | `true`, `false` | creates `settings_history` and records every change in it ([History](history.md)) | `categories.soft_deletes` (default `false`) gives categories the same trash-and-restore rule. `tables.prefix` and the table names (`tables.categories`, `tables.audit`, `tables.definitions`, -`stores..table`) are recorded with the switches and honoured everywhere, including the +`tables.history`, `stores..table`) are recorded with the switches and honoured everywhere, including the check that refuses to install over a table that is not the package's. ## Identity modes @@ -118,11 +119,12 @@ type fails). A database store with no entry in the file fails. ## Keeping the switches tested `tests/Feature/Database/SchemaMatrixTest.php` builds a pairwise set of shapes (every pair of -switch values meets in at least one; 10 shapes covering all 177 pairs of the nine switches, -`tenancy.mode` none and column included, both counts asserted) and runs each end to end, inside a -tenant in column mode, finishing with `doctor`. It runs on SQLite with the suite and on MySQL and -PostgreSQL in the `database` group; `LARANAIL_SETTINGS_MATRIX=full` runs all 1,152 shapes, which -the weekly CI job does. (`database` mode adds no column, so it is not a separate shape.) +switch values meets in at least one; 11 shapes covering all 217 pairs of the ten switches, +`tenancy.mode` none and column and `history.enabled` on and off included, both counts asserted) +and runs each end to end, inside a tenant in column mode, reading the history where it is on, and +finishing with `doctor`. It runs on SQLite with the suite and on MySQL and PostgreSQL in the +`database` group; `LARANAIL_SETTINGS_MATRIX=full` runs all 2,304 shapes, which the weekly CI job +does. A schema file recorded before `history.enabled` existed reads as history off. (`database` mode adds no column, so it is not a separate shape.) --- diff --git a/docs/tools/settings-api.md b/docs/tools/settings-api.md index df0fe2c..7258515 100644 --- a/docs/tools/settings-api.md +++ b/docs/tools/settings-api.md @@ -59,8 +59,11 @@ A stored `null` is an answer: `has()` is true and `get()` returns `null`, not th | `promote(?PromotionRequest)` | moves runtime-file values into the database; returns a `PromotionReport` | | `clearCache()` | resets the cached values of the handle's owner, or of its whole store; see [Caching](caching.md) | | `warmCache()` | loads the handle's scope (owner or global) into the cache now; returns the record count | +| `history()` | the value history of the handle's store, owner and locale (needs `view_history`); see [History](history.md) | +| `rollback($key, $toVersion)` | writes the value of an earlier version as a new version (needs `rollback`); returns the new version | +| `historyDiff($key, $from, $to)` | the value at two versions, decrypted only for an actor holding `view_sensitive` | -Writes raise `UnknownSetting` (strict store, no definition), `OwnerNotAllowed`, `LockedSetting`, `InvalidSettingValue`, `EncryptionUnavailable` or `StoreNotWritable`. A handle with an actor can also raise `AccessDenied` or `VerificationRequired`, any handle `ActorRequired` (when an actor is required) and `ApprovalUnavailable`. Every exception extends `SettingsException`. +Writes raise `UnknownSetting` (strict store, no definition), `OwnerNotAllowed`, `LockedSetting`, `InvalidSettingValue`, `EncryptionUnavailable` or `StoreNotWritable`. A handle with an actor can also raise `AccessDenied` or `VerificationRequired`, any handle `ActorRequired` (when an actor is required) and `ApprovalUnavailable`. `history()`, `rollback()` and `historyDiff()` raise `HistoryUnavailable` for a store that keeps no history or a version it does not hold. Every exception extends `SettingsException`. Each write is one action in `Simtabi\Laranail\Settings\Actions` (`SetSetting`, `ForgetSetting`, `LockSetting`, `UnlockSetting`), taking a DTO and the actor. The handle delegates to them, and later channels (console, REST) will too, so behaviour cannot differ between them. diff --git a/src/Actions/Categories/CategoryActions.php b/src/Actions/Categories/CategoryActions.php index 0498a10..9e4f05f 100644 --- a/src/Actions/Categories/CategoryActions.php +++ b/src/Actions/Categories/CategoryActions.php @@ -5,7 +5,7 @@ namespace Simtabi\Laranail\Settings\Actions\Categories; use Illuminate\Contracts\Events\Dispatcher; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; /** * The category actions, held together so a handle is built from one collaborator. diff --git a/src/Actions/Categories/CategoryGuard.php b/src/Actions/Categories/CategoryGuard.php index e05775e..9b2e6af 100644 --- a/src/Actions/Categories/CategoryGuard.php +++ b/src/Actions/Categories/CategoryGuard.php @@ -13,10 +13,10 @@ use Simtabi\Laranail\Settings\Data\CategorySlug; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Support\AuditedTransaction; -use Simtabi\Laranail\Settings\Database\CategoryRepository; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * What every category change does around its work: authorize `manage_categories`, then run the @@ -35,10 +35,11 @@ public function __construct( * @template T * * @param Closure(CategoryRepository, DatabaseDriver): T $work + * @param list $also more events dispatched after `$after` (what exactly changed) * * @return T */ - public function run(Store $store, CategorySlug $slug, ?Actor $actor, string $operation, object $before, object $after, Closure $work): mixed + public function run(Store $store, CategorySlug $slug, ?Actor $actor, string $operation, object $before, object $after, Closure $work, array $also = []): mixed { $subject = new Subject($store->name, category: $slug->value); $meta = ['operation' => $operation, 'category' => $slug->value]; @@ -57,8 +58,12 @@ function () use ($store, $database, $work, $before): mixed { return $work(new CategoryRepository($database, $store->name), $database); }, - then: function () use ($after): void { + then: function () use ($after, $also): void { $this->events->dispatch($after); + + foreach ($also as $event) { + $this->events->dispatch($event); + } }, meta: $meta, ); diff --git a/src/Actions/Categories/CreateCategory.php b/src/Actions/Categories/CreateCategory.php index 2ff2e8b..c17a7cf 100644 --- a/src/Actions/Categories/CreateCategory.php +++ b/src/Actions/Categories/CreateCategory.php @@ -10,7 +10,7 @@ use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Events\CategorySaved; use Simtabi\Laranail\Settings\Events\CategorySaving; -use Simtabi\Laranail\Settings\Database\CategoryRepository; +use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * Create a category in a store, optionally under a parent of the same store: needs diff --git a/src/Actions/Categories/DeleteCategory.php b/src/Actions/Categories/DeleteCategory.php index d3e90e6..ae23fea 100644 --- a/src/Actions/Categories/DeleteCategory.php +++ b/src/Actions/Categories/DeleteCategory.php @@ -10,7 +10,7 @@ use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Events\CategoryDeleted; use Simtabi\Laranail\Settings\Events\CategoryDeleting; -use Simtabi\Laranail\Settings\Database\CategoryRepository; +use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * Delete a category: needs `manage_categories`. Its children move to the top level and the diff --git a/src/Actions/Categories/MoveCategory.php b/src/Actions/Categories/MoveCategory.php index 36020d3..e8cff83 100644 --- a/src/Actions/Categories/MoveCategory.php +++ b/src/Actions/Categories/MoveCategory.php @@ -7,11 +7,12 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\CategorySlug; +use Simtabi\Laranail\Settings\Events\CategoryMoved; use Simtabi\Laranail\Settings\Events\CategorySaved; use Simtabi\Laranail\Settings\Events\CategorySaving; use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; -use Simtabi\Laranail\Settings\Database\CategoryRepository; use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; +use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * Put a category under another of the same store, or at the top level with a null parent: @@ -32,6 +33,6 @@ public function handle(Store $store, string $slug, ?string $parent, ?Actor $acto $this->guard->run($store, $category, $actor, 'move', $events[0], $events[1], static function (CategoryRepository $categories) use ($category, $under): void { $categories->move($category, $under); - }); + }, [new CategoryMoved($store->name->value, $slug, $parent)]); } } diff --git a/src/Actions/Categories/RenameCategory.php b/src/Actions/Categories/RenameCategory.php index 812e99e..36b430a 100644 --- a/src/Actions/Categories/RenameCategory.php +++ b/src/Actions/Categories/RenameCategory.php @@ -9,7 +9,8 @@ use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Events\CategorySaved; use Simtabi\Laranail\Settings\Events\CategorySaving; -use Simtabi\Laranail\Settings\Database\CategoryRepository; +use Simtabi\Laranail\Settings\Events\CategoryRenamed; +use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * Give a category a new title (its slug, the identifier, stays): needs `manage_categories`. @@ -28,6 +29,6 @@ public function handle(Store $store, string $slug, string $title, ?Actor $actor $this->guard->run($store, $input->slug, $actor, 'rename', $events[0], $events[1], static function (CategoryRepository $categories) use ($input): void { $categories->rename($input->slug, $input->title); - }); + }, [new CategoryRenamed($store->name->value, $slug)]); } } diff --git a/src/Actions/ClearCache.php b/src/Actions/ClearCache.php index 4e438c7..e4cde60 100644 --- a/src/Actions/ClearCache.php +++ b/src/Actions/ClearCache.php @@ -12,8 +12,8 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Caching\SettingsCache; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; /** * Reset cached settings (design §7.5, `laranail::settings.clear-cache`): every bag, one store's, diff --git a/src/Actions/DiagnoseSettings.php b/src/Actions/DiagnoseSettings.php index 626066e..d0b4d4e 100644 --- a/src/Actions/DiagnoseSettings.php +++ b/src/Actions/DiagnoseSettings.php @@ -9,13 +9,13 @@ use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Diagnostics\Finding; use Simtabi\Laranail\Settings\Database\SchemaShape; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; -use Simtabi\Laranail\Settings\Database\SchemaInspector; use Simtabi\Laranail\Settings\Exceptions\SettingsException; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Package\Tools\Services\Doctor\DoctorResult; +use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /** * What `laranail::settings.doctor` reports, per store with a database layer: readiness (the diff --git a/src/Actions/DiffHistory.php b/src/Actions/DiffHistory.php new file mode 100644 index 0000000..7e324d2 --- /dev/null +++ b/src/Actions/DiffHistory.php @@ -0,0 +1,84 @@ +subject(); + $this->access->authorize($actor, Ability::ViewHistory, $subject); + + $store = $target->store; + $scope = $subject->scope(); + $database = $store->database(); + $history = $database instanceof DatabaseDriver && $database->shape()->historyTable ? new HistoryRepository($database) : null; + + if (! $history instanceof HistoryRepository) { + throw new HistoryUnavailable(sprintf('Store [%s] keeps no history.', $store->name)); + } + + $entries = []; + + foreach ([$from, $to] as $version) { + $entries[] = $history->find($store->name, $scope, $target->key, $target->locale, $version) + ?? throw new HistoryUnavailable(sprintf('Setting [%s] in store [%s] for scope [%s] has no version %d in its history.', $target->key, $store->name, $scope, $version)); + } + + [$older, $newer] = $entries; + $protected = $subject->sensitive || $older->newEncrypted || $newer->newEncrypted; + $redacted = $protected && $actor instanceof Actor && ! $this->access->allows($actor, Ability::ViewSensitive, $subject); + + return new HistoryDiff( + store: $store->name->value, + scope: $scope->value, + key: $target->key->value, + locale: $target->locale->value, + fromVersion: $from, + toVersion: $to, + from: $redacted ? null : $this->value($older, $target), + to: $redacted ? null : $this->value($newer, $target), + fromFound: $older->newValue !== null, + toFound: $newer->newValue !== null, + changed: $older->newValue !== $newer->newValue || $older->newType !== $newer->newType, + redacted: $redacted, + encrypted: $protected, + ); + } + + private function value(HistoryEntry $entry, SettingTarget $target): mixed + { + if ($entry->newValue === null) { + return null; + } + + return $this->pipeline->fromRecord(new Record($target->subject()->scope(), $target->key, $target->locale, $entry->newValue, $entry->newType, $entry->newEncrypted), $target->definition); + } +} diff --git a/src/Actions/FindForeignTables.php b/src/Actions/FindForeignTables.php index 1b26612..18748ff 100644 --- a/src/Actions/FindForeignTables.php +++ b/src/Actions/FindForeignTables.php @@ -4,9 +4,9 @@ namespace Simtabi\Laranail\Settings\Actions; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; -use Simtabi\Laranail\Settings\Database\SchemaInspector; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; /** * The tables `install` would create that already exist and are not this package's (D-4). A bare diff --git a/src/Actions/FindOrphans.php b/src/Actions/FindOrphans.php index 070c5ad..fea9ab7 100644 --- a/src/Actions/FindOrphans.php +++ b/src/Actions/FindOrphans.php @@ -8,8 +8,8 @@ use Illuminate\Database\Eloquent\Model; use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\OwnerRef; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; /** * Find the settings of owners that no longer exist (G-7): rows left by bulk deletes, which fire diff --git a/src/Actions/FlushScope.php b/src/Actions/FlushScope.php index 632a7dd..67b22ca 100644 --- a/src/Actions/FlushScope.php +++ b/src/Actions/FlushScope.php @@ -17,7 +17,7 @@ use Simtabi\Laranail\Settings\Events\ScopeFlushed; use Simtabi\Laranail\Settings\Events\ScopeFlushing; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; /** * Remove every value an owner holds in a store, from every writable layer: needs `forget`. Used diff --git a/src/Actions/ForgetSetting.php b/src/Actions/ForgetSetting.php index 305acee..e86284c 100644 --- a/src/Actions/ForgetSetting.php +++ b/src/Actions/ForgetSetting.php @@ -7,7 +7,7 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\SettingTarget; -use Simtabi\Laranail\Settings\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; /** * Remove a scope's own value so reads fall through again: needs `forget` (and `override_lock` @@ -22,10 +22,10 @@ public function __construct( public function handle(SettingTarget $target, ?Actor $actor = null): void { - $this->guard->run(Ability::Forget, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target): array { + $this->guard->run(Ability::Forget, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target, $actor): array { $removed = $override - ? $this->writer->forgetOverridingLock($target->store, $target->key, $target->locale, $target->owner, $target->definition) - : $this->writer->forget($target->store, $target->key, $target->locale, $target->owner, $target->definition); + ? $this->writer->causedBy($actor, $target->reason)->forgetOverridingLock($target->store, $target->key, $target->locale, $target->owner, $target->definition) + : $this->writer->causedBy($actor, $target->reason)->forget($target->store, $target->key, $target->locale, $target->owner, $target->definition); return [$removed?->version, null]; }); diff --git a/src/Actions/HistoryActions.php b/src/Actions/HistoryActions.php new file mode 100644 index 0000000..0e430ad --- /dev/null +++ b/src/Actions/HistoryActions.php @@ -0,0 +1,18 @@ +guard->run(Ability::Lock, $target, $actor, respectsLocks: false, write: function () use ($target): array { - $after = $this->writer->lock($target->store, $target->key, $target->locale, $target->owner, $target->definition); + $this->guard->run(Ability::Lock, $target, $actor, respectsLocks: false, write: function () use ($target, $actor): array { + $after = $this->writer->causedBy($actor, $target->reason)->lock($target->store, $target->key, $target->locale, $target->owner, $target->definition); return [$after->version > 1 ? $after->version - 1 : null, $after->version]; }); diff --git a/src/Actions/MakeStore.php b/src/Actions/MakeStore.php index ed2b6c3..4e37fdc 100644 --- a/src/Actions/MakeStore.php +++ b/src/Actions/MakeStore.php @@ -10,8 +10,8 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\GeneratedStore; use Simtabi\Laranail\Settings\Database\StoreSchema; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /** * Generate a new database store (G-3: no runtime DDL): one migration for it, a copy of the diff --git a/src/Actions/PromoteStore.php b/src/Actions/PromoteStore.php index 129b68c..e9afc5c 100644 --- a/src/Actions/PromoteStore.php +++ b/src/Actions/PromoteStore.php @@ -23,12 +23,12 @@ use Simtabi\Laranail\Settings\Events\StorePromoted; use Simtabi\Laranail\Settings\Data\PromotionRequest; use Simtabi\Laranail\Settings\Events\StorePromoting; -use Simtabi\Laranail\Settings\Support\ValuePipeline; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\PromotionLocked; use Simtabi\Laranail\Settings\Support\AuditedTransaction; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; /** * Promote a store's runtime file into its database layer (design §7.4): needs `promote`. diff --git a/src/Actions/PruneAudit.php b/src/Actions/PruneAudit.php index 9504495..5a64b29 100644 --- a/src/Actions/PruneAudit.php +++ b/src/Actions/PruneAudit.php @@ -6,15 +6,17 @@ use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Data\Actor; +use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Events\AuditPruned; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Database\AuditRepository; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Database\AuditRepository; /** * Delete audit rows older than `audit.keep_days` from the audit table of every connection a @@ -29,6 +31,7 @@ public function __construct( private StoreRegistry $stores, ?AccessGuard $access = null, + private ?Dispatcher $events = null, ) { $this->access = $access ?? AccessGuard::closed(); } @@ -59,6 +62,7 @@ public function handle(int $keepDays, ?Actor $actor = null): int } $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'audit', 'keep_days' => $keepDays, 'removed' => $removed]); + $this->events?->dispatch(new AuditPruned($removed, $keepDays)); return $removed; } diff --git a/src/Actions/PruneHistory.php b/src/Actions/PruneHistory.php new file mode 100644 index 0000000..437136f --- /dev/null +++ b/src/Actions/PruneHistory.php @@ -0,0 +1,71 @@ + $keepDays, 'keep_versions' => $keepVersions] as $name => $value) { + if ($value !== null && $value < 1) { + throw new InvalidConfiguration(sprintf('laranail.settings.history.%s: [%d] must be at least 1.', $name, $value)); + } + } + + $subject = new Subject($this->stores->default()->name); + $this->access->authorize($actor, Ability::Prune, $subject); + + $cutoff = $keepDays === null ? null : CarbonImmutable::now()->subDays($keepDays); + $removed = 0; + $seen = []; + + foreach ($this->stores->all() as $store) { + $database = $store->database(); + + if (! $database instanceof DatabaseDriver || ! $database->shape()->historyTable || isset($seen[$database->connectionName()])) { + continue; + } + + $seen[$database->connectionName()] = true; + $removed += new HistoryRepository($database)->prune($cutoff, $keepVersions, $store->name); + } + + $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'history', 'keep_days' => $keepDays, 'keep_versions' => $keepVersions, 'removed' => $removed]); + $this->events->dispatch(new HistoryPruned($removed, $keepDays, $keepVersions)); + + return $removed; + } +} diff --git a/src/Actions/PruneOrphans.php b/src/Actions/PruneOrphans.php index fbc85ea..b6e1413 100644 --- a/src/Actions/PruneOrphans.php +++ b/src/Actions/PruneOrphans.php @@ -6,13 +6,15 @@ use Closure; use Simtabi\Laranail\Settings\Data\Actor; +use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Events\OrphansPruned; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; /** * Remove the settings of owners that no longer exist (G-7), as {@see FindOrphans} finds them. @@ -30,6 +32,7 @@ public function __construct( private FlushScope $flush, private Closure $models, ?AccessGuard $access = null, + private ?Dispatcher $events = null, ) { $this->access = $access ?? AccessGuard::closed(); } @@ -66,6 +69,7 @@ public function handle(?Actor $actor = null): int } $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'orphans', 'owners' => $flushed, 'removed' => $removed]); + $this->events?->dispatch(new OrphansPruned($flushed, $removed)); return $removed; } diff --git a/src/Actions/QueryAudit.php b/src/Actions/QueryAudit.php index b311e49..d5a263e 100644 --- a/src/Actions/QueryAudit.php +++ b/src/Actions/QueryAudit.php @@ -14,10 +14,10 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Data\AuditFilter; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Database\AuditRepository; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\DriverUnavailable; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Database\AuditRepository; /** * Read the audit trail (§16.8): needs `view_audit` when an actor is present (a trusted call diff --git a/src/Actions/QueryHistory.php b/src/Actions/QueryHistory.php new file mode 100644 index 0000000..f0c2297 --- /dev/null +++ b/src/Actions/QueryHistory.php @@ -0,0 +1,47 @@ +store instanceof StoreName ? $this->stores->get($filter->store) : $this->stores->default(); + + $this->access->authorize($actor, Ability::ViewHistory, new Subject( + $store->name, + key: $filter->key, + owner: $filter->scope?->owner(), + )); + + $history = HistoryRepository::locate($this->stores, $store->name) + ?? throw new HistoryUnavailable(sprintf('Store [%s] keeps no history: it has no active database layer, or its schema was recorded without the history table.', $store->name)); + + return $history->query($filter->with(store: $store->name)); + } +} diff --git a/src/Actions/RollbackSetting.php b/src/Actions/RollbackSetting.php new file mode 100644 index 0000000..7025ff2 --- /dev/null +++ b/src/Actions/RollbackSetting.php @@ -0,0 +1,70 @@ +guard->run(Ability::Rollback, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target, $toVersion, $actor, &$version): array { + $store = $target->store; + $scope = $target->subject()->scope(); + $database = $store->database(); + $history = $database instanceof DatabaseDriver && $database->shape()->historyTable ? new HistoryRepository($database) : null; + + if (! $history instanceof HistoryRepository) { + throw new HistoryUnavailable(sprintf('Store [%s] keeps no history, so [%s] cannot be rolled back.', $store->name, $target->key)); + } + + $entry = $history->find($store->name, $scope, $target->key, $target->locale, $toVersion); + + if (! $entry instanceof HistoryEntry || $entry->newValue === null) { + throw new HistoryUnavailable(sprintf('Setting [%s] in store [%s] for scope [%s] has no value at version %d in its history.', $target->key, $store->name, $scope, $toVersion)); + } + + $value = $this->pipeline->fromRecord(new Record($scope, $target->key, $target->locale, $entry->newValue, $entry->newType, $entry->newEncrypted), $target->definition); + $current = $store->writableLayer()->driver->load($store->name, [$scope])->find($scope, $target->key, $target->locale)->version ?? 0; + + $after = $this->writer->causedBy($actor, $target->reason)->rollback($store, $target->key, $target->locale, $target->owner, $target->definition, $value, $current, $override); + $version = $after->version; + $this->events->dispatch(new SettingRolledBack($store->name->value, $scope->value, $target->key->value, $target->locale->value, $toVersion, $after->version)); + + return [$current > 0 ? $current : null, $after->version]; + }); + + return $version; + } +} diff --git a/src/Actions/SetSetting.php b/src/Actions/SetSetting.php index 3cbe720..6e68401 100644 --- a/src/Actions/SetSetting.php +++ b/src/Actions/SetSetting.php @@ -7,7 +7,7 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\SettingWrite; -use Simtabi\Laranail\Settings\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; /** * Store a value: needs `update` (and `override_lock` over a locked row the store lets be @@ -25,11 +25,11 @@ public function handle(SettingWrite $write, ?Actor $actor = null): void { $target = $write->target; - $this->guard->run(Ability::Update, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target, $write): array { + $this->guard->run(Ability::Update, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target, $write, $actor): array { $after = match (true) { - $write->expectedVersion !== null => $this->writer->setExpecting($target->store, $target->key, $target->locale, $target->owner, $target->definition, $write->value, $write->expectedVersion, $override), - $override => $this->writer->setOverridingLock($target->store, $target->key, $target->locale, $target->owner, $target->definition, $write->value), - default => $this->writer->set($target->store, $target->key, $target->locale, $target->owner, $target->definition, $write->value), + $write->expectedVersion !== null => $this->writer->causedBy($actor, $target->reason)->setExpecting($target->store, $target->key, $target->locale, $target->owner, $target->definition, $write->value, $write->expectedVersion, $override), + $override => $this->writer->causedBy($actor, $target->reason)->setOverridingLock($target->store, $target->key, $target->locale, $target->owner, $target->definition, $write->value), + default => $this->writer->causedBy($actor, $target->reason)->set($target->store, $target->key, $target->locale, $target->owner, $target->definition, $write->value), }; return [$after->version > 1 ? $after->version - 1 : null, $after->version]; diff --git a/src/Actions/SettingActions.php b/src/Actions/SettingActions.php index c2c62de..b41010b 100644 --- a/src/Actions/SettingActions.php +++ b/src/Actions/SettingActions.php @@ -4,8 +4,8 @@ namespace Simtabi\Laranail\Settings\Actions; -use Simtabi\Laranail\Settings\Stores\SettingWriter; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; /** * The write actions a settings handle delegates to, held together so a handle is built from diff --git a/src/Actions/SyncDefinitions.php b/src/Actions/SyncDefinitions.php index ade2de7..90167ef 100644 --- a/src/Actions/SyncDefinitions.php +++ b/src/Actions/SyncDefinitions.php @@ -5,16 +5,18 @@ namespace Simtabi\Laranail\Settings\Actions; use Simtabi\Laranail\Settings\Data\Actor; +use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; -use Simtabi\Laranail\Settings\Database\DefinitionsRepository; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Events\DefinitionsSynced; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Database\DefinitionsRepository; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** * Copy every code and config definition into the definitions table as an `is_system` row (D-6, @@ -33,6 +35,7 @@ public function __construct( private DefinitionRegistry $definitions, private ValueEncoder $encoder, private AccessGuard $access, + private ?Dispatcher $events = null, ) {} /** @return SyncReport */ @@ -70,6 +73,7 @@ public function handle(?Actor $actor = null): array 'removed' => $report['removed'], 'conflicts' => count($report['conflicts']), ]); + $this->events?->dispatch(new DefinitionsSynced($report['synced'], $report['removed'], count($report['conflicts']), count($report['skipped']))); return $report; } diff --git a/src/Actions/UnlockSetting.php b/src/Actions/UnlockSetting.php index 8bbc0fe..61734ba 100644 --- a/src/Actions/UnlockSetting.php +++ b/src/Actions/UnlockSetting.php @@ -7,7 +7,7 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\SettingTarget; -use Simtabi\Laranail\Settings\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; /** * Unlock one scope's row against writes: needs `unlock`. @@ -21,8 +21,8 @@ public function __construct( public function handle(SettingTarget $target, ?Actor $actor = null): void { - $this->guard->run(Ability::Unlock, $target, $actor, respectsLocks: false, write: function () use ($target): array { - $after = $this->writer->unlock($target->store, $target->key, $target->locale, $target->owner, $target->definition); + $this->guard->run(Ability::Unlock, $target, $actor, respectsLocks: false, write: function () use ($target, $actor): array { + $after = $this->writer->causedBy($actor, $target->reason)->unlock($target->store, $target->key, $target->locale, $target->owner, $target->definition); return [$after->version > 1 ? $after->version - 1 : null, $after->version]; }); diff --git a/src/Actions/WarmCache.php b/src/Actions/WarmCache.php index 7d68559..fe1328f 100644 --- a/src/Actions/WarmCache.php +++ b/src/Actions/WarmCache.php @@ -12,7 +12,7 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; /** * Load one scope's bag into the cache ahead of the first read (design §7.5, diff --git a/src/Actions/WriteGuard.php b/src/Actions/WriteGuard.php index 3c9beda..656810a 100644 --- a/src/Actions/WriteGuard.php +++ b/src/Actions/WriteGuard.php @@ -10,9 +10,9 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Data\SettingTarget; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Stores\SettingWriter; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Support\AuditedTransaction; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; /** diff --git a/src/Audit/DatabaseAuditSink.php b/src/Audit/DatabaseAuditSink.php index f62f0da..0625dee 100644 --- a/src/Audit/DatabaseAuditSink.php +++ b/src/Audit/DatabaseAuditSink.php @@ -8,9 +8,9 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Contracts\AuditSink; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Database\AuditRepository; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Database\AuditRepository; /** * Writes each audit entry as a row of `settings_audit` on the connection of the entry's store diff --git a/src/Categories/CategoryManager.php b/src/Categories/CategoryManager.php index 981ba3d..e50f4de 100644 --- a/src/Categories/CategoryManager.php +++ b/src/Categories/CategoryManager.php @@ -12,11 +12,11 @@ use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Data\CategorySlug; use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; -use Simtabi\Laranail\Settings\Database\CategoryRepository; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; use Simtabi\Laranail\Settings\Actions\Categories\CategoryActions; +use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** * The categories of one store, for the actor of the handle that returned it diff --git a/src/Console/ClearCacheCommand.php b/src/Console/ClearCacheCommand.php index 2702bae..2a4f2e2 100644 --- a/src/Console/ClearCacheCommand.php +++ b/src/Console/ClearCacheCommand.php @@ -7,9 +7,9 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Actions\ClearCache; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Console\Tools\Commands\Command; use Simtabi\Laranail\Settings\Exceptions\SettingsException; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** diff --git a/src/Console/HistoryCommand.php b/src/Console/HistoryCommand.php new file mode 100644 index 0000000..dbf29a8 --- /dev/null +++ b/src/Console/HistoryCommand.php @@ -0,0 +1,142 @@ +target($settings->asSystem('laranail::settings.history')); + $key = $this->argument('key'); + $key = is_string($key) ? $key : ''; + $diff = $this->option('diff'); + $rollback = $this->option('rollback'); + + if (is_string($rollback)) { + return $this->rollback($handle, $key, $rollback); + } + + if (is_string($diff)) { + return $this->diff($handle, $key, $diff); + } + + return $this->list($handle, $key); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + } + + private function target(Settings $settings): Settings + { + $store = $this->option('store'); + $owner = $this->option('owner'); + $locale = $this->option('locale'); + + if (is_string($store) && $store !== '') { + $settings = $settings->store($store); + } + + if (is_string($owner) && $owner !== '') { + $settings = $settings->for(Scope::fromString($owner)?->owner() ?? throw new InvalidIdentifier(sprintf('--owner: [%s] is not alias:id.', $owner))); + } + + return is_string($locale) && $locale !== '' ? $settings->locale($locale) : $settings; + } + + private function list(Settings $settings, string $key): int + { + $limit = $this->option('limit'); + $entries = $settings->history()->key($key)->get(is_string($limit) && ctype_digit($limit) ? (int) $limit : 20); + + if ($entries === []) { + $this->info(sprintf('No history for [%s].', $key)); + + return self::SUCCESS; + } + + $this->table( + ['Version', 'Operation', 'Scope', 'Locale', 'By', 'Reason', 'At'], + array_map(static fn (HistoryEntry $entry): array => [ + $entry->version, + $entry->operation->value, + $entry->scope, + $entry->locale === '' ? '-' : $entry->locale, + $entry->causerType->value . ($entry->causerId === null ? '' : ':' . $entry->causerAlias . ':' . $entry->causerId), + $entry->reason ?? '', + $entry->createdAt->toIso8601String(), + ], $entries), + ); + + return self::SUCCESS; + } + + private function diff(Settings $settings, string $key, string $range): int + { + if (preg_match('/^(\d+)\.\.(\d+)$/', $range, $versions) !== 1) { + $this->error('--diff takes two versions, FROM..TO (for example 3..5).'); + + return self::FAILURE; + } + + $diff = $settings->historyDiff($key, (int) $versions[1], (int) $versions[2]); + $hidden = $diff->redacted || ($diff->encrypted && $this->option('reveal') !== true); + $show = static fn (mixed $value, bool $found): string => match (true) { + $hidden => '[protected]', + ! $found => '(no value)', + default => (string) json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), + }; + + $this->line(sprintf('v%d: %s', $diff->fromVersion, $show($diff->from, $diff->fromFound))); + $this->line(sprintf('v%d: %s', $diff->toVersion, $show($diff->to, $diff->toFound))); + $this->info($diff->changed ? 'The value changed.' : 'The value is the same.'); + + return self::SUCCESS; + } + + private function rollback(Settings $settings, string $key, string $version): int + { + if (! ctype_digit($version) || (int) $version < 1) { + $this->error('--rollback takes a version number.'); + + return self::FAILURE; + } + + $new = $settings->rollback($key, (int) $version); + $this->info(sprintf('Rolled [%s] back to version %d; it is now at version %d.', $key, (int) $version, $new)); + + return self::SUCCESS; + } +} diff --git a/src/Console/PruneHistoryCommand.php b/src/Console/PruneHistoryCommand.php new file mode 100644 index 0000000..c0374ae --- /dev/null +++ b/src/Console/PruneHistoryCommand.php @@ -0,0 +1,69 @@ +number($this->option('days') ?? $config->get('laranail.settings.history.keep_days')); + $versions = $this->number($this->option('versions') ?? $config->get('laranail.settings.history.keep_versions')); + + if ($days === false || $versions === false) { + $this->error('The retention period and the number of versions must be whole numbers.'); + + return self::FAILURE; + } + + if ($days === null && $versions === null) { + $this->info('No history retention is configured (history.keep_days and history.keep_versions are null); nothing to prune.'); + + return self::SUCCESS; + } + + try { + $removed = $prune->handle($days, $versions, Actor::system('laranail::settings.prune-history')); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(sprintf('Removed %d history entr%s.', $removed, $removed === 1 ? 'y' : 'ies')); + + return self::SUCCESS; + } + + /** A whole number, null when unset, false when it is anything else. */ + private function number(mixed $value): int|false|null + { + return match (true) { + $value === null => null, + is_int($value) => $value, + is_string($value) && ctype_digit($value) => (int) $value, + default => false, + }; + } +} diff --git a/src/Console/WarmCacheCommand.php b/src/Console/WarmCacheCommand.php index df8e959..eb8c36a 100644 --- a/src/Console/WarmCacheCommand.php +++ b/src/Console/WarmCacheCommand.php @@ -8,9 +8,9 @@ use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Actions\WarmCache; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Console\Tools\Commands\Command; use Simtabi\Laranail\Settings\Exceptions\SettingsException; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** diff --git a/src/Contracts/Settings.php b/src/Contracts/Settings.php index c9817e2..cb5fe22 100644 --- a/src/Contracts/Settings.php +++ b/src/Contracts/Settings.php @@ -10,7 +10,9 @@ use Simtabi\Laranail\Settings\Data\OwnerRef; use Illuminate\Contracts\Auth\Authenticatable; use Simtabi\Laranail\Settings\Audit\AuditQuery; +use Simtabi\Laranail\Settings\Data\HistoryDiff; use Simtabi\Laranail\Settings\Data\PromotionReport; +use Simtabi\Laranail\Settings\History\HistoryQuery; use Simtabi\Laranail\Settings\Data\PromotionRequest; use Simtabi\Laranail\Settings\Resolution\Explanation; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; @@ -22,10 +24,11 @@ use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; use Simtabi\Laranail\Settings\Exceptions\PromotionLocked; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; +use Simtabi\Laranail\Settings\Exceptions\HistoryUnavailable; use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; use Simtabi\Laranail\Settings\Exceptions\VerificationRequired; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** * Read and write settings. `store()`, `for()`, `locale()`, `as()`, `asSystem()` and `because()` @@ -192,4 +195,34 @@ public function promote(?PromotionRequest $request = null): PromotionReport; * Needs `view_audit` when the handle carries an actor. Entries never hold values. */ public function audit(): AuditQuery; + + /** + * Query the value history (§4.3) of this handle's store (and owner and locale, when set): + * `->key()`, `->for($owner)`, `->global()`, `->since()`, `->until()`, `->versions()`, then + * `->get()`, `->cursor()` or `->paginate()`. Needs `view_history` when the handle carries an + * actor. Payloads stay as stored (encrypted values encrypted), and are removed for an actor + * who may not view the setting's sensitive values. + */ + public function history(): HistoryQuery; + + /** + * Return a setting to the value it held at `$toVersion`, written as a new version through + * the normal write pipeline; returns that new version. Needs `rollback` (and step-up + * verification when `verification.abilities` lists it, as it does by default). + * + * @throws HistoryUnavailable when the store keeps no history or has no value at that version + * @throws AccessDenied + * @throws VerificationRequired + * @throws LockedSetting + */ + public function rollback(string $key, int $toVersion): int; + + /** + * The value at two versions of a setting. Needs `view_history`; an encrypted or sensitive + * value is decrypted only for an actor holding `view_sensitive` (or a trusted call), and is + * otherwise redacted to "changed or not". + * + * @throws HistoryUnavailable when the store keeps no history or lacks either version + */ + public function historyDiff(string $key, int $from, int $to): HistoryDiff; } diff --git a/src/Data/AlertContext.php b/src/Data/AlertContext.php new file mode 100644 index 0000000..84968f3 --- /dev/null +++ b/src/Data/AlertContext.php @@ -0,0 +1,85 @@ + $details the event's other identifiers (counts, versions) */ + public function __construct( + public string $event, + public ?string $store, + public ?string $scope, + public ?string $key, + public ?string $locale, + public string $outcome, + public string $actor, + public bool $sensitive, + public CarbonImmutable $occurredAt, + public array $details = [], + ) {} + + /** @param bool $sensitive whether the key's definition is sensitive (or encrypted) */ + public static function fromEvent(object $event, bool $sensitive, CarbonImmutable $occurredAt): self + { + $summary = EventSummary::of($event); + $text = static fn (string $name): ?string => is_string($summary[$name] ?? null) ? $summary[$name] : null; + $denied = $event instanceof AccessWasDenied || $event instanceof VerificationWasRequired; + $actor = $text('actor') ?? ($denied ? 'nobody' : 'system'); + + return new self( + event: new ReflectionClass($event)->getShortName(), + store: $text('store'), + scope: $text('scope'), + key: $text('key'), + locale: $text('locale'), + outcome: $denied ? 'denied' : 'allowed', + actor: $actor, + sensitive: $sensitive, + occurredAt: $occurredAt, + details: array_diff_key($summary, array_flip(['store', 'scope', 'key', 'locale', 'actor'])), + ); + } + + /** One line naming what happened, for a subject or a heading. */ + public function headline(): string + { + $what = trim((string) preg_replace('/(?event)); + + return $this->key === null + ? sprintf('laranail/settings: %s%s', $what, $this->store === null ? '' : ' in store ' . $this->store) + : sprintf('laranail/settings: %s, [%s] in store %s', $what, $this->key, $this->store ?? '?'); + } + + /** @return array */ + public function toArray(): array + { + return [ + 'event' => $this->event, + 'store' => $this->store, + 'scope' => $this->scope, + 'key' => $this->key, + 'locale' => $this->locale, + 'outcome' => $this->outcome, + 'actor' => $this->actor, + 'sensitive' => $this->sensitive, + 'occurred_at' => $this->occurredAt->toIso8601String(), + 'details' => $this->details, + ]; + } +} diff --git a/src/Data/AlertRule.php b/src/Data/AlertRule.php new file mode 100644 index 0000000..cb00b75 --- /dev/null +++ b/src/Data/AlertRule.php @@ -0,0 +1,142 @@ + $events + * @param list|null $keys + * @param list|null $stores + * @param list|null $outcomes + * @param list $mail + * @param array{type: class-string, id: int|string}|null $database + */ + public function __construct( + public array $events, + public ?array $keys = null, + public ?array $stores = null, + public bool $sensitiveOnly = false, + public ?array $outcomes = null, + public array $mail = [], + public ?string $slack = null, + public ?array $database = null, + public ?string $queue = null, + ) {} + + /** + * @param array $rule + * + * @throws InvalidConfiguration naming the rule's config path + */ + public static function fromConfig(array $rule, int|string $index): self + { + $path = 'laranail.settings.alerts.rules.' . $index; + $notify = $rule['notify'] ?? []; + + if (! is_array($notify)) { + throw new InvalidConfiguration($path . '.notify: an array of mail, slack and database.'); + } + + $events = self::strings($rule['events'] ?? null, $path . '.events', nullable: false) ?? []; + + if ($events === []) { + throw new InvalidConfiguration($path . '.events: name at least one event.'); + } + + $sensitive = $rule['sensitive_only'] ?? false; + $slack = $notify['slack'] ?? null; + $queue = $rule['queue'] ?? null; + + if (! is_bool($sensitive)) { + throw new InvalidConfiguration($path . '.sensitive_only: true or false.'); + } + + if ($slack !== null && (! is_string($slack) || $slack === '')) { + throw new InvalidConfiguration($path . '.notify.slack: a webhook URL, or null.'); + } + + if ($queue !== null && (! is_string($queue) || $queue === '')) { + throw new InvalidConfiguration($path . '.queue: a queue name, or null to send at once.'); + } + + return new self( + $events, + self::strings($rule['keys'] ?? null, $path . '.keys'), + self::strings($rule['stores'] ?? null, $path . '.stores'), + $sensitive, + self::strings($rule['outcomes'] ?? null, $path . '.outcomes'), + self::strings($notify['mail'] ?? [], $path . '.notify.mail', nullable: false) ?? [], + $slack, + self::database($notify['database'] ?? null, $path . '.notify.database'), + $queue, + ); + } + + /** Whether this rule answers the alert. */ + public function matches(object $event, AlertContext $context): bool + { + if (! array_any($this->events, static fn (string $name): bool => $name === $context->event || $name === $event::class)) { + return false; + } + + if ($this->stores !== null && ! in_array($context->store, $this->stores, true)) { + return false; + } + + if ($this->keys !== null && ($context->key === null || ! array_any($this->keys, static fn (string $glob): bool => Str::is($glob, $context->key)))) { + return false; + } + + if ($this->sensitiveOnly && ! $context->sensitive) { + return false; + } + + return $this->outcomes === null || in_array($context->outcome, $this->outcomes, true); + } + + /** @return list|null */ + private static function strings(mixed $value, string $path, bool $nullable = true): ?array + { + if ($value === null && $nullable) { + return null; + } + + if (! is_array($value) || ! array_all($value, static fn (mixed $item): bool => is_string($item) && $item !== '')) { + throw new InvalidConfiguration($path . ': a list of strings' . ($nullable ? ', or null for any.' : '.')); + } + + /** @var list */ + return array_values($value); + } + + /** @return array{type: class-string, id: int|string}|null */ + private static function database(mixed $value, string $path): ?array + { + if ($value === null) { + return null; + } + + $type = is_array($value) ? ($value['type'] ?? null) : null; + $id = is_array($value) ? ($value['id'] ?? null) : null; + + if (! is_string($type) || ! is_subclass_of($type, Model::class) || (! is_int($id) && ! is_string($id))) { + throw new InvalidConfiguration($path . ': [type => an Eloquent model class using Notifiable, id => its key], or null.'); + } + + return ['type' => $type, 'id' => $id]; + } +} diff --git a/src/Data/HistoryDiff.php b/src/Data/HistoryDiff.php new file mode 100644 index 0000000..dbec2ef --- /dev/null +++ b/src/Data/HistoryDiff.php @@ -0,0 +1,32 @@ +id, $this->store, $this->settingRef, $this->scope, $this->key, $this->locale, $this->operation, null, null, $this->oldType, $this->newType, $this->oldEncrypted, $this->newEncrypted, $this->version, $this->causerType, $this->causerAlias, $this->causerId, $this->reason, $this->createdAt); + } + + /** + * The entry without its payloads where they are encrypted: what may be shown to anyone who + * may read the history (`view_history`) but not the values (`view_sensitive`). + * + * @return array + */ + public function toArray(): array + { + return [ + 'id' => $this->id, + 'store' => $this->store, + 'setting_ref' => $this->settingRef, + 'scope' => $this->scope, + 'key' => $this->key, + 'locale' => $this->locale, + 'operation' => $this->operation->value, + 'old_value' => $this->oldEncrypted ? null : $this->oldValue, + 'new_value' => $this->newEncrypted ? null : $this->newValue, + 'old_type' => $this->oldType, + 'new_type' => $this->newType, + 'old_encrypted' => $this->oldEncrypted, + 'new_encrypted' => $this->newEncrypted, + 'version' => $this->version, + 'causer_type' => $this->causerType->value, + 'causer_alias' => $this->causerAlias, + 'causer_id' => $this->causerId, + 'reason' => $this->reason, + 'created_at' => $this->createdAt->toIso8601String(), + ]; + } +} diff --git a/src/Data/HistoryFilter.php b/src/Data/HistoryFilter.php new file mode 100644 index 0000000..5b35382 --- /dev/null +++ b/src/Data/HistoryFilter.php @@ -0,0 +1,48 @@ +store, + $scope ?? $this->scope, + $key ?? $this->key, + $locale ?? $this->locale, + $since ?? $this->since, + $until ?? $this->until, + $fromVersion ?? $this->fromVersion, + $toVersion ?? $this->toVersion, + ); + } +} diff --git a/src/Data/HistoryPage.php b/src/Data/HistoryPage.php new file mode 100644 index 0000000..76a8f10 --- /dev/null +++ b/src/Data/HistoryPage.php @@ -0,0 +1,25 @@ + $entries */ + public function __construct( + public array $entries, + public int $perPage, + public ?string $nextCursor = null, + public ?string $previousCursor = null, + ) {} + + public function hasMore(): bool + { + return $this->nextCursor !== null; + } +} diff --git a/src/Database/SchemaNames.php b/src/Database/SchemaNames.php index 8302c29..e920857 100644 --- a/src/Database/SchemaNames.php +++ b/src/Database/SchemaNames.php @@ -9,7 +9,7 @@ /** * The package's table names: `tables.prefix` (D-4) prepended to `tables.categories`, - * `tables.audit`, `tables.definitions` and each store's values table (`stores..table`, default the store name). + * `tables.audit`, `tables.definitions`, `tables.history` and each store's values table (`stores..table`, default the store name). * Every name is validated, because it is interpolated into SQL identifiers. */ final readonly class SchemaNames @@ -19,6 +19,7 @@ public function __construct( private string $categories = 'settings_categories', private string $audit = 'settings_audit', private string $definitions = 'settings_definitions', + private string $history = 'settings_history', ) { if (preg_match('/^[a-z0-9_]{0,32}$/', $prefix) !== 1) { throw new InvalidConfiguration(sprintf('laranail.settings.tables.prefix: [%s] must be [a-z0-9_], at most 32 characters.', $prefix)); @@ -27,6 +28,7 @@ public function __construct( self::assertTable($categories, 'laranail.settings.tables.categories'); self::assertTable($audit, 'laranail.settings.tables.audit'); self::assertTable($definitions, 'laranail.settings.tables.definitions'); + self::assertTable($history, 'laranail.settings.tables.history'); } /** @param array $tables `laranail.settings.tables` */ @@ -37,6 +39,7 @@ public static function fromConfig(array $tables): self self::string($tables, 'categories', 'settings_categories'), self::string($tables, 'audit', 'settings_audit'), self::string($tables, 'definitions', 'settings_definitions'), + self::string($tables, 'history', 'settings_history'), ); } @@ -63,10 +66,16 @@ public function definitions(): string return $this->prefix . $this->definitions; } - /** @return array{prefix: string, categories: string, audit: string, definitions: string} the unprefixed names */ + /** The value history table (§4.3), one per connection like the audit table. */ + public function history(): string + { + return $this->prefix . $this->history; + } + + /** @return array{prefix: string, categories: string, audit: string, definitions: string, history: string} the unprefixed names */ public function toArray(): array { - return ['prefix' => $this->prefix, 'categories' => $this->categories, 'audit' => $this->audit, 'definitions' => $this->definitions]; + return ['prefix' => $this->prefix, 'categories' => $this->categories, 'audit' => $this->audit, 'definitions' => $this->definitions, 'history' => $this->history]; } /** A store's values table: its configured table, or its name, after the prefix. */ diff --git a/src/Database/SchemaShape.php b/src/Database/SchemaShape.php index 2a8c4b9..519f2b5 100644 --- a/src/Database/SchemaShape.php +++ b/src/Database/SchemaShape.php @@ -43,6 +43,7 @@ public function __construct( public SchemaNames $names = new SchemaNames, public array $stores = [], public TenancyMode $tenancy = TenancyMode::None, + public bool $historyTable = false, ) {} /** @@ -79,6 +80,12 @@ public static function fromConfig(array $settings, mixed $dbToolsIdType = null): throw new InvalidConfiguration('laranail.settings.definitions.table: true or false.'); } + $history = self::section($settings, 'history')['enabled'] ?? true; + + if (! is_bool($history)) { + throw new InvalidConfiguration('laranail.settings.history.enabled: true or false.'); + } + $default = $settings['default'] ?? 'settings'; $default = new StoreName(is_string($default) ? $default : 'settings'); @@ -94,6 +101,7 @@ public static function fromConfig(array $settings, mixed $dbToolsIdType = null): SchemaNames::fromConfig(self::section($settings, 'tables')), self::storesFromConfig($settings, $followed ?? IdType::Bigint, $default), $tenancy, + $history, ); } @@ -136,6 +144,8 @@ public static function fromArray(array $data): self SchemaNames::fromConfig($tables), $stores, TenancyMode::tryFrom(self::text($switches, 'tenancy', 'none')) ?? throw $invalid('tenancy'), + // A file recorded before the history table existed describes a schema without it. + ($switches['history_table'] ?? false) === true, ); } @@ -161,6 +171,7 @@ public function toArray(): array 'categories_soft_deletes' => $this->categoriesSoftDeletes, 'definitions_table' => $this->definitionsTable, 'tenancy' => $this->tenancy->value, + 'history_table' => $this->historyTable, ], 'tables' => $this->names->toArray(), 'stores' => $stores, @@ -185,7 +196,7 @@ public function withStore(StoreSchema $store): self return $this; } - return new self($this->version, $this->identity, $this->ids, $this->ownerKey, $this->ownerKeyType, $this->translations, $this->categoriesSoftDeletes, $this->definitionsTable, $this->names, [...$this->stores, $store->name->value => $store], $this->tenancy); + return new self($this->version, $this->identity, $this->ids, $this->ownerKey, $this->ownerKeyType, $this->translations, $this->categoriesSoftDeletes, $this->definitionsTable, $this->names, [...$this->stores, $store->name->value => $store], $this->tenancy, $this->historyTable); } /** diff --git a/src/Definitions/DefinitionBuilder.php b/src/Definitions/DefinitionBuilder.php index 6f12605..aa94d56 100644 --- a/src/Definitions/DefinitionBuilder.php +++ b/src/Definitions/DefinitionBuilder.php @@ -8,6 +8,7 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\Precedence; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** * A mutable builder for one definition; {@see register()} builds the immutable diff --git a/src/Drivers/CachingDriver.php b/src/Drivers/CachingDriver.php index d169035..7c58112 100644 --- a/src/Drivers/CachingDriver.php +++ b/src/Drivers/CachingDriver.php @@ -11,8 +11,8 @@ use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\CacheTarget; -use Simtabi\Laranail\Settings\Caching\SettingsCache; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; +use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; /** * A database layer behind the settings cache (design §7.3, §7.5): reads come from cached per-scope diff --git a/src/Drivers/DatabaseDriver.php b/src/Drivers/DatabaseDriver.php index bea0c28..f89fa7e 100644 --- a/src/Drivers/DatabaseDriver.php +++ b/src/Drivers/DatabaseDriver.php @@ -291,6 +291,20 @@ public function lockedFind(StoreName $store, Scope $scope, Key $key, Locale $loc }); } + /** + * The stable reference of one identity's row (live or trashed) for the history table: its + * `uid` when the identity mode has one, else its primary key, as a string. Null when there is + * no row. + */ + public function reference(StoreName $store, Scope $scope, Key $key, Locale $locale): ?string + { + $column = $this->shape()->identity->hasUid() ? 'uid' : 'id'; + + $reference = $this->attempt($store, fn (): mixed => $this->identity($this->table($store), $scope, $key, $locale)->value($column)); + + return is_int($reference) || is_string($reference) ? (string) $reference : null; + } + public function forget(StoreName $store, Scope $scope, Key $key, Locale $locale): void { $this->assertWritable($store); diff --git a/src/Enums/HistoryOperation.php b/src/Enums/HistoryOperation.php new file mode 100644 index 0000000..b55607e --- /dev/null +++ b/src/Enums/HistoryOperation.php @@ -0,0 +1,33 @@ +history()`: an immutable query over the value history (§4.3), newest version first. + * Narrow it with `for()`, `global()`, `store()`, `key()`, `locale()`, `since()`, `until()` and + * `versions()`, then read it with `get()`, `cursor()` or `paginate()`. + * + * Entries carry the payloads as stored: encrypted values stay encrypted. For an actor who may not + * view a sensitive or encrypted setting, the entry's payloads are removed entirely + * ({@see HistoryEntry::redacted()}); `historyDiff()` is the way to read a past value. + */ +final readonly class HistoryQuery +{ + /** @param (Closure(HistoryEntry): bool)|null $mayView whether this actor may see an entry's values; null: every entry */ + public function __construct( + private QueryHistory $action, + private ?Actor $actor = null, + private HistoryFilter $filter = new HistoryFilter, + private ?Closure $mayView = null, + ) {} + + /** Entries about one owner (its scope). */ + public function for(Settable|OwnerRef $owner): self + { + $ref = $owner instanceof Settable ? $owner->settingsOwner() : $owner; + + return $this->with($this->filter->with(scope: $ref->scope())); + } + + /** Entries about global values only. */ + public function global(): self + { + return $this->with($this->filter->with(scope: Scope::global())); + } + + public function store(string $name): self + { + return $this->with($this->filter->with(store: new StoreName($name))); + } + + public function key(string $key): self + { + return $this->with($this->filter->with(key: new Key($key))); + } + + public function locale(string $locale): self + { + return $this->with($this->filter->with(locale: new Locale($locale))); + } + + public function since(DateTimeInterface $moment): self + { + return $this->with($this->filter->with(since: CarbonImmutable::instance($moment))); + } + + public function until(DateTimeInterface $moment): self + { + return $this->with($this->filter->with(until: CarbonImmutable::instance($moment))); + } + + /** Versions in this range, inclusive; either end may be open (null). */ + public function versions(?int $from = null, ?int $to = null): self + { + return $this->with($this->filter->with(fromVersion: $from, toVersion: $to)); + } + + public function filter(): HistoryFilter + { + return $this->filter; + } + + /** @return list newest version first */ + public function get(?int $limit = null): array + { + $query = $this->action->handle($this->filter, $this->actor); + + if ($limit !== null) { + $query->limit(max(1, $limit)); + } + + return array_values(array_map(fn (object $row): HistoryEntry => $this->entry((array) $row), $query->get()->all())); + } + + /** @return LazyCollection streamed in chunks, for long trails */ + public function cursor(): LazyCollection + { + return $this->action->handle($this->filter, $this->actor)->cursor()->map(fn (object $row): HistoryEntry => $this->entry((array) $row)); + } + + /** One page; pass its `nextCursor` back for the next. */ + public function paginate(int $perPage = 50, ?string $cursor = null): HistoryPage + { + $page = $this->action->handle($this->filter, $this->actor)->cursorPaginate(max(1, $perPage), ['*'], 'cursor', $cursor === null ? null : Cursor::fromEncoded($cursor)); + + return new HistoryPage( + array_values(array_map(fn (mixed $row): HistoryEntry => $this->entry(is_object($row) ? (array) $row : []), $page->items())), + max(1, $perPage), + $page->nextCursor()?->encode(), + $page->previousCursor()?->encode(), + ); + } + + /** @param array $row */ + private function entry(array $row): HistoryEntry + { + $entry = HistoryRepository::entry($row); + + return $this->mayView instanceof Closure && ! ($this->mayView)($entry) ? $entry->redacted() : $entry; + } + + private function with(HistoryFilter $filter): self + { + return new self($this->action, $this->actor, $filter, $this->mayView); + } +} diff --git a/src/Listeners/LogSettingsEvent.php b/src/Listeners/LogSettingsEvent.php new file mode 100644 index 0000000..6f851fe --- /dev/null +++ b/src/Listeners/LogSettingsEvent.php @@ -0,0 +1,35 @@ +getShortName()); + + $refusal ? $this->logger->warning($message, EventSummary::of($event)) : $this->logger->info($message, EventSummary::of($event)); + } +} diff --git a/src/Listeners/SendSettingsAlert.php b/src/Listeners/SendSettingsAlert.php new file mode 100644 index 0000000..7b6c831 --- /dev/null +++ b/src/Listeners/SendSettingsAlert.php @@ -0,0 +1,179 @@ + $rules + * @param Closure(?string, ?string): bool $sensitive whether a store's key is sensitive or encrypted + * @param Closure(): CarbonImmutable $clock + */ + public function __construct( + private Notifications $notifications, + private array $rules, + private Closure $sensitive, + private Closure $clock, + private LoggerInterface $logger, + private ?Cache $cache = null, + private int $throttle = 0, + private string $prefix = 'laranail-settings', + ) {} + + public function handle(object $event): void + { + if ($this->rules === []) { + return; + } + + $probe = AlertContext::fromEvent($event, false, ($this->clock)()); + $context = AlertContext::fromEvent($event, ($this->sensitive)($probe->store, $probe->key), $probe->occurredAt); + + foreach ($this->rules as $index => $rule) { + if (! $rule->matches($event, $context) || $this->throttled($index, $context)) { + continue; + } + + try { + $this->send($rule, $context); + } catch (Throwable $exception) { + // The change has committed; a failing alert must not turn it into an error. + $this->logger->error(sprintf('laranail/settings: alert rule %d could not be sent: %s', $index, $exception->getMessage()), ['event' => $context->event, 'store' => $context->store, 'key' => $context->key]); + } + } + } + + private function send(AlertRule $rule, AlertContext $context): void + { + $anonymous = new AnonymousNotifiable; + $channels = []; + + if ($rule->mail !== []) { + $anonymous->route('mail', $rule->mail); + $channels[] = 'mail'; + } + + if ($rule->slack !== null && SettingsAlert::slackAvailable()) { + $anonymous->route('slack', $rule->slack); + $channels[] = 'slack'; + } + + if ($channels !== []) { + $this->deliver($anonymous, new SettingsAlert($context, $channels), $rule->queue); + } + + if ($rule->database !== null) { + $notifiable = $this->notifiable($rule->database); + + if ($notifiable instanceof Model) { + $this->deliver($notifiable, new SettingsAlert($context, ['database']), $rule->queue); + } + } + } + + private function deliver(object $notifiable, SettingsAlert $alert, ?string $queue): void + { + if ($queue === null) { + $this->notifications->sendNow($notifiable, $alert); + + return; + } + + $this->notifications->send($notifiable, $alert->onQueue($queue)); + } + + /** @param array{type: class-string, id: int|string} $target */ + private function notifiable(array $target): ?Model + { + $model = $target['type']::query()->find($target['id']); + + if (! $model instanceof Model) { + $this->logger->warning(sprintf('laranail/settings: the alert notifiable [%s:%s] does not exist; the database alert was not sent.', $target['type'], $target['id'])); + + return null; + } + + return $model; + } + + private function throttled(int $index, AlertContext $context): bool + { + if (! $this->cache instanceof Cache || $this->throttle < 1) { + return false; + } + + $key = sprintf('%s:alerts:%d:%s', $this->prefix, $index, sha1(implode('|', [$context->event, $context->store, $context->scope, $context->key, $context->locale]))); + + try { + return ! $this->cache->add($key, true, $this->throttle); + } catch (Throwable $exception) { + $this->logger->warning(sprintf('laranail/settings: the alert throttle could not reach the cache (%s); sending the alert anyway.', $exception->getMessage())); + + return false; + } + } +} diff --git a/src/Logging/OperationalLogger.php b/src/Logging/OperationalLogger.php index ae45bd8..a66e658 100644 --- a/src/Logging/OperationalLogger.php +++ b/src/Logging/OperationalLogger.php @@ -9,7 +9,7 @@ use Psr\Log\LoggerTrait; use Psr\Log\LoggerInterface; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** * The package's operational log: denials, verification failures and configuration changes, diff --git a/src/Notifications/SettingsAlert.php b/src/Notifications/SettingsAlert.php new file mode 100644 index 0000000..efaa08a --- /dev/null +++ b/src/Notifications/SettingsAlert.php @@ -0,0 +1,122 @@ + $channels the channels this copy is sent on + * @param string $slackMessage the Slack message class to build (the Slack channel package's, by default) + */ + public function __construct( + public readonly AlertContext $context, + public readonly array $channels, + public readonly string $slackMessage = self::SLACK_MESSAGE, + ) {} + + /** Whether Slack alerts can be sent (the Slack channel package is installed). */ + public static function slackAvailable(): bool + { + return class_exists(self::SLACK_MESSAGE); + } + + /** @return list */ + public function via(object $notifiable): array + { + return $this->channels; + } + + public function toMail(object $notifiable): MailMessage + { + $mail = new MailMessage() + ->subject($this->context->headline()) + ->line($this->context->headline() . '.'); + + foreach ($this->lines() as $label => $value) { + $mail->line(sprintf('%s: %s', $label, $value)); + } + + return $mail->line('Values are never included in alerts; read the setting or its history to see what changed.'); + } + + /** @return array */ + public function toArray(object $notifiable): array + { + return $this->context->toArray(); + } + + /** @return array */ + public function toDatabase(object $notifiable): array + { + return $this->toArray($notifiable); + } + + /** + * The Slack message (incoming webhook), only when the Slack channel package is installed; + * the alert is never routed to Slack otherwise. + */ + public function toSlack(object $notifiable): ?object + { + if (! class_exists($this->slackMessage)) { + return null; + } + + $message = new ReflectionClass($this->slackMessage)->newInstance(); + $text = $this->context->headline() . "\n" . implode("\n", array_map( + static fn (string $label, string $value): string => sprintf('%s: %s', $label, $value), + array_keys($this->lines()), + $this->lines(), + )); + + if (method_exists($message, 'content')) { + $message->content($text); + } + + return $message; + } + + /** @return array */ + private function lines(): array + { + $lines = [ + 'Event' => $this->context->event, + 'Store' => $this->context->store ?? '-', + 'Key' => $this->context->key ?? '-', + 'Scope' => $this->context->scope ?? '-', + 'Locale' => $this->context->locale === null || $this->context->locale === '' ? '-' : $this->context->locale, + 'Actor' => $this->context->actor, + 'Outcome' => $this->context->outcome, + 'At' => $this->context->occurredAt->toIso8601String(), + ]; + + foreach ($this->context->details as $name => $value) { + $lines[ucfirst(str_replace('_', ' ', $name))] = is_bool($value) ? ($value ? 'yes' : 'no') : (string) ($value ?? '-'); + } + + return $lines; + } +} diff --git a/src/Providers/SettingsServiceProvider.php b/src/Providers/SettingsServiceProvider.php index ae349c0..579efa9 100644 --- a/src/Providers/SettingsServiceProvider.php +++ b/src/Providers/SettingsServiceProvider.php @@ -25,8 +25,8 @@ use Simtabi\Laranail\Package\Tools\Package; use Simtabi\Laranail\Settings\Stores\Store; use Illuminate\Contracts\Validation\Factory; -use Simtabi\Laranail\Settings\Audit\Auditor; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Data\AlertRule; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\SettingsManager; @@ -40,44 +40,45 @@ use Simtabi\Laranail\Settings\Actions\FlushScope; use Simtabi\Laranail\Settings\Actions\PruneAudit; use Simtabi\Laranail\Settings\Actions\QueryAudit; +use Simtabi\Laranail\Settings\Actions\WriteGuard; use Simtabi\Laranail\Settings\Audit\LogAuditSink; use Simtabi\Laranail\Settings\Contracts\Settings; use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Actions\DiffHistory; use Simtabi\Laranail\Settings\Actions\FindOrphans; use Simtabi\Laranail\Settings\Audit\AutoAuditSink; use Simtabi\Laranail\Settings\Audit\NullAuditSink; use Simtabi\Laranail\Settings\Contracts\AuditSink; use Simtabi\Laranail\Settings\Events\LayerSkipped; use Simtabi\Laranail\Settings\Models\ModelContext; -use Simtabi\Laranail\Settings\Resolution\Resolver; use Illuminate\Cache\Repository as CacheRepository; use Simtabi\Laranail\Settings\Actions\PromoteStore; +use Simtabi\Laranail\Settings\Actions\PruneHistory; use Simtabi\Laranail\Settings\Actions\PruneOrphans; +use Simtabi\Laranail\Settings\Actions\QueryHistory; use Simtabi\Laranail\Settings\Actions\StoreActions; use Simtabi\Laranail\Settings\Contracts\Authorizer; use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Database\SchemaShape; -use Simtabi\Laranail\Settings\Stores\SettingWriter; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Support\ConfigValues; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Illuminate\Contracts\Encryption\StringEncrypter; use Illuminate\Database\ConnectionResolverInterface; use Illuminate\Database\Eloquent\Relations\Relation; -use Simtabi\Laranail\Settings\Caching\SettingsCache; use Simtabi\Laranail\Settings\Console\DoctorCommand; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; -use Simtabi\Laranail\Settings\Support\ValuePipeline; use Illuminate\Contracts\Auth\Factory as AuthFactory; use Illuminate\Contracts\Filesystem\Factory as Disks; +use Simtabi\Laranail\Settings\Actions\HistoryActions; use Simtabi\Laranail\Settings\Actions\SettingActions; -use Simtabi\Laranail\Settings\Casting\CasterRegistry; +use Simtabi\Laranail\Settings\Console\HistoryCommand; use Simtabi\Laranail\Settings\Console\PromoteCommand; use Simtabi\Laranail\Settings\Drivers\ReadOnlyValues; +use Simtabi\Laranail\Settings\Actions\RollbackSetting; use Simtabi\Laranail\Settings\Actions\SyncDefinitions; use Simtabi\Laranail\Settings\Audit\DatabaseAuditSink; use Simtabi\Laranail\Settings\Contracts\ActorResolver; +use Simtabi\Laranail\Settings\Services\Access\Auditor; use Simtabi\Laranail\Settings\Console\MakeStoreCommand; use Simtabi\Laranail\Settings\Console\WarmCacheCommand; use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; @@ -85,38 +86,49 @@ use Simtabi\Laranail\Settings\Contracts\ValueValidator; use Simtabi\Laranail\Settings\Support\RecordSerializer; use Simtabi\Laranail\Settings\Actions\FindForeignTables; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Console\ClearCacheCommand; use Simtabi\Laranail\Settings\Console\PruneAuditCommand; use Simtabi\Laranail\Settings\Logging\OperationalLogger; use Simtabi\Laranail\Settings\Verification\NullVerifier; +use Simtabi\Laranail\Settings\Listeners\LogSettingsEvent; +use Simtabi\Laranail\Settings\Console\PruneHistoryCommand; use Simtabi\Laranail\Settings\Console\PruneOrphansCommand; use Simtabi\Laranail\Settings\Contracts\BootstrapEvidence; +use Simtabi\Laranail\Settings\Listeners\SendSettingsAlert; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Stores\InstallationEvidence; use Simtabi\Laranail\Package\Tools\Commands\InstallCommand; use Simtabi\Laranail\Settings\Authorization\GateAuthorizer; use Simtabi\Laranail\Settings\Exceptions\SettingsException; -use Simtabi\Laranail\Settings\Tenancy\TenantDiscriminators; +use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; +use Simtabi\Laranail\Settings\Services\Resolution\Resolver; use Simtabi\Laranail\Settings\Authorization\ChainAuthorizer; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; use Simtabi\Laranail\Settings\Database\SchemaReadinessProbe; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; use Simtabi\Laranail\Settings\Support\LaravelValueValidator; use Simtabi\Laranail\Settings\Console\SyncDefinitionsCommand; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; -use Simtabi\Laranail\Settings\Definitions\DatabaseDefinitions; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Authentication\GuardActorResolver; use Simtabi\Laranail\Settings\Actions\Categories\CategoryActions; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; use Simtabi\Laranail\Settings\Authentication\SanctumActorResolver; use Simtabi\Laranail\Settings\Authorization\PermissionsAuthorizer; use Simtabi\Laranail\Settings\Verification\ActorTimestampVerifier; use Simtabi\Laranail\Package\Tools\Providers\PackageServiceProvider; +use Simtabi\Laranail\Settings\Services\Tenancy\TenantDiscriminators; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; use Simtabi\Laranail\Settings\Database\Seeders\DefaultCategoriesSeeder; +use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; use Simtabi\Laranail\Settings\Verification\PasswordConfirmationVerifier; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; +use Illuminate\Contracts\Notifications\Dispatcher as NotificationDispatcher; use Simtabi\Laranail\Package\Tools\Support\Definitions\AutoSeederDefinition; /** @@ -147,7 +159,7 @@ public function configurePackage(Package $package): void ->hasPackageSeeders(AutoSeederDefinition::make('laranail/settings:defaults') ->seeders([DefaultCategoriesSeeder::class]) ->options(['disable_foreign_key_checks' => false, 'fire_events' => true])) - ->hasCommands([PromoteCommand::class, PruneOrphansCommand::class, PruneAuditCommand::class, MakeStoreCommand::class, DoctorCommand::class, SyncDefinitionsCommand::class, WarmCacheCommand::class, ClearCacheCommand::class]) + ->hasCommands([PromoteCommand::class, PruneOrphansCommand::class, PruneAuditCommand::class, PruneHistoryCommand::class, HistoryCommand::class, MakeStoreCommand::class, DoctorCommand::class, SyncDefinitionsCommand::class, WarmCacheCommand::class, ClearCacheCommand::class]) ->hasInstallCommand(static function (InstallCommand $command): void { $command ->startWith(static function (InstallCommand $command): void { @@ -181,6 +193,18 @@ public function packageBooted(): void foreach (self::strings($app, 'laranail.settings.readiness.flush_on') as $event) { $events->listen($event, $flush); } + + // Built-in listeners (`listeners.*`): registered by class, so nothing is built until an + // event fires. Reading configuration here touches neither the database nor the cache. + $config = $app->make(Repository::class); + + if ($config->get('laranail.settings.listeners.log', false) === true) { + $events->listen(LogSettingsEvent::EVENTS, LogSettingsEvent::class); + } + + if ($config->get('laranail.settings.listeners.alerts', true) !== false && filter_var($config->get('laranail.settings.alerts.enabled', false), FILTER_VALIDATE_BOOL)) { + $events->listen(SendSettingsAlert::EVENTS, SendSettingsAlert::class); + } } #[Override] @@ -303,6 +327,7 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { $this->registerAccess(); $this->registerCache(); + $this->registerListeners(); $this->app->scoped(SettingActions::class, static fn (Application $app): SettingActions => SettingActions::using( $app->make(SettingWriter::class), @@ -350,6 +375,7 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { $app->make(DefinitionRegistry::class), $app->make(ValueEncoder::class), $app->make(AccessGuard::class), + $app->make(Dispatcher::class), )); $this->app->scoped(QueryAudit::class, static fn (Application $app): QueryAudit => new QueryAudit( @@ -367,11 +393,31 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { $app->make(StoreActions::class)->flush, static fn (string $alias): ?string => Relation::getMorphedModel($alias), $app->make(AccessGuard::class), + $app->make(Dispatcher::class), + )); + + $this->app->scoped(HistoryActions::class, static function (Application $app): HistoryActions { + $access = $app->make(AccessGuard::class); + $writer = $app->make(SettingWriter::class); + $pipeline = $app->make(ValuePipeline::class); + + return new HistoryActions( + new QueryHistory($app->make(StoreRegistry::class), $access), + new RollbackSetting($writer, new WriteGuard($access, $writer), $pipeline, $app->make(Dispatcher::class)), + new DiffHistory($access, $pipeline), + ); + }); + + $this->app->scoped(PruneHistory::class, static fn (Application $app): PruneHistory => new PruneHistory( + $app->make(StoreRegistry::class), + $app->make(AccessGuard::class), + $app->make(Dispatcher::class), )); $this->app->scoped(PruneAudit::class, static fn (Application $app): PruneAudit => new PruneAudit( $app->make(StoreRegistry::class), $app->make(AccessGuard::class), + $app->make(Dispatcher::class), )); $this->app->bind(MakeStore::class, static fn (Application $app): MakeStore => new MakeStore( @@ -392,6 +438,7 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { storeActions: $app->make(StoreActions::class), auditQuery: $app->make(QueryAudit::class), databaseDefinitions: $app->make(DatabaseDefinitions::class), + historyActions: $app->make(HistoryActions::class), )); } @@ -582,6 +629,59 @@ static function (string $operation, Throwable $exception) use ($app): void { }); } + /** + * The built-in listeners, resolved when an event fires: the operational log, and alerts with + * their rules (validated then, with each rule's config path in the error), the throttle cache + * and the sensitive-key check that `sensitive_only` rules use. + */ + private function registerListeners(): void + { + $this->app->bind(LogSettingsEvent::class, static fn (Application $app): LogSettingsEvent => new LogSettingsEvent($app->make(OperationalLogger::class))); + + $this->app->bind(SendSettingsAlert::class, static function (Application $app): SendSettingsAlert { + $config = $app->make(Repository::class); + $cache = $config->get('laranail.settings.alerts.cache'); + $throttle = self::integer($app, 'laranail.settings.alerts.throttle', 300); + $repository = null; + + if ($throttle > 0) { + $store = $app->make(Caches::class)->store(is_string($cache) && $cache !== '' ? $cache : null); + $repository = $store instanceof CacheRepository ? $store : null; + } + + return new SendSettingsAlert( + $app->make(NotificationDispatcher::class), + array_values(array_map( + static fn (mixed $rule, int|string $index): AlertRule => is_array($rule) + ? AlertRule::fromConfig($rule, $index) + : throw new InvalidConfiguration(sprintf('laranail.settings.alerts.rules.%s: each rule is an array.', $index)), + self::array($app, 'laranail.settings.alerts.rules'), + array_keys(self::array($app, 'laranail.settings.alerts.rules')), + )), + static function (?string $store, ?string $key) use ($app): bool { + if ($store === null || $key === null) { + return false; + } + + try { + $name = new StoreName($store); + $setting = new Key($key); + } catch (SettingsException) { + return false; + } + + return ($app->make(RuntimeConfiguration::class)->findDefinition($name, $setting) + ?? $app->make(DefinitionRegistry::class)->find($name, $setting))?->isSensitive() ?? false; + }, + self::clock(), + $app->make(OperationalLogger::class), + $repository, + $throttle, + self::string($app, 'laranail.settings.cache.prefix', 'laranail-settings'), + ); + }); + } + /** * Tenancy (Amendment B): who the current tenant is, and the context the Eloquent models read * it from. `tenancy.discriminator`: `auto` (stancl/tenancy, then spatie/laravel-multitenancy, @@ -692,6 +792,7 @@ private function registerAccess(): void $undefined === 'allow', $app->make(Repository::class)->get('laranail.settings.authorization.require_actor', false) === true, $app->make(RuntimeConfiguration::class), + $app->make(Dispatcher::class), ); }); } diff --git a/src/Authorization/AccessGuard.php b/src/Services/Access/AccessGuard.php similarity index 87% rename from src/Authorization/AccessGuard.php rename to src/Services/Access/AccessGuard.php index a55e981..3d6e58c 100644 --- a/src/Authorization/AccessGuard.php +++ b/src/Services/Access/AccessGuard.php @@ -2,34 +2,38 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Authorization; +namespace Simtabi\Laranail\Settings\Services\Access; use Psr\Log\NullLogger; use Carbon\CarbonImmutable; use Illuminate\Http\Request; use Psr\Log\LoggerInterface; use Simtabi\Laranail\Settings\Data\Actor; +use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; -use Simtabi\Laranail\Settings\Audit\Auditor; use Simtabi\Laranail\Settings\Data\Decision; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Contracts\Authorizer; +use Simtabi\Laranail\Settings\Events\AccessWasDenied; use Simtabi\Laranail\Settings\Contracts\ActorResolver; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Simtabi\Laranail\Settings\Exceptions\ActorRequired; use Simtabi\Laranail\Settings\Verification\NullVerifier; +use Simtabi\Laranail\Settings\Events\VerificationWasRequired; use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; +use Simtabi\Laranail\Settings\Authorization\ClosureAuthorizer; use Simtabi\Laranail\Settings\Exceptions\VerificationRequired; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; use Simtabi\Laranail\Settings\Authentication\ClosureActorResolver; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** * Enforces access for one call: the actor requirement, the token ceiling, the authorizer, the - * undefined-ability policy and step-up verification. Every denial is logged and audited before - * it is thrown. Trusted calls (no actor, or an explicit system actor) are never authorized. + * undefined-ability policy and step-up verification. Every denial is logged, audited and + * announced ({@see AccessWasDenied}, {@see VerificationWasRequired}) before it is thrown. Trusted + * calls (no actor, or an explicit system actor) are never authorized. * * Bound `scoped`: it reads the runtime configuration of the current request. */ @@ -46,6 +50,7 @@ public function __construct( private bool $undefinedAllows = false, private bool $requireActor = false, private ?RuntimeConfiguration $runtime = null, + private ?Dispatcher $events = null, ) {} /** A guard that denies every actor and audits nowhere: the safe default for a hand-built manager. */ @@ -73,6 +78,7 @@ public function withAuditor(Auditor $auditor): self $this->undefinedAllows, $this->requireActor, $this->runtime, + $this->events, ); } @@ -209,5 +215,11 @@ private function refuse(?Actor $actor, Ability $ability, Subject $subject, strin $actor, meta: ['refusal' => $outcome, 'detail' => $reason], ); + + // At once, not after commit: the refusal throws, so a surrounding transaction is about to + // roll back, and whoever listens for refusals must hear of this one regardless. + $this->events?->dispatch($outcome === 'verification_required' && $actor instanceof Actor + ? new VerificationWasRequired($ability, $subject, $actor) + : new AccessWasDenied($ability, $subject, $actor, $outcome, $reason)); } } diff --git a/src/Audit/Auditor.php b/src/Services/Access/Auditor.php similarity index 95% rename from src/Audit/Auditor.php rename to src/Services/Access/Auditor.php index 146a46e..012b34d 100644 --- a/src/Audit/Auditor.php +++ b/src/Services/Access/Auditor.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Audit; +namespace Simtabi\Laranail\Settings\Services\Access; use Closure; use Carbon\CarbonImmutable; @@ -13,7 +13,7 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Contracts\AuditSink; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** * Builds audit entries and hands each to every configured sink, then to any sink added at diff --git a/src/Caching/SettingsCache.php b/src/Services/Cache/SettingsCache.php similarity index 99% rename from src/Caching/SettingsCache.php rename to src/Services/Cache/SettingsCache.php index ecf0eec..394cb4c 100644 --- a/src/Caching/SettingsCache.php +++ b/src/Services/Cache/SettingsCache.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Caching; +namespace Simtabi\Laranail\Settings\Services\Cache; use Closure; use Throwable; diff --git a/src/Casting/CasterRegistry.php b/src/Services/Casting/CasterRegistry.php similarity index 79% rename from src/Casting/CasterRegistry.php rename to src/Services/Casting/CasterRegistry.php index 0cc983a..3b4eb9d 100644 --- a/src/Casting/CasterRegistry.php +++ b/src/Services/Casting/CasterRegistry.php @@ -2,10 +2,17 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Casting; +namespace Simtabi\Laranail\Settings\Services\Casting; use BackedEnum; use Simtabi\Laranail\Settings\Contracts\Caster; +use Simtabi\Laranail\Settings\Casting\EnumCaster; +use Simtabi\Laranail\Settings\Casting\ArrayCaster; +use Simtabi\Laranail\Settings\Casting\FloatCaster; +use Simtabi\Laranail\Settings\Casting\StringCaster; +use Simtabi\Laranail\Settings\Casting\BooleanCaster; +use Simtabi\Laranail\Settings\Casting\IntegerCaster; +use Simtabi\Laranail\Settings\Casting\DateTimeCaster; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; /** diff --git a/src/Configuration/RuntimeConfiguration.php b/src/Services/Configuration/RuntimeConfiguration.php similarity index 96% rename from src/Configuration/RuntimeConfiguration.php rename to src/Services/Configuration/RuntimeConfiguration.php index 4863b0f..25ec516 100644 --- a/src/Configuration/RuntimeConfiguration.php +++ b/src/Services/Configuration/RuntimeConfiguration.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Configuration; +namespace Simtabi\Laranail\Settings\Services\Configuration; use Closure; use Psr\Log\NullLogger; @@ -20,16 +20,16 @@ use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Contracts\AuditSink; use Simtabi\Laranail\Settings\Contracts\Authorizer; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; -use Simtabi\Laranail\Settings\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Contracts\ActorResolver; use Simtabi\Laranail\Settings\Verification\ClosureVerifier; use Simtabi\Laranail\Settings\Definitions\DefinitionBuilder; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Authorization\ClosureAuthorizer; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Authentication\ClosureActorResolver; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** * Configuration changed in code, for the current request or job only. diff --git a/src/Database/AuditRepository.php b/src/Services/Database/AuditRepository.php similarity index 98% rename from src/Database/AuditRepository.php rename to src/Services/Database/AuditRepository.php index fae0452..ea7dcdf 100644 --- a/src/Database/AuditRepository.php +++ b/src/Services/Database/AuditRepository.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Database; +namespace Simtabi\Laranail\Settings\Services\Database; use JsonException; use Carbon\CarbonImmutable; @@ -15,9 +15,9 @@ use Simtabi\Laranail\Settings\Data\AuditFilter; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; /** * The audit table on one connection (§16.8): every read, write and delete of audit rows goes diff --git a/src/Database/CategoryRepository.php b/src/Services/Database/CategoryRepository.php similarity index 99% rename from src/Database/CategoryRepository.php rename to src/Services/Database/CategoryRepository.php index 6adf077..02bac8b 100644 --- a/src/Database/CategoryRepository.php +++ b/src/Services/Database/CategoryRepository.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Database; +namespace Simtabi\Laranail\Settings\Services\Database; use Carbon\CarbonImmutable; use Illuminate\Database\Query\Builder; diff --git a/src/Database/DefinitionsRepository.php b/src/Services/Database/DefinitionsRepository.php similarity index 98% rename from src/Database/DefinitionsRepository.php rename to src/Services/Database/DefinitionsRepository.php index 60550d9..e1ce6a2 100644 --- a/src/Database/DefinitionsRepository.php +++ b/src/Services/Database/DefinitionsRepository.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Database; +namespace Simtabi\Laranail\Settings\Services\Database; use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Support\Json; diff --git a/src/Services/Database/HistoryRepository.php b/src/Services/Database/HistoryRepository.php new file mode 100644 index 0000000..a623f9a --- /dev/null +++ b/src/Services/Database/HistoryRepository.php @@ -0,0 +1,248 @@ +get($store)->database(); + + return $database instanceof DatabaseDriver && $database->shape()->historyTable ? new self($database) : null; + } + + /** + * One row as an entry; a row missing a required column raises DriverFailure rather than + * inventing an entry. + * + * @param array $row + */ + public static function entry(array $row): HistoryEntry + { + $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; + $id = $text('id'); + $store = $text('store'); + $scope = $text('scope'); + $key = $text('key'); + $created = $text('created_at'); + $operation = HistoryOperation::tryFrom($text('operation') ?? ''); + $causer = ActorType::tryFrom($text('causer_type') ?? ''); + $version = $row['version'] ?? null; + + if ($id === null || $store === null || $scope === null || $key === null || $created === null || ! $operation instanceof HistoryOperation || ! $causer instanceof ActorType || ! is_numeric($version)) { + throw new DriverFailure(sprintf('History row [%s] is malformed.', $id ?? '?')); + } + + return new HistoryEntry( + id: $id, + store: $store, + settingRef: $text('setting_ref'), + scope: $scope, + key: $key, + locale: $text('locale') ?? '', + operation: $operation, + oldValue: $text('old_value'), + newValue: $text('new_value'), + oldType: $text('old_type'), + newType: $text('new_type'), + oldEncrypted: DatabaseValues::boolean($row['old_encrypted'] ?? false), + newEncrypted: DatabaseValues::boolean($row['new_encrypted'] ?? false), + version: (int) $version, + causerType: $causer, + causerAlias: $text('causer_alias'), + causerId: $text('causer_id'), + reason: $text('reason'), + createdAt: CarbonImmutable::parse($created), + ); + } + + public function database(): DatabaseDriver + { + return $this->database; + } + + /** + * Append one entry. `$before` is the row as it was (null for a first write), `$after` the row + * as it is now (null for a forget). Runs on the caller's transaction, so a failed insert rolls + * the change back with it. + */ + public function record( + StoreName $store, + HistoryOperation $operation, + ?Record $before, + ?Record $after, + int $version, + ?string $reference, + ?Actor $causer, + ?string $reason, + CarbonImmutable $at, + ): void { + $subject = $after ?? $before ?? throw new DriverFailure('A history entry needs the row before or after the change.'); + $causer ??= Actor::system(); + + $this->database->attempt($store, fn (): bool => $this->table()->insert([ + 'id' => (string) Str::ulid(), + 'store' => $store->value, + 'setting_ref' => $reference, + 'scope' => $subject->scope->value, + 'key' => $subject->key->value, + 'locale' => $subject->locale->value, + 'operation' => $operation->value, + 'old_value' => $before?->payload, + 'new_value' => $after?->payload, + 'old_type' => $before?->type, + 'new_type' => $after?->type, + 'old_encrypted' => $before instanceof Record && $before->encrypted, + 'new_encrypted' => $after instanceof Record && $after->encrypted, + 'version' => $version, + 'causer_type' => $causer->type->value, + 'causer_alias' => $causer->alias, + 'causer_id' => $causer->id, + 'reason' => $reason ?? $causer->context->reason, + 'created_at' => $at, + ] + $this->database->tenantColumns())); + } + + /** The highest version this identity's history holds (0 when it has none). */ + public function latestVersion(StoreName $store, Scope $scope, Key $key, Locale $locale): int + { + $version = $this->database->attempt($store, fn (): mixed => $this->identity($store, $scope, $key, $locale)->max('version')); + + return is_numeric($version) ? (int) $version : 0; + } + + /** The entry that produced this version of the identity's value (never a tombstone), or null. */ + public function find(StoreName $store, Scope $scope, Key $key, Locale $locale, int $version): ?HistoryEntry + { + $row = $this->database->attempt($store, fn (): ?object => $this->identity($store, $scope, $key, $locale) + ->where('version', $version) + ->where('operation', '!=', HistoryOperation::Forget->value) + ->orderByDesc('id') + ->first()); + + return $row === null ? null : self::entry((array) $row); + } + + /** The current tenant's entries matching a filter, newest version first. */ + public function query(HistoryFilter $filter): Builder + { + $query = $this->database->scoped($this->table()); + + foreach (['store' => $filter->store?->value, 'scope' => $filter->scope?->value, 'key' => $filter->key?->value, 'locale' => $filter->locale?->value] as $column => $value) { + if ($value !== null) { + $query->where($column, $value); + } + } + + if ($filter->since instanceof CarbonImmutable) { + $query->where('created_at', '>=', $filter->since); + } + + if ($filter->until instanceof CarbonImmutable) { + $query->where('created_at', '<=', $filter->until); + } + + if ($filter->fromVersion !== null) { + $query->where('version', '>=', $filter->fromVersion); + } + + if ($filter->toVersion !== null) { + $query->where('version', '<=', $filter->toVersion); + } + + return $query->orderByDesc('version')->orderByDesc('id'); + } + + /** + * Delete every tenant's entries the retention policy no longer keeps: older than `$cutoff`, + * and/or more than `$keepVersions` versions behind their identity's newest. Returns how many + * went. The store names the store in an outage message only. + */ + public function prune(?CarbonImmutable $cutoff, ?int $keepVersions, StoreName $store): int + { + return $this->database->attempt($store, function () use ($cutoff, $keepVersions): int { + $removed = $cutoff instanceof CarbonImmutable ? $this->table()->where('created_at', '<', $cutoff)->delete() : 0; + + if ($keepVersions === null) { + return $removed; + } + + $tenant = $this->database->shape()->tenancy->hasColumn() ? ['tenant'] : []; + $groups = $this->table() + ->select([...$tenant, 'store', 'scope', 'key', 'locale']) + ->selectRaw('max(version) as newest') + ->groupBy([...$tenant, 'store', 'scope', 'key', 'locale']) + ->get(); + + foreach ($groups as $group) { + $group = (array) $group; + $newest = is_numeric($group['newest'] ?? null) ? (int) $group['newest'] : 0; + + if ($newest - $keepVersions < 1) { + continue; + } + + $query = $this->table()->where('version', '<=', $newest - $keepVersions); + + foreach ([...$tenant, 'store', 'scope', 'key', 'locale'] as $column) { + $query->where($column, $group[$column] ?? null); + } + + $removed += $query->delete(); + } + + return $removed; + }); + } + + private function identity(StoreName $store, Scope $scope, Key $key, Locale $locale): Builder + { + return $this->database->scoped($this->table()) + ->where('store', $store->value) + ->where('scope', $scope->value) + ->where('key', $key->value) + ->where('locale', $locale->value); + } + + private function table(): Builder + { + return $this->database->connection()->table($this->database->names()->history()); + } +} diff --git a/src/Database/SchemaInspector.php b/src/Services/Database/SchemaInspector.php similarity index 97% rename from src/Database/SchemaInspector.php rename to src/Services/Database/SchemaInspector.php index 56518e9..68fdfe9 100644 --- a/src/Database/SchemaInspector.php +++ b/src/Services/Database/SchemaInspector.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Database; +namespace Simtabi\Laranail\Settings\Services\Database; use Throwable; use Illuminate\Database\Query\Builder; diff --git a/src/Database/SchemaShapeRepository.php b/src/Services/Database/SchemaShapeRepository.php similarity index 96% rename from src/Database/SchemaShapeRepository.php rename to src/Services/Database/SchemaShapeRepository.php index 68057fb..eeb97f1 100644 --- a/src/Database/SchemaShapeRepository.php +++ b/src/Services/Database/SchemaShapeRepository.php @@ -2,11 +2,13 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Database; +namespace Simtabi\Laranail\Settings\Services\Database; use Closure; use Throwable; use Illuminate\Filesystem\Filesystem; +use Simtabi\Laranail\Settings\Database\SchemaShape; +use Simtabi\Laranail\Settings\Database\StoreSchema; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** diff --git a/src/Definitions/DatabaseDefinitions.php b/src/Services/Definitions/DatabaseDefinitions.php similarity index 96% rename from src/Definitions/DatabaseDefinitions.php rename to src/Services/Definitions/DatabaseDefinitions.php index 44b581c..5539feb 100644 --- a/src/Definitions/DatabaseDefinitions.php +++ b/src/Services/Definitions/DatabaseDefinitions.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Definitions; +namespace Simtabi\Laranail\Settings\Services\Definitions; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Stores\Store; @@ -10,12 +10,12 @@ use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Support\Translations; use Simtabi\Laranail\Settings\Support\ValueEncoder; -use Simtabi\Laranail\Settings\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Enums\TranslationsMode; use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; -use Simtabi\Laranail\Settings\Database\DefinitionsRepository; +use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; +use Simtabi\Laranail\Settings\Services\Database\DefinitionsRepository; /** * The `database` definition source (D-6): rows of the optional definitions table that are not diff --git a/src/Definitions/DefinitionRegistry.php b/src/Services/Definitions/DefinitionRegistry.php similarity index 96% rename from src/Definitions/DefinitionRegistry.php rename to src/Services/Definitions/DefinitionRegistry.php index 9691b7d..0c606e7 100644 --- a/src/Definitions/DefinitionRegistry.php +++ b/src/Services/Definitions/DefinitionRegistry.php @@ -2,14 +2,15 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Definitions; +namespace Simtabi\Laranail\Settings\Services\Definitions; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\Precedence; -use Simtabi\Laranail\Settings\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; +use Simtabi\Laranail\Settings\Definitions\DefinitionBuilder; +use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; /** * Every known setting definition, from code (`define()`) and from the `definitions` config map. diff --git a/src/Drivers/DriverFactory.php b/src/Services/Drivers/DriverFactory.php similarity index 94% rename from src/Drivers/DriverFactory.php rename to src/Services/Drivers/DriverFactory.php index 1eec3e7..7c0d023 100644 --- a/src/Drivers/DriverFactory.php +++ b/src/Services/Drivers/DriverFactory.php @@ -2,17 +2,23 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Drivers; +namespace Simtabi\Laranail\Settings\Services\Drivers; use Closure; use Illuminate\Contracts\Config\Repository; use Simtabi\Laranail\Settings\Contracts\Driver; use Simtabi\Laranail\Settings\Data\LayerConfig; use Simtabi\Laranail\Settings\Enums\DriverType; +use Simtabi\Laranail\Settings\Drivers\PhpDriver; +use Simtabi\Laranail\Settings\Drivers\JsonDriver; +use Simtabi\Laranail\Settings\Drivers\ArrayDriver; use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Database\SchemaShape; +use Simtabi\Laranail\Settings\Drivers\ConfigDriver; use Illuminate\Database\ConnectionResolverInterface; use Illuminate\Contracts\Filesystem\Factory as Disks; +use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Drivers\ReadOnlyValues; use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; use Simtabi\Laranail\Settings\Support\RecordSerializer; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; diff --git a/src/Resolution/PreloadedRecords.php b/src/Services/Resolution/PreloadedRecords.php similarity index 97% rename from src/Resolution/PreloadedRecords.php rename to src/Services/Resolution/PreloadedRecords.php index 1d55e0a..bcbec1d 100644 --- a/src/Resolution/PreloadedRecords.php +++ b/src/Services/Resolution/PreloadedRecords.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Resolution; +namespace Simtabi\Laranail\Settings\Services\Resolution; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Record; diff --git a/src/Resolution/Resolver.php b/src/Services/Resolution/Resolver.php similarity index 96% rename from src/Resolution/Resolver.php rename to src/Services/Resolution/Resolver.php index 1307aa1..1623772 100644 --- a/src/Resolution/Resolver.php +++ b/src/Services/Resolution/Resolver.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Resolution; +namespace Simtabi\Laranail\Settings\Services\Resolution; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Scope; @@ -13,9 +13,10 @@ use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\Precedence; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Support\ValuePipeline; +use Simtabi\Laranail\Settings\Resolution\Explanation; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; /** * Resolves a read through the cascade: diff --git a/src/Stores/SettingWriter.php b/src/Services/Stores/SettingWriter.php similarity index 70% rename from src/Stores/SettingWriter.php rename to src/Services/Stores/SettingWriter.php index 206382a..93b54ca 100644 --- a/src/Stores/SettingWriter.php +++ b/src/Services/Stores/SettingWriter.php @@ -2,29 +2,36 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Stores; +namespace Simtabi\Laranail\Settings\Services\Stores; use Closure; use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Data\Key; +use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Locale; use Simtabi\Laranail\Settings\Data\Record; use Illuminate\Contracts\Events\Dispatcher; +use Simtabi\Laranail\Settings\Stores\Layer; +use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Events\SettingSaved; +use Simtabi\Laranail\Settings\Events\SettingLocked; use Simtabi\Laranail\Settings\Events\SettingSaving; -use Simtabi\Laranail\Settings\Support\ValuePipeline; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Enums\HistoryOperation; +use Simtabi\Laranail\Settings\Events\SettingUnlocked; use Simtabi\Laranail\Settings\Events\SettingForgotten; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; use Simtabi\Laranail\Settings\Events\SettingForgetting; use Simtabi\Laranail\Settings\Exceptions\LockedSetting; use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; +use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; +use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** * Every write path: set, forget, lock, unlock. Checks run before anything is stored, in this @@ -35,6 +42,12 @@ * A plain set that loses a race (another writer changed the row between the read and the * write) is retried once when `writes.retry_on_conflict` is on, re-reading the row under a row * lock; a write that names the version it expects is never retried. + * + * On a database layer whose schema has the history table (§4.3), every change also appends a + * history entry in the same transaction as the row, so a failed history insert rolls the change + * back. The entry keeps the payload as stored (encrypted values stay encrypted) and names the + * causer given to {@see causedBy()}. A row created again after a forget continues its version + * from the history, so "version N" always means one value. */ final readonly class SettingWriter { @@ -48,8 +61,27 @@ public function __construct( private Closure $clock, private bool $retryOnConflict = false, private ?Closure $onRetry = null, + private ?Actor $causer = null, + private ?string $reason = null, ) {} + /** A copy whose history entries name this causer and reason (null causer: the system). */ + public function causedBy(?Actor $causer, ?string $reason = null): self + { + return new self($this->pipeline, $this->events, $this->clock, $this->retryOnConflict, $this->onRetry, $causer, $reason); + } + + /** + * Write a value a rollback recovered, as a new version, only if the row is still at + * `$expectedVersion`; its history entry is a `rollback`. Lock rules apply as for a set. + * + * @throws ConcurrentModification + */ + public function rollback(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition, mixed $value, int $expectedVersion, bool $overrideLock = false): Record + { + return $this->write($store, $key, $locale, $owner, $definition, $value, $overrideLock, $expectedVersion, HistoryOperation::Rollback); + } + /** Store a value and return the stored record. A locked row refuses it. */ public function set(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition, mixed $value): Record { @@ -111,13 +143,13 @@ public function unlock(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, return $this->storeLock($store, $key, $locale, $owner, locked: false, definition: $definition); } - private function write(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition, mixed $value, bool $overrideLock, ?int $expectedVersion = null): Record + private function write(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition, mixed $value, bool $overrideLock, ?int $expectedVersion = null, HistoryOperation $operation = HistoryOperation::Set): Record { $retries = $expectedVersion === null && $this->retryOnConflict ? 1 : 0; for ($attempt = 0; ; $attempt++) { try { - return $this->writeOnce($store, $key, $locale, $owner, $definition, $value, $overrideLock, $expectedVersion, relocked: $attempt > 0); + return $this->writeOnce($store, $key, $locale, $owner, $definition, $value, $overrideLock, $expectedVersion, $operation, relocked: $attempt > 0); } catch (ConcurrentModification $conflict) { if ($attempt >= $retries) { throw $conflict; @@ -130,7 +162,7 @@ private function write(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, } } - private function writeOnce(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition, mixed $value, bool $overrideLock, ?int $expectedVersion, bool $relocked): Record + private function writeOnce(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition, mixed $value, bool $overrideLock, ?int $expectedVersion, HistoryOperation $operation, bool $relocked): Record { $this->guard($store, $key, $locale, $owner, $definition, $overrideLock); @@ -163,7 +195,7 @@ private function writeOnce(Store $store, Key $key, Locale $locale, ?OwnerRef $ow ); $this->events->dispatch(new SettingSaving($store->name->value, $scope->value, $key->value, $locale->value, $version)); - $layer->driver->put($store->name, $record); + $this->persist($store, $layer, $operation, $existing, $record); $this->events->dispatch(new SettingSaved($store->name->value, $scope->value, $key->value, $locale->value, $version)); return $record; @@ -171,7 +203,8 @@ private function writeOnce(Store $store, Key $key, Locale $locale, ?OwnerRef $ow /** * The version a write continues: the live row's, else (soft deletes) the trashed row's, so - * the write restores it instead of colliding with it, else 0. + * the write restores it instead of colliding with it, else the newest version in the history + * (a row created again after a forget continues its trail), else 0. */ private function baseVersion(Layer $layer, Store $store, Scope $scope, Key $key, Locale $locale, ?Record $existing): int { @@ -179,7 +212,37 @@ private function baseVersion(Layer $layer, Store $store, Scope $scope, Key $key, return $existing->version; } - return $this->database($layer)?->trashedVersion($store->name, $scope, $key, $locale) ?? 0; + $trashed = $this->database($layer)?->trashedVersion($store->name, $scope, $key, $locale) ?? 0; + + return max($trashed, $this->history($layer)?->latestVersion($store->name, $scope, $key, $locale) ?? 0); + } + + /** + * Store a record and, where the layer keeps history, its history entry, in one transaction + * (a savepoint inside the caller's), so a failed history insert undoes the row. + */ + private function persist(Store $store, Layer $layer, HistoryOperation $operation, ?Record $before, Record $after): void + { + $history = $this->history($layer); + + if (! $history instanceof HistoryRepository) { + $layer->driver->put($store->name, $after); + + return; + } + + $history->database()->transaction(function () use ($store, $layer, $history, $operation, $before, $after): void { + $layer->driver->put($store->name, $after); + $history->record($store->name, $operation, $before, $after, $after->version, $history->database()->reference($store->name, $after->scope, $after->key, $after->locale), $this->causer, $this->reason, ($this->clock)()); + }, $store->name); + } + + /** The history table of the layer's database, when the recorded schema has one. */ + private function history(Layer $layer): ?HistoryRepository + { + $database = $this->database($layer); + + return $database instanceof DatabaseDriver && $database->shape()->historyTable ? new HistoryRepository($database) : null; } private function database(Layer $layer): ?DatabaseDriver @@ -200,7 +263,19 @@ private function remove(Store $store, Key $key, Locale $locale, ?OwnerRef $owner } $this->events->dispatch(new SettingForgetting($store->name->value, $scope->value, $key->value, $locale->value, $existing->version)); - $layer->driver->forget($store->name, $scope, $key, $locale); + $history = $this->history($layer); + + if ($history instanceof HistoryRepository) { + // A tombstone: the version that was removed, no new value. The next write continues after it. + $history->database()->transaction(function () use ($store, $layer, $history, $scope, $key, $locale, $existing): void { + $reference = $history->database()->reference($store->name, $scope, $key, $locale); + $layer->driver->forget($store->name, $scope, $key, $locale); + $history->record($store->name, HistoryOperation::Forget, $existing, null, $existing->version, $reference, $this->causer, $this->reason, ($this->clock)()); + }, $store->name); + } else { + $layer->driver->forget($store->name, $scope, $key, $locale); + } + $this->events->dispatch(new SettingForgotten($store->name->value, $scope->value, $key->value, $locale->value, $existing->version)); return $existing; @@ -212,8 +287,8 @@ private function storeLock(Store $store, Key $key, Locale $locale, ?OwnerRef $ow $layer = $store->writableLayer(); $scope = $this->scope($owner); - $existing = $layer->driver->load($store->name, [$scope])->find($scope, $key, $locale) - ?? new Record($scope, $key, $locale, null, version: $this->baseVersion($layer, $store, $scope, $key, $locale, null)); + $found = $layer->driver->load($store->name, [$scope])->find($scope, $key, $locale); + $existing = $found ?? new Record($scope, $key, $locale, null, version: $this->baseVersion($layer, $store, $scope, $key, $locale, null)); $record = new Record( $existing->scope, @@ -230,7 +305,10 @@ private function storeLock(Store $store, Key $key, Locale $locale, ?OwnerRef $ow $definition instanceof Definition && $definition->public, ); - $layer->driver->put($store->name, $record); + $this->persist($store, $layer, $locked ? HistoryOperation::Lock : HistoryOperation::Unlock, $found, $record); + + $event = $locked ? SettingLocked::class : SettingUnlocked::class; + $this->events->dispatch(new $event($store->name->value, $scope->value, $key->value, $locale->value, $record->version)); return $record; } diff --git a/src/Stores/StoreRegistry.php b/src/Services/Stores/StoreRegistry.php similarity index 96% rename from src/Stores/StoreRegistry.php rename to src/Services/Stores/StoreRegistry.php index e6805a9..81cadbe 100644 --- a/src/Stores/StoreRegistry.php +++ b/src/Services/Stores/StoreRegistry.php @@ -2,10 +2,12 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Stores; +namespace Simtabi\Laranail\Settings\Services\Stores; use Closure; use Simtabi\Laranail\Settings\Enums\IdType; +use Simtabi\Laranail\Settings\Stores\Layer; +use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Contracts\Driver; use Simtabi\Laranail\Settings\Data\LayerConfig; @@ -13,18 +15,19 @@ use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Database\StoreSchema; use Simtabi\Laranail\Settings\Support\ConfigValues; -use Simtabi\Laranail\Settings\Caching\SettingsCache; use Simtabi\Laranail\Settings\Drivers\CachingDriver; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Exceptions\UnknownStore; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; use Simtabi\Laranail\Settings\Contracts\BootstrapEvidence; +use Simtabi\Laranail\Settings\Stores\InstallationEvidence; use Simtabi\Laranail\Settings\Drivers\BootstrapGatedDriver; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; +use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** * Builds and validates every store from configuration on first use. Configuration errors are diff --git a/src/Tenancy/TenantDiscriminators.php b/src/Services/Tenancy/TenantDiscriminators.php similarity index 95% rename from src/Tenancy/TenantDiscriminators.php rename to src/Services/Tenancy/TenantDiscriminators.php index 8e2a753..deebf9b 100644 --- a/src/Tenancy/TenantDiscriminators.php +++ b/src/Services/Tenancy/TenantDiscriminators.php @@ -2,11 +2,13 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Tenancy; +namespace Simtabi\Laranail\Settings\Services\Tenancy; use Illuminate\Contracts\Container\Container; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Tenancy\NullTenantDiscriminator; +use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; /** * Builds the configured tenant discriminator (`tenancy.discriminator`): `auto` (stancl/tenancy, diff --git a/src/Support/ValuePipeline.php b/src/Services/Values/ValuePipeline.php similarity index 90% rename from src/Support/ValuePipeline.php rename to src/Services/Values/ValuePipeline.php index 15d43d1..e911077 100644 --- a/src/Support/ValuePipeline.php +++ b/src/Services/Values/ValuePipeline.php @@ -2,14 +2,15 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Support; +namespace Simtabi\Laranail\Settings\Services\Values; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Record; use Simtabi\Laranail\Settings\Data\Definition; -use Simtabi\Laranail\Settings\Casting\CasterRegistry; +use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; use Simtabi\Laranail\Settings\Contracts\ValueValidator; +use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; /** * Turns a caller's value into a stored payload (validate raw → cast → encode → encrypt) and a diff --git a/src/SettingsManager.php b/src/SettingsManager.php index 9f9daea..bc16c53 100644 --- a/src/SettingsManager.php +++ b/src/SettingsManager.php @@ -19,30 +19,35 @@ use Illuminate\Contracts\Auth\Authenticatable; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Audit\AuditQuery; +use Simtabi\Laranail\Settings\Data\HistoryDiff; use Simtabi\Laranail\Settings\Actions\WarmCache; +use Simtabi\Laranail\Settings\Data\HistoryEntry; use Simtabi\Laranail\Settings\Data\SettingWrite; use Simtabi\Laranail\Settings\Actions\ClearCache; use Simtabi\Laranail\Settings\Actions\QueryAudit; use Simtabi\Laranail\Settings\Contracts\Settable; use Simtabi\Laranail\Settings\Contracts\Settings; +use Simtabi\Laranail\Settings\Data\HistoryFilter; use Simtabi\Laranail\Settings\Data\SettingTarget; -use Simtabi\Laranail\Settings\Resolution\Resolver; use Simtabi\Laranail\Settings\Actions\StoreActions; use Simtabi\Laranail\Settings\Data\PromotionReport; -use Simtabi\Laranail\Settings\Stores\SettingWriter; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\History\HistoryQuery; use Simtabi\Laranail\Settings\Data\PromotionRequest; +use Simtabi\Laranail\Settings\Actions\HistoryActions; use Simtabi\Laranail\Settings\Actions\SettingActions; use Simtabi\Laranail\Settings\Resolution\Explanation; use Simtabi\Laranail\Settings\Exceptions\TypeMismatch; use Simtabi\Laranail\Settings\Exceptions\ActorRequired; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; use Simtabi\Laranail\Settings\Categories\CategoryManager; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; -use Simtabi\Laranail\Settings\Definitions\DatabaseDefinitions; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Resolution\Resolver; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** * The {@see Settings} implementation: an immutable handle over the store, owner, locale and @@ -78,6 +83,7 @@ public function __construct( private ?StoreActions $storeActions = null, private ?QueryAudit $auditQuery = null, private ?DatabaseDefinitions $databaseDefinitions = null, + private ?HistoryActions $historyActions = null, ) { $this->access = $access ?? AccessGuard::closed(); $this->actions = $actions ?? SettingActions::using($writer, $this->access); @@ -320,6 +326,48 @@ public function audit(): AuditQuery return $this->storeName instanceof StoreName ? $query->store($this->storeName->value) : $query; } + public function history(): HistoryQuery + { + $store = $this->targetStore(); + $filter = new HistoryFilter($store->name, $this->owner instanceof OwnerRef ? $this->scope() : null, locale: $this->selectedLocale); + $actor = $this->actingAs; + + return new HistoryQuery( + $this->historyActions()->query, + $actor, + $filter, + $actor instanceof Actor ? function (HistoryEntry $entry) use ($actor): bool { + $store = $this->stores->get(new StoreName($entry->store)); + $key = new Key($entry->key); + $definition = $this->definition($store, $key); + $subject = Subject::of($store->name, $key, new Locale($entry->locale), Scope::fromString($entry->scope)?->owner(), $definition); + + return ! ($subject->sensitive || $entry->oldEncrypted || $entry->newEncrypted) || $this->access->allows($actor, Ability::ViewSensitive, $subject); + } : null, + ); + } + + public function rollback(string $key, int $toVersion): int + { + $target = $this->writeTarget($key); + + try { + return $this->historyActions()->rollback->handle($target, $toVersion, $this->actingAs); + } finally { + $this->resolver->forgetPreloaded($target->store, $this->scope()); + } + } + + public function historyDiff(string $key, int $from, int $to): HistoryDiff + { + return $this->historyActions()->diff->handle($this->writeTarget($key), $from, $to, $this->actingAs); + } + + private function historyActions(): HistoryActions + { + return $this->historyActions ?? throw new LogicException('This settings handle was built without the history actions; resolve Settings from the container.'); + } + private function storeActions(): StoreActions { return $this->storeActions ?? throw new LogicException('This settings handle was built without store actions; resolve Settings from the container.'); @@ -451,6 +499,7 @@ private function with( $this->storeActions, $this->auditQuery, $this->databaseDefinitions, + $this->historyActions, ); } } diff --git a/src/Support/AuditedTransaction.php b/src/Support/AuditedTransaction.php index 2d8de6c..6e75775 100644 --- a/src/Support/AuditedTransaction.php +++ b/src/Support/AuditedTransaction.php @@ -10,7 +10,7 @@ use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\SettingsException; /** diff --git a/src/Support/EventSummary.php b/src/Support/EventSummary.php new file mode 100644 index 0000000..de94ede --- /dev/null +++ b/src/Support/EventSummary.php @@ -0,0 +1,55 @@ + */ + public static function of(object $event): array + { + $summary = []; + + foreach (get_object_vars($event) as $property => $value) { + $name = (string) $property; + match (true) { + $value instanceof Subject => $summary += self::subject($value), + $value instanceof Actor => $summary['actor'] = self::actor($value), + $value instanceof BackedEnum => $summary[$name] = $value->value, + is_scalar($value) || $value === null => $summary[$name] = $value, + default => null, + }; + } + + return $summary; + } + + /** `user::`, `system`, `token::`… */ + public static function actor(Actor $actor): string + { + return $actor->id === null ? $actor->type->value : sprintf('%s:%s:%s', $actor->type->value, $actor->alias ?? '?', $actor->id); + } + + /** @return array */ + private static function subject(Subject $subject): array + { + return [ + 'store' => $subject->store->value, + 'scope' => $subject->scope()->value, + 'key' => $subject->key?->value, + 'locale' => $subject->locale->value, + 'category' => $subject->category, + ]; + } +} diff --git a/src/Testing/SettingsFake.php b/src/Testing/SettingsFake.php index 45f1841..4559706 100644 --- a/src/Testing/SettingsFake.php +++ b/src/Testing/SettingsFake.php @@ -13,15 +13,17 @@ use Illuminate\Contracts\Auth\Authenticatable; use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Audit\AuditQuery; +use Simtabi\Laranail\Settings\Data\HistoryDiff; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Contracts\Settable; use Simtabi\Laranail\Settings\Contracts\Settings; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Data\PromotionReport; +use Simtabi\Laranail\Settings\History\HistoryQuery; use Simtabi\Laranail\Settings\Data\PromotionRequest; use Simtabi\Laranail\Settings\Resolution\Explanation; use Simtabi\Laranail\Settings\Categories\CategoryManager; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** * Installed by `Settings::fake()`: the real engine over in-memory layers, recording writes and @@ -192,6 +194,21 @@ public function audit(): AuditQuery return $this->inner->audit(); } + public function history(): HistoryQuery + { + return $this->inner->history(); + } + + public function rollback(string $key, int $toVersion): int + { + return $this->inner->rollback($key, $toVersion); + } + + public function historyDiff(string $key, int $from, int $to): HistoryDiff + { + return $this->inner->historyDiff($key, $from, $to); + } + public function assertSaved(string $key, mixed ...$value): void { $checksValue = $value !== []; diff --git a/src/deprecated-aliases.php b/src/deprecated-aliases.php new file mode 100644 index 0000000..ac3a6ad --- /dev/null +++ b/src/deprecated-aliases.php @@ -0,0 +1,63 @@ + AuditRepository::class, + Simtabi\Laranail\Settings\Database\CategoryRepository::class => CategoryRepository::class, + Simtabi\Laranail\Settings\Database\DefinitionsRepository::class => DefinitionsRepository::class, + Simtabi\Laranail\Settings\Database\SchemaInspector::class => SchemaInspector::class, + Simtabi\Laranail\Settings\Database\SchemaShapeRepository::class => SchemaShapeRepository::class, + Simtabi\Laranail\Settings\Stores\SettingWriter::class => SettingWriter::class, + Simtabi\Laranail\Settings\Stores\StoreRegistry::class => StoreRegistry::class, + Simtabi\Laranail\Settings\Resolution\Resolver::class => Resolver::class, + Simtabi\Laranail\Settings\Resolution\PreloadedRecords::class => PreloadedRecords::class, + Simtabi\Laranail\Settings\Authorization\AccessGuard::class => AccessGuard::class, + Simtabi\Laranail\Settings\Audit\Auditor::class => Auditor::class, + Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration::class => RuntimeConfiguration::class, + Simtabi\Laranail\Settings\Definitions\DefinitionRegistry::class => DefinitionRegistry::class, + Simtabi\Laranail\Settings\Definitions\DatabaseDefinitions::class => DatabaseDefinitions::class, + Simtabi\Laranail\Settings\Tenancy\TenantDiscriminators::class => TenantDiscriminators::class, + Simtabi\Laranail\Settings\Casting\CasterRegistry::class => CasterRegistry::class, + Simtabi\Laranail\Settings\Support\ValuePipeline::class => ValuePipeline::class, + Simtabi\Laranail\Settings\Drivers\DriverFactory::class => DriverFactory::class, + Simtabi\Laranail\Settings\Caching\SettingsCache::class => SettingsCache::class, +] as $deprecated => $moved) { + if (! class_exists($deprecated, false)) { + class_alias($moved, $deprecated); + } +} diff --git a/tests/Arch/ArchitectureTest.php b/tests/Arch/ArchitectureTest.php index 8ccd55c..5e8a27e 100644 --- a/tests/Arch/ArchitectureTest.php +++ b/tests/Arch/ArchitectureTest.php @@ -74,7 +74,7 @@ } // A scan that inspects nothing has broken, not found a clean tree. - expect($inspected)->toBeGreaterThanOrEqual(110) + expect($inspected)->toBeGreaterThanOrEqual(240) ->and($offending)->toBe([]) ->and(is_dir($root . '/resources/views'))->toBeFalse(); }); diff --git a/tests/Arch/LayeringTest.php b/tests/Arch/LayeringTest.php index 4522246..677be7b 100644 --- a/tests/Arch/LayeringTest.php +++ b/tests/Arch/LayeringTest.php @@ -45,6 +45,7 @@ function classOf(string $path): string 'Actions\\Categories\\CategoryGuard' => 'run(): the guard every category action runs through', 'Actions\\SettingActions' => 'a bundle of the write actions for entry points (using())', 'Actions\\StoreActions' => 'a bundle of the store actions for entry points', + 'Actions\\HistoryActions' => 'a bundle of the history actions for entry points', 'Actions\\Categories\\CategoryActions' => 'a bundle of the category actions for entry points (using())', 'Actions\\QueryAudit' => 'get(), cursor(), paginate(): one authorized read in three result shapes, part of the public API', 'Actions\\PruneOrphans' => 'find(): deprecated in 0.1, forwards to FindOrphans, removed in 1.0', @@ -67,7 +68,7 @@ function classOf(string $path): string } } - expect(count($files))->toBeGreaterThanOrEqual(23) + expect(count($files))->toBeGreaterThanOrEqual(30) ->and(array_keys(array_diff_key($offenders, ACTION_EXEMPTIONS)))->toBe([]) // An exemption that no longer needs to be one is stale. ->and(array_keys(array_diff_key(ACTION_EXEMPTIONS, $offenders)))->toBe([]); @@ -77,12 +78,12 @@ function classOf(string $path): string $files = sourceFiles('Actions'); $offenders = array_keys(array_filter($files, static fn (string $code): bool => preg_match('/->connection\(\)|getSchemaBuilder\(|DB::/', $code) === 1)); - expect(count($files))->toBeGreaterThanOrEqual(23) + expect(count($files))->toBeGreaterThanOrEqual(30) ->and($offenders)->toBe([]); }); it('lets only entry points depend on actions', function (): void { - $entryPoints = ['SettingsManager.php', 'Providers/', 'Facades/', 'Console/', 'Categories/CategoryManager.php', 'Audit/AuditQuery.php']; + $entryPoints = ['SettingsManager.php', 'Providers/', 'Facades/', 'Console/', 'Categories/CategoryManager.php', 'Audit/AuditQuery.php', 'History/HistoryQuery.php']; $files = sourceFiles(''); $offenders = []; @@ -96,7 +97,7 @@ function classOf(string $path): string } } - expect(count($files))->toBeGreaterThanOrEqual(200) + expect(count($files))->toBeGreaterThanOrEqual(240) ->and($offenders)->toBe([]); }); @@ -113,7 +114,7 @@ function classOf(string $path): string } } - expect(count($files))->toBeGreaterThanOrEqual(10) + expect(count($files))->toBeGreaterThanOrEqual(11) ->and(array_values(array_diff($mutable, array_keys($exempt))))->toBe([]) ->and(array_values(array_diff(array_keys($exempt), $mutable)))->toBe([]); }); diff --git a/tests/Arch/ServicesTest.php b/tests/Arch/ServicesTest.php new file mode 100644 index 0000000..93f1efa --- /dev/null +++ b/tests/Arch/ServicesTest.php @@ -0,0 +1,155 @@ + new name. */ +const MOVED_SERVICES = [ + 'Database\\AuditRepository' => 'Services\\Database\\AuditRepository', + 'Database\\CategoryRepository' => 'Services\\Database\\CategoryRepository', + 'Database\\DefinitionsRepository' => 'Services\\Database\\DefinitionsRepository', + 'Database\\SchemaInspector' => 'Services\\Database\\SchemaInspector', + 'Database\\SchemaShapeRepository' => 'Services\\Database\\SchemaShapeRepository', + 'Stores\\SettingWriter' => 'Services\\Stores\\SettingWriter', + 'Stores\\StoreRegistry' => 'Services\\Stores\\StoreRegistry', + 'Resolution\\Resolver' => 'Services\\Resolution\\Resolver', + 'Resolution\\PreloadedRecords' => 'Services\\Resolution\\PreloadedRecords', + 'Authorization\\AccessGuard' => 'Services\\Access\\AccessGuard', + 'Audit\\Auditor' => 'Services\\Access\\Auditor', + 'Configuration\\RuntimeConfiguration' => 'Services\\Configuration\\RuntimeConfiguration', + 'Definitions\\DefinitionRegistry' => 'Services\\Definitions\\DefinitionRegistry', + 'Definitions\\DatabaseDefinitions' => 'Services\\Definitions\\DatabaseDefinitions', + 'Tenancy\\TenantDiscriminators' => 'Services\\Tenancy\\TenantDiscriminators', + 'Casting\\CasterRegistry' => 'Services\\Casting\\CasterRegistry', + 'Support\\ValuePipeline' => 'Services\\Values\\ValuePipeline', + 'Drivers\\DriverFactory' => 'Services\\Drivers\\DriverFactory', + 'Caching\\SettingsCache' => 'Services\\Cache\\SettingsCache', +]; + +/** @return array path relative to src/ => contents */ +function servicesSources(): array +{ + $root = dirname(__DIR__, 2) . '/src/'; + $files = []; + + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)) as $file) { + if ($file instanceof SplFileInfo && $file->getExtension() === 'php' && $file->getFilename() !== 'deprecated-aliases.php') { + $files[substr($file->getPathname(), strlen($root))] = (string) file_get_contents($file->getPathname()); + } + } + + ksort($files); + + return $files; +} + +it('keeps contract implementations out of Services', function (): void { + $services = array_filter(array_keys(servicesSources()), static fn (string $path): bool => str_starts_with($path, 'Services/')); + $offenders = []; + + foreach ($services as $path) { + $class = 'Simtabi\\Laranail\\Settings\\' . str_replace(['/', '.php'], ['\\', ''], $path); + + foreach (PLUGIN_CONTRACTS as $contract) { + if (is_subclass_of($class, $contract)) { + $offenders[] = $class . ' implements ' . $contract; + } + } + } + + expect(count($services))->toBeGreaterThanOrEqual(20) + ->and($offenders)->toBe([]); +}); + +it('files every repository and registry under Services', function (): void { + $files = servicesSources(); + $offenders = array_keys(array_filter( + $files, + static fn (string $code, string $path): bool => ! str_starts_with($path, 'Services/') && preg_match('/^(?:final\s+|readonly\s+|abstract\s+)*class\s+\w+(Repository|Registry)\b/m', $code) === 1, + ARRAY_FILTER_USE_BOTH, + )); + $found = array_keys(array_filter( + $files, + static fn (string $code, string $path): bool => str_starts_with($path, 'Services/') && preg_match('/^(?:final\s+|readonly\s+|abstract\s+)*class\s+\w+(Repository|Registry)\b/m', $code) === 1, + ARRAY_FILTER_USE_BOTH, + )); + + // The positive control: the scan does find the repositories and registries that exist. + expect(count($files))->toBeGreaterThanOrEqual(240) + ->and(count($found))->toBeGreaterThanOrEqual(8) + ->and($offenders)->toBe([]); +}); + +it('aliases exactly the moved classes, and each old name still works', function (): void { + $file = (string) file_get_contents(dirname(__DIR__, 2) . '/src/deprecated-aliases.php'); + preg_match_all('/^\s*(?:\\\\)?Simtabi\\\\Laranail\\\\Settings\\\\([A-Za-z\\\\]+)::class\s*=>/m', $file, $matches); + $aliased = $matches[1]; + $base = 'Simtabi\\Laranail\\Settings\\'; + $broken = []; + + foreach (MOVED_SERVICES as $old => $new) { + $reflection = new ReflectionClass($base . $old); + + if ($reflection->getName() !== $base . $new || ! is_a($base . $new, $base . $old, true)) { + $broken[] = $old; + } + } + + expect(count(MOVED_SERVICES))->toBe(19) + ->and($aliased)->toHaveCount(19) + ->and(array_values(array_diff($aliased, array_keys(MOVED_SERVICES))))->toBe([]) + ->and(array_values(array_diff(array_keys(MOVED_SERVICES), $aliased)))->toBe([]) + ->and($broken)->toBe([]) + // No old file is left behind to shadow the alias. + ->and(array_filter(array_keys(MOVED_SERVICES), static fn (string $old): bool => is_file(dirname(__DIR__, 2) . '/src/' . str_replace('\\', '/', $old) . '.php')))->toBe([]); +}); + +it('keeps an old name working in a type declaration', function (): void { + $accepts = static fn (StoreRegistry $registry): string => $registry::class; + $registry = new Simtabi\Laranail\Settings\Services\Stores\StoreRegistry( + new DriverFactory( + Mockery::mock(Factory::class), + Mockery::mock(Repository::class), + new ReadOnlyValues(new ValueEncoder), + new RecordSerializer, + sys_get_temp_dir(), + ), + 'settings', + ['settings' => ['layers' => []]], + [], + ); + + expect($accepts($registry))->toBe(Simtabi\Laranail\Settings\Services\Stores\StoreRegistry::class); +}); diff --git a/tests/Feature/AccessEventsTest.php b/tests/Feature/AccessEventsTest.php new file mode 100644 index 0000000..f326204 --- /dev/null +++ b/tests/Feature/AccessEventsTest.php @@ -0,0 +1,83 @@ +set('site.name', 'Acme'); + settings()->lock('site.name'); + settings()->unlock('site.name'); + + Event::assertDispatched(SettingLocked::class, static fn (SettingLocked $event): bool => $event->key === 'site.name' && $event->scope === 'global' && $event->version === 2); + Event::assertDispatched(SettingUnlocked::class, static fn (SettingUnlocked $event): bool => $event->version === 3); +}); + +it('announces a refusal at once, with the ability, the subject and the actor', function (): void { + Event::fake([AccessWasDenied::class]); + + expect(fn () => settings()->as(user(5))->set('site.name', 'x'))->toThrow(AccessDenied::class); + + Event::assertDispatched(AccessWasDenied::class, static fn (AccessWasDenied $event): bool => $event->ability === Ability::Update + && $event->subject->key?->value === 'site.name' + && $event->actor?->id === '5' + && $event->refusal === 'access_denied'); +}); + +it('announces a call refused for want of an actor', function (): void { + Event::fake([AccessWasDenied::class]); + settings()->configuration()->requireActor(); + + expect(fn (): mixed => settings()->get('site.name'))->toThrow(ActorRequired::class); + + Event::assertDispatched(AccessWasDenied::class, static fn (AccessWasDenied $event): bool => ! $event->actor instanceof Actor && $event->refusal === 'actor_required'); +}); + +it('announces an actor stopped for step-up verification', function (): void { + Event::fake([VerificationWasRequired::class, AccessWasDenied::class]); + allowGates(Ability::Rollback); + + expect(fn (): int => settings()->as(user())->rollback('site.name', 1))->toThrow(VerificationRequired::class); + + Event::assertDispatched(VerificationWasRequired::class, static fn (VerificationWasRequired $event): bool => $event->ability === Ability::Rollback && $event->actor->id === '1'); + Event::assertNotDispatched(AccessWasDenied::class); +}); + +it('keeps values out of every new event and dispatches the changes after commit', function (): void { + $events = [SettingLocked::class, SettingUnlocked::class, SettingRolledBack::class, AccessWasDenied::class, VerificationWasRequired::class, DefinitionsSynced::class, AuditPruned::class, HistoryPruned::class, OrphansPruned::class, CategoryMoved::class, CategoryRenamed::class]; + $properties = []; + + foreach ($events as $class) { + $properties = [...$properties, ...array_keys(get_class_vars($class))]; + } + + $afterCommit = array_filter($events, static fn (string $class): bool => is_subclass_of($class, ShouldDispatchAfterCommit::class)); + + expect(count($events))->toBe(11) + ->and(array_intersect($properties, ['value', 'payload', 'old_value', 'new_value', 'oldValue', 'newValue']))->toBe([]) + // Refusals are announced at once (the refusal throws and rolls its transaction back). + ->and(array_values(array_diff($events, $afterCommit)))->toBe([AccessWasDenied::class, VerificationWasRequired::class]); +}); diff --git a/tests/Feature/AlertsTest.php b/tests/Feature/AlertsTest.php new file mode 100644 index 0000000..0463f04 --- /dev/null +++ b/tests/Feature/AlertsTest.php @@ -0,0 +1,261 @@ +set('laranail.settings.alerts.enabled', true); + config()->set('laranail.settings.alerts.rules', $rules); + + foreach ($extra as $key => $value) { + config()->set('laranail.settings.' . $key, $value); + } + + app()->getProvider(SettingsServiceProvider::class)?->packageBooted(); +} + +/** @return list every alert sent on demand (to addresses rather than a model) */ +function sentAlerts(): array +{ + return Notification::sent(new AnonymousNotifiable, SettingsAlert::class)->all(); +} + +it('registers no alert listener unless alerts are enabled', function (): void { + $raw = app('events')->getRawListeners(); + + expect(in_array(SendSettingsAlert::class, $raw[SettingSaved::class] ?? [], true))->toBeFalse() + ->and(in_array(LogSettingsEvent::class, $raw[SettingSaved::class] ?? [], true))->toBeFalse(); + + alertOn([], ['listeners.alerts' => false]); + + expect(in_array(SendSettingsAlert::class, app('events')->getRawListeners()[SettingSaved::class] ?? [], true))->toBeFalse(); +}); + +it('mails an alert for a matching change, with identifiers only', function (): void { + Notification::fake(); + alertOn([['events' => ['SettingSaved'], 'keys' => ['mail.*'], 'notify' => ['mail' => ['ops@example.test']]]]); + + settings()->as(user(3))->asSystem('nightly')->set('mail.host', 'smtp.example.test'); + settings()->set('site.name', 'Acme'); + + Notification::assertSentOnDemand(SettingsAlert::class, static fn (SettingsAlert $alert, array $channels, object $notifiable): bool => $channels === ['mail'] + && $notifiable->routes['mail'] === ['ops@example.test'] + && $alert->context->key === 'mail.host' + && $alert->context->event === 'SettingSaved' + && $alert->context->outcome === 'allowed'); + Notification::assertSentOnDemandTimes(SettingsAlert::class, 1); +}); + +it('throttles a rule per key, and alerts again for another key', function (): void { + Notification::fake(); + alertOn([['events' => [SettingSaved::class], 'notify' => ['mail' => ['ops@example.test']]]], ['alerts.cache' => 'array']); + + settings()->set('site.name', 'one'); + settings()->set('site.name', 'two'); + settings()->set('site.url', 'https://example.test'); + + Notification::assertSentOnDemandTimes(SettingsAlert::class, 2); +}); + +it('does not throttle when the throttle is zero', function (): void { + Notification::fake(); + alertOn([['events' => ['SettingSaved'], 'notify' => ['mail' => ['ops@example.test']]]], ['alerts.throttle' => 0]); + + settings()->set('site.name', 'one'); + settings()->set('site.name', 'two'); + + Notification::assertSentOnDemandTimes(SettingsAlert::class, 2); +}); + +it('sends anyway when the throttle cache fails, and logs it', function (): void { + Notification::fake(); + $cache = Mockery::mock(Repository::class); + $cache->shouldReceive('add')->andThrow(new RuntimeException('cache down')); + $logger = alertLogger(); + $listener = new SendSettingsAlert(app(Dispatcher::class), [AlertRule::fromConfig(['events' => ['SettingSaved'], 'notify' => ['mail' => ['ops@example.test']]], 0)], static fn (): bool => false, static fn (): CarbonImmutable => now()->toImmutable(), $logger, $cache, 60); + + $listener->handle(new SettingSaved('settings', 'global', 'site.name', '', 1)); + + Notification::assertSentOnDemandTimes(SettingsAlert::class, 1); + expect($logger->messages)->toHaveCount(1) + ->and($logger->messages[0])->toContain('cache down'); +}); + +it('narrows by store, sensitive keys and outcome', function (): void { + Notification::fake(); + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + alertOn([ + ['events' => ['SettingSaved'], 'stores' => ['billing'], 'notify' => ['mail' => ['billing@example.test']]], + ['events' => ['SettingSaved'], 'sensitive_only' => true, 'notify' => ['mail' => ['security@example.test']]], + ['events' => ['AccessWasDenied', 'SettingSaved'], 'outcomes' => ['denied'], 'notify' => ['mail' => ['denied@example.test']]], + ]); + + settings()->set('site.name', 'Acme'); + settings()->set('mail.password', TestCredentials::secret()); + + expect(fn () => settings()->as(user(4))->set('site.name', 'x'))->toThrow(AccessDenied::class); + + $routes = array_map(static fn (SettingsAlert $alert): string => $alert->context->event . ':' . ($alert->context->key ?? '-') . ':' . $alert->context->outcome, sentAlerts()); + + expect($routes)->toBe(['SettingSaved:mail.password:allowed', 'AccessWasDenied:site.name:denied']); + + $denied = sentAlerts()[1]->context; + + expect($denied->actor)->toStartWith('user:')->toEndWith(':4') + ->and($denied->sensitive)->toBeFalse() + ->and($denied->details)->toMatchArray(['ability' => 'update', 'refusal' => 'access_denied']); +}); + +it('queues the alert on the rule\'s queue', function (): void { + Notification::fake(); + alertOn([['events' => ['SettingLocked'], 'notify' => ['mail' => ['ops@example.test']], 'queue' => 'alerts']]); + + settings()->set('site.name', 'Acme'); + settings()->lock('site.name'); + + $alert = sentAlerts()[0]; + + expect($alert)->toBeInstanceOf(SettingsAlert::class) + ->and($alert->queue)->toBe('alerts') + ->and($alert->context->event)->toBe('SettingLocked') + ->and($alert->context->details)->toBe(['version' => 2]); +}); + +it('routes to Slack only when the Slack channel package is installed', function (): void { + Notification::fake(); + alertOn([['events' => ['SettingSaved'], 'notify' => ['mail' => ['ops@example.test'], 'slack' => 'https://hooks.slack.test/T/B/C']]]); + $installed = class_exists(SettingsAlert::SLACK_MESSAGE); + + settings()->set('site.name', 'Acme'); + + expect(sentAlerts()[0]->channels)->toBe($installed ? ['mail', 'slack'] : ['mail']); + + require_once __DIR__ . '/../Fixtures/Stubs/legacy-slack-message.php'; + settings()->set('site.url', 'https://example.test'); + + $slack = sentAlerts()[1]; + $message = $slack->toSlack(new AnonymousNotifiable); + + expect($slack->channels)->toBe(['mail', 'slack']) + ->and($message?->content ?? null)->toContain('Setting Saved')->toContain('site.url') + ->and(new SettingsAlert($slack->context, ['slack'], 'Nope\\NoSuchMessage')->toSlack(new AnonymousNotifiable))->toBeNull(); +}); + +it('never puts a setting\'s value into any channel of an alert', function (): void { + Notification::fake(); + require_once __DIR__ . '/../Fixtures/Stubs/legacy-slack-message.php'; + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + alertOn([['events' => SendSettingsAlert::EVENTS, 'notify' => ['mail' => ['ops@example.test'], 'slack' => 'https://hooks.slack.test/T/B/C']]], ['alerts.throttle' => 0]); + $secret = TestCredentials::secret('alert'); + + settings()->because('rotate')->set('mail.password', $secret); + settings()->lock('mail.password'); + expect(fn (): mixed => settings()->as(user())->get('mail.password'))->toThrow(AccessDenied::class); + + $alerts = sentAlerts(); + $rendered = ''; + $notifiable = new AnonymousNotifiable; + + foreach ($alerts as $alert) { + $mail = $alert->toMail($notifiable); + $rendered .= $mail->subject . json_encode($mail->toArray()) . $mail->render() + . json_encode($alert->toArray($notifiable)) . json_encode($alert->toDatabase($notifiable)) + . json_encode($alert->toSlack($notifiable)) . serialize($alert); + } + + // Three alerts (saved, locked, denied), each rendered on every channel; none holds the secret. + expect($alerts)->toHaveCount(3) + ->and(strlen($rendered))->toBeGreaterThan(3000) + ->and($rendered)->toContain('mail.password') + ->and($rendered)->not->toContain($secret); +}); + +it('rejects a malformed rule with its config path', function (array $rule, string $message): void { + alertOn([$rule]); + + expect(fn () => app(SendSettingsAlert::class))->toThrow(InvalidConfiguration::class, $message); +})->with([ + 'no events' => [['events' => []], 'rules.0.events: name at least one event'], + 'events not a list' => [['events' => 'SettingSaved'], 'rules.0.events: a list of strings.'], + 'bad keys' => [['events' => ['SettingSaved'], 'keys' => [1]], 'rules.0.keys: a list of strings, or null'], + 'bad sensitive' => [['events' => ['SettingSaved'], 'sensitive_only' => 'yes'], 'rules.0.sensitive_only'], + 'bad notify' => [['events' => ['SettingSaved'], 'notify' => 'ops@example.test'], 'rules.0.notify'], + 'bad slack' => [['events' => ['SettingSaved'], 'notify' => ['slack' => '']], 'rules.0.notify.slack'], + 'bad queue' => [['events' => ['SettingSaved'], 'queue' => 5], 'rules.0.queue'], + 'bad database model' => [['events' => ['SettingSaved'], 'notify' => ['database' => ['type' => stdClass::class, 'id' => 1]]], 'rules.0.notify.database'], +]); + +it('rejects a rule that is not an array', function (): void { + alertOn(['nonsense']); + + expect(fn () => app(SendSettingsAlert::class))->toThrow(InvalidConfiguration::class, 'rules.0: each rule is an array'); +}); + +it('names the event in a headline, with the key when there is one', function (): void { + $at = now()->toImmutable(); + + expect(AlertContext::fromEvent(new SettingSaved('settings', 'global', 'site.name', '', 1), false, $at)->headline())->toBe('laranail/settings: Setting Saved, [site.name] in store settings') + ->and(AlertContext::fromEvent(new AuditPruned(3, 30), false, $at)->headline())->toBe('laranail/settings: Audit Pruned') + ->and(AlertContext::fromEvent(new StorePromoted('settings', 1, 0, null), false, $at)->headline())->toBe('laranail/settings: Store Promoted in store settings'); +}); + +it('logs every settings event when the log listener is on', function (): void { + alertOn([], ['listeners.log' => true, 'alerts.enabled' => false]); + $logger = alertLogger(); + $listener = new LogSettingsEvent($logger); + + expect(in_array(LogSettingsEvent::class, app('events')->getRawListeners()[SettingSaved::class] ?? [], true))->toBeTrue(); + + $listener->handle(new SettingSaved('settings', 'global', 'site.name', '', 2)); + $listener->handle(new AccessWasDenied(Ability::View, new Subject(new StoreName('settings')), null, 'actor_required')); + + expect($logger->messages)->toBe([ + 'info laranail/settings event: SettingSaved {"store":"settings","scope":"global","key":"site.name","locale":"","version":2}', + 'warning laranail/settings event: AccessWasDenied {"ability":"view","store":"settings","scope":"global","key":null,"locale":"","category":null,"actor":null,"refusal":"actor_required","reason":null}', + ]); +}); + +function alertLogger(): AbstractLogger +{ + return new class extends AbstractLogger + { + /** @var list */ + public array $messages = []; + + public function log($level, string|Stringable|\Stringable $message, array $context = []): void + { + $this->messages[] = trim(sprintf('%s %s %s', is_string($level) ? $level : '', $message, $context === [] ? '' : json_encode($context))); + } + }; +} diff --git a/tests/Feature/AuditAndLoggingTest.php b/tests/Feature/AuditAndLoggingTest.php index cb503c4..0999d41 100644 --- a/tests/Feature/AuditAndLoggingTest.php +++ b/tests/Feature/AuditAndLoggingTest.php @@ -22,9 +22,9 @@ use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Simtabi\Laranail\Settings\Tests\Fixtures\TestUser; use Simtabi\Laranail\Settings\Logging\OperationalLogger; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** Point the package log at a Monolog test handler and return the handler. */ function captureLog(): TestHandler diff --git a/tests/Feature/Database/AlertsDatabaseTest.php b/tests/Feature/Database/AlertsDatabaseTest.php new file mode 100644 index 0000000..0c981fa --- /dev/null +++ b/tests/Feature/Database/AlertsDatabaseTest.php @@ -0,0 +1,89 @@ + 'bigint']); + DB::table('test_users')->insert(['id' => 1, 'name' => 'Ada']); +}); + +function databaseAlerts(int|string $id, ?string $queue = null): void +{ + config()->set('laranail.settings.alerts.enabled', true); + config()->set('laranail.settings.alerts.rules', [[ + 'events' => ['SettingSaved'], + 'notify' => ['database' => ['type' => TestUser::class, 'id' => $id]], + 'queue' => $queue, + ]]); + app()->getProvider(SettingsServiceProvider::class)?->packageBooted(); +} + +it('notifies the database notifiable a rule names', function (): void { + Notification::fake(); + databaseAlerts(1, 'alerts'); + + settings()->set('site.name', 'Acme'); + + Notification::assertSentTo(TestUser::query()->findOrFail(1), SettingsAlert::class, static fn (SettingsAlert $alert, array $channels): bool => $channels === ['database'] + && $alert->queue === 'alerts' + && $alert->toDatabase(new stdClass)['key'] === 'site.name'); + Notification::assertNothingSentTo(new AnonymousNotifiable); +}); + +it('skips a database notifiable that does not exist, and the write still succeeds', function (): void { + Notification::fake(); + databaseAlerts(99); + + settings()->set('site.name', 'Acme'); + + Notification::assertNothingSent(); + expect(settings()->get('site.name'))->toBe('Acme'); +}); + +it('logs an alert that cannot be sent instead of failing the write', function (): void { + Notification::fake(); + $logged = new class extends AbstractLogger + { + /** @var list */ + public array $messages = []; + + public function log($level, string|Stringable $message, array $context = []): void + { + $this->messages[] = $level . ' ' . $message; + } + }; + settings()->configuration()->logTo($logged); + databaseAlerts(1); + Schema::drop('test_users'); + + settings()->set('site.name', 'Acme'); + + expect(settings()->get('site.name'))->toBe('Acme'); + Notification::assertNothingSent(); + expect($logged->messages)->toHaveCount(1) + ->and($logged->messages[0])->toStartWith('error laranail/settings: alert rule 0 could not be sent'); +}); + +it('sends nothing when alerts are on but no rule is configured', function (): void { + Notification::fake(); + config()->set('laranail.settings.alerts.enabled', true); + app()->getProvider(SettingsServiceProvider::class)?->packageBooted(); + + settings()->set('site.name', 'Acme'); + + Notification::assertNothingSent(); +}); diff --git a/tests/Feature/Database/AuditTableTest.php b/tests/Feature/Database/AuditTableTest.php index 3a4f12d..5fde82f 100644 --- a/tests/Feature/Database/AuditTableTest.php +++ b/tests/Feature/Database/AuditTableTest.php @@ -11,7 +11,7 @@ use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; beforeEach(function (): void { useDatabase(); diff --git a/tests/Feature/Database/BootstrapAndPromotionTest.php b/tests/Feature/Database/BootstrapAndPromotionTest.php index c0801ae..1b795a8 100644 --- a/tests/Feature/Database/BootstrapAndPromotionTest.php +++ b/tests/Feature/Database/BootstrapAndPromotionTest.php @@ -12,7 +12,6 @@ use Simtabi\Laranail\Settings\Data\PromotionReport; use Simtabi\Laranail\Settings\Events\StorePromoted; use Simtabi\Laranail\Settings\Data\PromotionRequest; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Simtabi\Laranail\Settings\Exceptions\PromotionLocked; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; @@ -20,7 +19,8 @@ use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; use Simtabi\Laranail\Settings\Exceptions\DriverUnavailable; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** A store in bootstrap mode whose database layer points at a database that does not exist yet. */ function bootstrapWithoutDatabase(bool $evidence): void diff --git a/tests/Feature/Database/CachingTest.php b/tests/Feature/Database/CachingTest.php index 4bd38c8..81bb4e6 100644 --- a/tests/Feature/Database/CachingTest.php +++ b/tests/Feature/Database/CachingTest.php @@ -19,15 +19,15 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Drivers\JsonDriver; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Illuminate\Database\Eloquent\Relations\Relation; -use Simtabi\Laranail\Settings\Caching\SettingsCache; use Simtabi\Laranail\Settings\Drivers\CachingDriver; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Illuminate\Support\Defer\DeferredCallbackCollection; +use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; use Simtabi\Laranail\Settings\Tests\Fixtures\SettingsOwner; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; /* diff --git a/tests/Feature/Database/CategoriesTest.php b/tests/Feature/Database/CategoriesTest.php index 08282fd..e6f832c 100644 --- a/tests/Feature/Database/CategoriesTest.php +++ b/tests/Feature/Database/CategoriesTest.php @@ -14,8 +14,8 @@ use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; beforeEach(function (): void { useDatabase(['stores.billing' => ['layers' => ['database']]], stores: ['billing']); diff --git a/tests/Feature/Database/CommandsTest.php b/tests/Feature/Database/CommandsTest.php index 4a016da..92a0444 100644 --- a/tests/Feature/Database/CommandsTest.php +++ b/tests/Feature/Database/CommandsTest.php @@ -10,8 +10,8 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Actions\MakeStore; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; // Writes into the testbench application shared by every process (config/, database/), so it // cannot run beside itself in parallel; the parallel mutation run leaves this group out. diff --git a/tests/Feature/Database/DatabaseLayerTest.php b/tests/Feature/Database/DatabaseLayerTest.php index ebfe3a2..9495736 100644 --- a/tests/Feature/Database/DatabaseLayerTest.php +++ b/tests/Feature/Database/DatabaseLayerTest.php @@ -11,16 +11,16 @@ use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\LayerConfig; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Exceptions\DriverUnavailable; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; function databaseDriver(bool $writable = true): DatabaseDriver { diff --git a/tests/Feature/Database/DedicatedStoreTest.php b/tests/Feature/Database/DedicatedStoreTest.php index 700d597..aaec2a6 100644 --- a/tests/Feature/Database/DedicatedStoreTest.php +++ b/tests/Feature/Database/DedicatedStoreTest.php @@ -5,8 +5,8 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Simtabi\Laranail\Settings\Data\OwnerRef; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; function useDedicatedStore(array $extra = []): void diff --git a/tests/Feature/Database/DefinitionsTableTest.php b/tests/Feature/Database/DefinitionsTableTest.php index 6879a22..f665805 100644 --- a/tests/Feature/Database/DefinitionsTableTest.php +++ b/tests/Feature/Database/DefinitionsTableTest.php @@ -12,9 +12,9 @@ use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** Insert a definition row edited at runtime (not is_system). */ function runtimeDefinition(string $key, array $columns = []): void diff --git a/tests/Feature/Database/GovernanceEventsTest.php b/tests/Feature/Database/GovernanceEventsTest.php new file mode 100644 index 0000000..c4b2770 --- /dev/null +++ b/tests/Feature/Database/GovernanceEventsTest.php @@ -0,0 +1,59 @@ +categories(); + + $categories->create(new NewCategory('mail', 'Mail')); + $categories->create(new NewCategory('smtp', 'SMTP')); + $categories->move('smtp', 'mail'); + $categories->move('smtp', null); + $categories->rename('mail', 'Email'); + + Event::assertDispatchedTimes(CategorySaved::class, 5); + Event::assertDispatched(CategoryMoved::class, static fn (CategoryMoved $event): bool => $event->slug === 'smtp' && $event->parent === 'mail' && $event->store === 'settings'); + Event::assertDispatched(CategoryMoved::class, static fn (CategoryMoved $event): bool => $event->parent === null); + Event::assertDispatched(CategoryRenamed::class, static fn (CategoryRenamed $event): bool => $event->slug === 'mail'); +}); + +it('announces a definitions sync with its counts', function (): void { + useDatabase(['definitions.table' => true]); + Event::fake([DefinitionsSynced::class]); + app(DefinitionRegistry::class)->define('site.name')->register(); + app(DefinitionRegistry::class)->define('site.url')->register(); + + app(SyncDefinitions::class)->handle(); + + Event::assertDispatched(DefinitionsSynced::class, static fn (DefinitionsSynced $event): bool => $event->synced === 2 && $event->removed === 0 && $event->conflicts === 0 && $event->skipped === 0); +}); + +it('announces an audit prune with what it removed and the period', function (): void { + useDatabase(); + Event::fake([AuditPruned::class]); + $this->travelTo(now()->subDays(40)); + settings()->set('site.name', 'Acme'); + $this->travelBack(); + + app(PruneAudit::class)->handle(30); + + Event::assertDispatched(AuditPruned::class, static fn (AuditPruned $event): bool => $event->removed === 1 && $event->keepDays === 30); +}); diff --git a/tests/Feature/Database/HandlesTest.php b/tests/Feature/Database/HandlesTest.php index eeb869e..0f181fa 100644 --- a/tests/Feature/Database/HandlesTest.php +++ b/tests/Feature/Database/HandlesTest.php @@ -12,14 +12,14 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Facades\Settings; use Simtabi\Laranail\Settings\Data\PromotionReport; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Data\PromotionRequest; use Simtabi\Laranail\Settings\Drivers\CachingDriver; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Stores\InstallationEvidence; use Simtabi\Laranail\Settings\Drivers\BootstrapGatedDriver; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; it('flushes one owner\'s values from every writable layer and leaves others alone', function (): void { useDatabase(['stores.settings.owners' => ['user']]); diff --git a/tests/Feature/Database/HistoryTest.php b/tests/Feature/Database/HistoryTest.php new file mode 100644 index 0000000..6c4136f --- /dev/null +++ b/tests/Feature/Database/HistoryTest.php @@ -0,0 +1,406 @@ + operation:version, newest first */ +function trail(string $key, ?OwnerRef $owner = null): array +{ + $history = $owner instanceof OwnerRef ? settings()->for($owner)->history() : settings()->history()->global(); + + return array_map(static fn (HistoryEntry $entry): string => $entry->operation->value . ':' . $entry->version, $history->key($key)->get()); +} + +it('records every change with the payload before and after, the causer and the reason', function (): void { + allowGates(Ability::Update, Ability::Lock, Ability::Unlock); + + settings()->set('site.name', 'Acme'); + settings()->as(user(7))->because('INC-9')->set('site.name', 'Acme Ltd'); + settings()->lock('site.name'); + settings()->unlock('site.name'); + + $entries = settings()->history()->key('site.name')->get(); + $update = $entries[2]; + + expect(trail('site.name'))->toBe(['unlock:4', 'lock:3', 'set:2', 'set:1']) + ->and($update->oldValue)->toBe('"Acme"') + ->and($update->newValue)->toBe('"Acme Ltd"') + ->and($update->causerType->value)->toBe('user') + ->and($update->causerId)->toBe('7') + ->and($update->reason)->toBe('INC-9') + ->and($update->settingRef)->toBe(DB::table('settings')->where('key', 'site.name')->value('uid')) + ->and($entries[3]->oldValue)->toBeNull() + ->and($entries[3]->causerType->value)->toBe('system') + ->and($entries[0]->newValue)->toBe('"Acme Ltd"'); +}); + +it('keeps encrypted values encrypted in the history', function (): void { + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + $secret = TestCredentials::secret('history'); + + settings()->set('mail.password', $secret); + + $row = DB::table('settings_history')->where('key', 'mail.password')->first(); + $entry = settings()->history()->key('mail.password')->get()[0]; + + expect(json_encode($row))->not->toContain($secret) + ->and((bool) $row?->new_encrypted)->toBeTrue() + ->and($row?->new_value)->toBe(DB::table('settings')->where('key', 'mail.password')->value('value')) + ->and($entry->toArray()['new_value'])->toBeNull() + ->and($entry->toArray()['new_encrypted'])->toBeTrue(); +}); + +it('writes a tombstone on forget and continues the version when the key is set again', function (): void { + $user = new OwnerRef('user', 1); + config()->set('laranail.settings.stores.settings.owners', ['user']); + + settings()->for($user)->set('theme', 'dark'); + settings()->for($user)->forget('theme'); + settings()->for($user)->set('theme', 'light'); + + $tombstone = settings()->for($user)->history()->key('theme')->versions(1, 1)->get()[0]; + + expect(trail('theme', $user))->toBe(['set:2', 'forget:1', 'set:1']) + ->and($tombstone->operation)->toBe(HistoryOperation::Forget) + ->and($tombstone->newValue)->toBeNull() + ->and($tombstone->oldValue)->toBe('"dark"') + ->and((int) DB::table('settings')->where('key', 'theme')->value('version'))->toBe(2); +}); + +it('rolls the change back when its history entry cannot be written', function (): void { + settings()->set('site.name', 'Acme'); + Schema::drop('settings_history'); + + expect(fn () => settings()->set('site.name', 'Changed'))->toThrow(DriverUnavailable::class); + + // The row write ran inside the same transaction, so it is gone too. + expect(DB::table('settings')->where('key', 'site.name')->value('value'))->toBe('"Acme"') + ->and((int) DB::table('settings')->where('key', 'site.name')->value('version'))->toBe(1) + ->and(DB::table('settings_audit')->where('action', 'update')->where('outcome', 'failed')->count())->toBe(1); +}); + +it('rolls a forget back when its tombstone cannot be written', function (): void { + settings()->set('site.name', 'Acme'); + DB::statement('drop table settings_history'); + + expect(fn () => settings()->forget('site.name'))->toThrow(DriverUnavailable::class) + ->and(settings()->get('site.name'))->toBe('Acme'); +}); + +it('rolls a setting back to an earlier version through the write pipeline', function (): void { + Event::fake([SettingRolledBack::class]); + settings()->set('site.name', 'Acme'); + settings()->set('site.name', 'Acme Ltd'); + + $version = settings()->because('revert INC-9')->rollback('site.name', 1); + $latest = settings()->history()->key('site.name')->get(1)[0]; + + expect($version)->toBe(3) + ->and(settings()->get('site.name'))->toBe('Acme') + ->and($latest->operation)->toBe(HistoryOperation::Rollback) + ->and($latest->oldValue)->toBe('"Acme Ltd"') + ->and($latest->newValue)->toBe('"Acme"') + ->and($latest->reason)->toBe('revert INC-9') + ->and(DB::table('settings_audit')->where('action', 'rollback')->where('outcome', 'allowed')->value('version_to'))->toEqual(3); + + Event::assertDispatched(SettingRolledBack::class, static fn (SettingRolledBack $event): bool => $event->key === 'site.name' && $event->toVersion === 1 && $event->version === 3); +}); + +it('rolls back an encrypted setting without exposing the value', function (): void { + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + $first = TestCredentials::secret('first'); + $second = TestCredentials::secret('second'); + expect($first)->not->toBe($second); + + settings()->set('mail.password', $first); + settings()->set('mail.password', $second); + settings()->rollback('mail.password', 1); + + expect(settings()->get('mail.password'))->toBe($first) + ->and(json_encode(DB::table('settings_history')->get()))->not->toContain($first) + ->and(json_encode(DB::table('settings_audit')->get()))->not->toContain($first); +}); + +it('refuses a rollback to a version the history does not hold, or to a tombstone', function (): void { + settings()->set('site.name', 'Acme'); + settings()->forget('site.name'); + settings()->set('site.name', 'Again'); + + expect(fn (): int => settings()->rollback('site.name', 9))->toThrow(HistoryUnavailable::class, 'no value at version 9') + // Version 1 holds a value (the first set) even though a tombstone shares its number. + ->and(settings()->rollback('site.name', 1))->toBe(3) + ->and(settings()->get('site.name'))->toBe('Acme'); +}); + +it('gates a rollback by the rollback ability and step-up verification', function (): void { + settings()->set('site.name', 'Acme'); + settings()->set('site.name', 'Acme Ltd'); + + expect(fn (): int => settings()->as(user())->rollback('site.name', 1))->toThrow(AccessDenied::class, '[rollback]'); + + allowGates(Ability::Rollback); + + // rollback is in verification.abilities by default, and the user has not confirmed a password. + expect(fn (): int => settings()->as(user())->rollback('site.name', 1))->toThrow(VerificationRequired::class); + + config()->set('laranail.settings.verification.driver', 'actor'); + app()->forgetScopedInstances(); + allowGates(Ability::Rollback); + $verified = Actor::user(user())->withVerifiedAt(now()->toImmutable()); + + expect(settings()->as($verified)->rollback('site.name', 1))->toBe(3) + ->and(DB::table('settings_audit')->where('action', 'rollback')->where('outcome', 'denied')->count())->toBe(2) + ->and(DB::table('settings_audit')->where('action', 'rollback')->where('outcome', 'allowed')->value('actor_id'))->toBe('1'); +}); + +it('refuses a rollback over a locked row', function (): void { + settings()->set('site.name', 'Acme'); + settings()->set('site.name', 'Acme Ltd'); + settings()->lock('site.name'); + + expect(fn (): int => settings()->rollback('site.name', 1))->toThrow(LockedSetting::class) + ->and(settings()->get('site.name'))->toBe('Acme Ltd'); +}); + +it('diffs two versions, and decrypts only for an actor who may view the value', function (): void { + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + $first = TestCredentials::secret('first'); + $second = TestCredentials::secret('second'); + + settings()->set('mail.password', $first); + settings()->set('mail.password', $second); + settings()->set('site.name', 'Acme'); + settings()->set('site.name', 'Acme'); + + $trusted = settings()->historyDiff('mail.password', 1, 2); + + allowGates(Ability::ViewHistory); + $redacted = settings()->as(user())->historyDiff('mail.password', 1, 2); + + allowGates(Ability::ViewSensitive); + $revealed = settings()->as(user())->historyDiff('mail.password', 1, 2); + $plain = settings()->historyDiff('site.name', 1, 2); + + expect([$trusted->from, $trusted->to, $trusted->redacted, $trusted->encrypted])->toBe([$first, $second, false, true]) + ->and([$redacted->from, $redacted->to, $redacted->redacted, $redacted->changed])->toBe([null, null, true, true]) + ->and([$revealed->from, $revealed->to])->toBe([$first, $second]) + ->and([$plain->from, $plain->to, $plain->changed, $plain->fromFound])->toBe(['Acme', 'Acme', false, true]) + ->and(fn (): HistoryDiff => settings()->historyDiff('site.name', 1, 5))->toThrow(HistoryUnavailable::class, 'no version 5'); +}); + +it('needs view_history to read the history, and hides protected payloads from an actor without view_sensitive', function (): void { + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + settings()->set('mail.password', TestCredentials::secret()); + settings()->set('site.name', 'Acme'); + + expect(fn (): array => settings()->as(user())->history()->get())->toThrow(AccessDenied::class, '[view_history]'); + + allowGates(Ability::ViewHistory); + $entries = settings()->as(user())->history()->get(); + $byKey = array_column(array_map(static fn (HistoryEntry $entry): array => [$entry->key, $entry], $entries), 1, 0); + + expect($byKey['mail.password']->newValue)->toBeNull() + ->and($byKey['site.name']->newValue)->toBe('"Acme"'); + + allowGates(Ability::ViewSensitive); + + expect(settings()->as(user())->history()->key('mail.password')->get()[0]->newValue)->not->toBeNull(); +}); + +it('filters by owner, locale, time and version, and pages with a cursor', function (): void { + config()->set('laranail.settings.stores.settings.owners', ['user']); + $user = new OwnerRef('user', 2); + app(DefinitionRegistry::class)->define('greeting')->localised()->register(); + + $this->travelTo(now()->subDay()); + settings()->set('site.name', 'v1'); + $this->travelBack(); + + foreach (range(2, 5) as $n) { + settings()->set('site.name', 'v' . $n); + } + + settings()->for($user)->set('site.name', 'mine'); + settings()->locale('fr')->set('greeting', 'Bonjour'); + + $first = settings()->history()->global()->key('site.name')->paginate(2); + $second = settings()->history()->global()->key('site.name')->paginate(2, $first->nextCursor); + + expect(settings()->history()->global()->key('site.name')->versions(2, 3)->get())->toHaveCount(2) + ->and(settings()->history()->global()->key('site.name')->since(now()->subHour())->get())->toHaveCount(4) + ->and(settings()->history()->global()->key('site.name')->until(now()->subHour())->get())->toHaveCount(1) + ->and(settings()->for($user)->history()->get())->toHaveCount(1) + ->and(settings()->history()->for($user)->key('site.name')->get()[0]->scope)->toBe('user:2') + ->and(settings()->locale('fr')->history()->get()[0]->key)->toBe('greeting') + ->and(settings()->history()->locale('fr')->filter()->locale?->value)->toBe('fr') + ->and(array_map(static fn (HistoryEntry $entry): int => $entry->version, $first->entries))->toBe([5, 4]) + ->and($first->hasMore())->toBeTrue() + ->and(array_map(static fn (HistoryEntry $entry): int => $entry->version, $second->entries))->toBe([3, 2]) + ->and(settings()->history()->store('settings')->global()->key('site.name')->cursor()->count())->toBe(5); +}); + +it('keeps no history when the schema was recorded without the table', function (): void { + useDatabase(['history.enabled' => false]); + + settings()->set('site.name', 'Acme'); + settings()->set('site.name', 'Acme Ltd'); + settings()->forget('site.name'); + settings()->set('site.name', 'Again'); + + expect(Schema::hasTable('settings_history'))->toBeFalse() + ->and((int) DB::table('settings')->where('key', 'site.name')->value('version'))->toBe(1) + ->and(fn (): array => settings()->history()->get())->toThrow(HistoryUnavailable::class, 'keeps no history') + ->and(fn (): int => settings()->rollback('site.name', 1))->toThrow(HistoryUnavailable::class, 'cannot be rolled back') + ->and(fn (): HistoryDiff => settings()->historyDiff('site.name', 1, 1))->toThrow(HistoryUnavailable::class, 'keeps no history'); +}); + +it('rejects a malformed history row rather than inventing an entry', function (): void { + settings()->set('site.name', 'Acme'); + DB::table('settings_history')->update(['operation' => 'teleport']); + + expect(fn (): array => settings()->history()->get())->toThrow(DriverFailure::class, 'is malformed'); +}); + +it('prunes history by age and by versions kept, audits the prune and announces it', function (): void { + Event::fake([HistoryPruned::class]); + $this->travelTo(now()->subDays(40)); + settings()->set('old.key', 'x'); + $this->travelBack(); + + foreach (range(1, 5) as $n) { + settings()->set('site.name', 'v' . $n); + } + + $byAge = app(PruneHistory::class)->handle(30, null); + $byVersions = app(PruneHistory::class)->handle(null, 2); + + expect($byAge)->toBe(1) + ->and($byVersions)->toBe(3) + ->and(trail('site.name'))->toBe(['set:5', 'set:4']) + ->and(DB::table('settings_audit')->where('action', 'prune')->count())->toBe(2) + ->and(fn () => app(PruneHistory::class)->handle(null, null))->toThrow(InvalidConfiguration::class, 'keep_days, keep_versions or both') + ->and(fn () => app(PruneHistory::class)->handle(0, null))->toThrow(InvalidConfiguration::class, 'keep_days: [0]'); + + Event::assertDispatched(HistoryPruned::class, static fn (HistoryPruned $event): bool => $event->removed === 3 && $event->keepVersions === 2 && $event->keepDays === null); +}); + +it('needs prune to prune the history', function (): void { + expect(fn () => app(PruneHistory::class)->handle(30, null, Actor::user(user())))->toThrow(AccessDenied::class, '[prune]'); +}); + +it('lists, diffs and rolls back from the history command', function (): void { + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + $secret = TestCredentials::secret('command'); + settings()->set('site.name', 'Acme'); + settings()->set('site.name', 'Acme Ltd'); + settings()->set('mail.password', $secret); + settings()->set('mail.password', TestCredentials::secret('other')); + + $list = Artisan::call('laranail::settings.history', ['key' => 'site.name']); + $listed = Artisan::output(); + $diff = Artisan::call('laranail::settings.history', ['key' => 'site.name', '--diff' => '1..2']); + $diffed = Artisan::output(); + Artisan::call('laranail::settings.history', ['key' => 'mail.password', '--diff' => '1..2']); + $hidden = Artisan::output(); + Artisan::call('laranail::settings.history', ['key' => 'mail.password', '--diff' => '1..2', '--reveal' => true]); + $revealed = Artisan::output(); + $rollback = Artisan::call('laranail::settings.history', ['key' => 'site.name', '--rollback' => '1']); + $rolled = Artisan::output(); + + expect([$list, $diff, $rollback])->toBe([0, 0, 0]) + ->and($listed)->toContain('set')->toContain('system') + ->and($diffed)->toContain('v1: "Acme"')->toContain('v2: "Acme Ltd"')->toContain('The value changed.') + ->and($hidden)->toContain('[protected]')->not->toContain($secret) + ->and($revealed)->toContain($secret) + ->and($rolled)->toContain('now at version 3') + ->and(settings()->get('site.name'))->toBe('Acme') + ->and(DB::table('settings_audit')->where('action', 'rollback')->value('reason'))->toBe('laranail::settings.history'); +}); + +it('reports bad history command input and an empty history', function (): void { + config()->set('laranail.settings.stores.settings.owners', ['user']); + + expect(Artisan::call('laranail::settings.history', ['key' => 'nothing.here']))->toBe(0) + ->and(Artisan::output())->toContain('No history for [nothing.here]') + ->and(Artisan::call('laranail::settings.history', ['key' => 'site.name', '--diff' => '1-2']))->toBe(1) + ->and(Artisan::output())->toContain('FROM..TO') + ->and(Artisan::call('laranail::settings.history', ['key' => 'site.name', '--rollback' => 'x']))->toBe(1) + ->and(Artisan::output())->toContain('version number') + ->and(Artisan::call('laranail::settings.history', ['key' => 'site.name', '--rollback' => '4']))->toBe(1) + ->and(Artisan::output())->toContain('no value at version 4') + ->and(Artisan::call('laranail::settings.history', ['key' => 'site.name', '--owner' => 'nonsense']))->toBe(1) + ->and(Artisan::output())->toContain('alias:id') + ->and(Artisan::call('laranail::settings.history', ['key' => 'site.name', '--owner' => 'user:3', '--store' => 'settings', '--locale' => 'fr', '--limit' => '5']))->toBe(0); +}); + +it('prunes from the prune-history command with the configured or given retention', function (): void { + foreach (range(1, 4) as $n) { + settings()->set('site.name', 'v' . $n); + } + + config()->set('laranail.settings.history.keep_days'); + config()->set('laranail.settings.history.keep_versions'); + + expect(Artisan::call('laranail::settings.prune-history'))->toBe(0) + ->and(Artisan::output())->toContain('nothing to prune') + ->and(Artisan::call('laranail::settings.prune-history', ['--versions' => 'many']))->toBe(1) + ->and(Artisan::call('laranail::settings.prune-history', ['--versions' => '0']))->toBe(1) + ->and(Artisan::output())->toContain('at least 1') + ->and(Artisan::call('laranail::settings.prune-history', ['--versions' => '1', '--days' => '30']))->toBe(0) + ->and(Artisan::output())->toContain('Removed 3 history entries') + ->and(DB::table('settings_audit')->where('action', 'prune')->value('actor_type'))->toBe('system'); + + config()->set('laranail.settings.history.keep_versions', 1); + + expect(Artisan::call('laranail::settings.prune-history'))->toBe(0) + ->and(Artisan::output())->toContain('Removed 0 history entries'); +}); + +it('records the tenant on history rows and reads only the current tenant\'s', function (): void { + useDatabase(['tenancy.mode' => 'column']); + app()->instance(TenantDiscriminator::class, new ClosureTenantDiscriminator(static fn (): string => 'acme')); + + settings()->set('site.name', 'Acme'); + $row = (array) DB::table('settings_history')->first(); + DB::table('settings_history')->insert(['id' => (string) Str::ulid(), 'tenant' => 'other'] + $row); + + expect(DB::table('settings_history')->orderBy('tenant')->pluck('tenant')->all())->toBe(['acme', 'other']) + ->and(settings()->history()->get())->toHaveCount(1) + // Retention is application-wide: each tenant keeps its own newest version. + ->and(app(PruneHistory::class)->handle(null, 1))->toBe(0); +}); diff --git a/tests/Feature/Database/MigrationTest.php b/tests/Feature/Database/MigrationTest.php index cd26450..b3f3acb 100644 --- a/tests/Feature/Database/MigrationTest.php +++ b/tests/Feature/Database/MigrationTest.php @@ -6,10 +6,10 @@ use Illuminate\Support\Facades\Schema; use Illuminate\Database\Migrations\Migration; use Simtabi\Laranail\Settings\Database\SchemaNames; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; -use Simtabi\Laranail\Settings\Database\SchemaInspector; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; /* * The package's one migration: every table, in dependency order, for every recorded database diff --git a/tests/Feature/Database/OwnersTest.php b/tests/Feature/Database/OwnersTest.php index 5a4de87..17f74a2 100644 --- a/tests/Feature/Database/OwnersTest.php +++ b/tests/Feature/Database/OwnersTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Simtabi\Laranail\Settings\Data\Actor; @@ -11,6 +12,7 @@ use Simtabi\Laranail\Settings\Actions\PruneAudit; use Simtabi\Laranail\Settings\Actions\FindOrphans; use Simtabi\Laranail\Settings\Actions\PruneOrphans; +use Simtabi\Laranail\Settings\Events\OrphansPruned; use Illuminate\Database\Eloquent\Relations\Relation; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; @@ -127,6 +129,7 @@ }); it('needs prune (and forget) to prune orphans with an actor, and audits the run', function (): void { + Event::fake([OrphansPruned::class]); $gone = SettingsOwner::query()->create(); $gone->settings()->set('ui.theme', 'dark'); SettingsOwner::query()->whereKey($gone->id)->delete(); @@ -141,6 +144,9 @@ expect($prune->handle($actor))->toBe(1) ->and(json_decode((string) DB::table('settings_audit')->where('action', 'prune')->where('outcome', 'allowed')->value('meta'), true))->toMatchArray(['owners' => 1]) ->and(DB::table('settings_audit')->where('action', 'prune')->where('outcome', 'denied')->count())->toBe(1); + + Event::assertDispatchedTimes(OrphansPruned::class, 1); + Event::assertDispatched(OrphansPruned::class, static fn (OrphansPruned $event): bool => $event->owners === 1 && $event->rows === 1); }); it('finds orphans with FindOrphans, and through the deprecated PruneOrphans::find()', function (): void { diff --git a/tests/Feature/Database/SchemaMatrixTest.php b/tests/Feature/Database/SchemaMatrixTest.php index 69e114b..b607c58 100644 --- a/tests/Feature/Database/SchemaMatrixTest.php +++ b/tests/Feature/Database/SchemaMatrixTest.php @@ -3,15 +3,17 @@ declare(strict_types=1); use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Artisan; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Data\NewCategory; +use Simtabi\Laranail\Settings\Data\HistoryEntry; use Simtabi\Laranail\Settings\Tests\Support\Pairwise; use Simtabi\Laranail\Settings\Actions\SyncDefinitions; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* * §13: the schema switches, kept tested. Every pair of switch values meets in at least one shape @@ -35,6 +37,7 @@ function switchFactors(): array 'definitions_table' => [false, true], 'categories_soft_deletes' => [false, true], 'tenancy' => ['none', 'column'], + 'history' => [true, false], ]; } @@ -63,9 +66,10 @@ function switchShapes(): array } // 141 pairs among the eight Phase 2b switches, plus tenancy's 2 values × the other 18 - // values = 177; the full product doubles from 576 to 1,152. - expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 1152 : 10) - ->and(count($all))->toBe(177) + // values = 177, plus history's 2 values × the other 20 values = 217 (Phase 4); the full + // product doubles from 1,152 to 2,304, and the pairwise set grows from 10 shapes to 11. + expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 2304 : 11) + ->and(count($all))->toBe(217) ->and(array_diff_key($all, $covered))->toBe([]); })->group('matrix', 'mutation-excluded'); @@ -81,6 +85,7 @@ function switchShapes(): array 'definitions.table' => $shape['definitions_table'], 'categories.soft_deletes' => $shape['categories_soft_deletes'], 'tenancy.mode' => $shape['tenancy'], + 'history.enabled' => $shape['history'], 'stores.settings.owners' => $dedicated ? [] : ['user'], 'stores.settings.soft_deletes' => $shape['soft_deletes'], 'stores.settings.inherits' => true, @@ -125,6 +130,9 @@ function switchShapes(): array expect(app(SyncDefinitions::class)->handle()['synced'])->toBe(1); } + // History (§4.3): the forget left a tombstone, so the row created again continued the trail. + $trail = $shape['history'] ? settings()->for($user)->history()->key('theme')->get() : []; + $exit = Artisan::call('laranail::settings.doctor', ['--json' => true]); $report = Artisan::output(); @@ -132,7 +140,11 @@ function switchShapes(): array ->and(settings()->for($user)->get('theme'))->toBe('light') ->and(settings()->for($user)->get('site.name'))->toBe('Acme') ->and(DB::table($ownerStore)->where('scope', 'user:1')->count())->toBe(1) - ->and((int) DB::table($ownerStore)->where('scope', 'user:1')->value('version'))->toBe($shape['soft_deletes'] ? 4 : 3) + ->and((int) DB::table($ownerStore)->where('scope', 'user:1')->value('version'))->toBe($shape['soft_deletes'] || $shape['history'] ? 4 : 3) + ->and(Schema::hasTable('settings_history'))->toBe($shape['history']) + ->and(array_map(static fn (HistoryEntry $entry): string => $entry->operation->value . ':' . $entry->version, $trail)) + ->toBe($shape['history'] ? ['unlock:4', 'lock:3', 'set:2', 'forget:1', 'set:1'] : []) + ->and($shape['history'] && $shape['tenancy'] === 'column' ? DB::table('settings_history')->distinct()->pluck('tenant')->all() : ['acme'])->toBe(['acme']) ->and(DB::table('settings')->where('key', 'mail.host')->value('category_id'))->toBe($again->id) ->and($again->id === $mail->id)->toBe($shape['categories_soft_deletes']) ->and(DB::table('settings')->distinct()->pluck($shape['tenancy'] === 'column' ? 'tenant' : 'scope')->contains('acme'))->toBe($shape['tenancy'] === 'column') diff --git a/tests/Feature/Database/SchemaShapeTest.php b/tests/Feature/Database/SchemaShapeTest.php index 2fdc046..74b1004 100644 --- a/tests/Feature/Database/SchemaShapeTest.php +++ b/tests/Feature/Database/SchemaShapeTest.php @@ -10,8 +10,8 @@ use Simtabi\Laranail\Settings\Actions\MakeStore; use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Database\StoreSchema; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; // Writes into the testbench application shared by every process (config/, database/), so it // cannot run beside itself in parallel; the parallel mutation run leaves this group out. diff --git a/tests/Feature/Database/SchemaSwitchesTest.php b/tests/Feature/Database/SchemaSwitchesTest.php index 3f01798..6feedcb 100644 --- a/tests/Feature/Database/SchemaSwitchesTest.php +++ b/tests/Feature/Database/SchemaSwitchesTest.php @@ -10,8 +10,8 @@ use Simtabi\Laranail\Settings\Actions\FindForeignTables; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /** The values table's column names. */ function valueColumns(string $table = 'settings'): array diff --git a/tests/Feature/Database/TenancyTest.php b/tests/Feature/Database/TenancyTest.php index 4f76464..9d87473 100644 --- a/tests/Feature/Database/TenancyTest.php +++ b/tests/Feature/Database/TenancyTest.php @@ -9,10 +9,10 @@ use Simtabi\Laranail\Settings\Models\ModelContext; use Simtabi\Laranail\Settings\Models\SettingCategory; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; -use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Tenancy\NullTenantDiscriminator; use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /* * Amendment B: column-mode tenancy. One database; every values, categories and audit row carries diff --git a/tests/Feature/Database/WriteRetryTest.php b/tests/Feature/Database/WriteRetryTest.php index 8e14ca5..66eaefa 100644 --- a/tests/Feature/Database/WriteRetryTest.php +++ b/tests/Feature/Database/WriteRetryTest.php @@ -9,9 +9,9 @@ use Illuminate\Database\Events\QueryExecuted; use Simtabi\Laranail\Settings\Data\SettingWrite; use Simtabi\Laranail\Settings\Data\SettingTarget; -use Simtabi\Laranail\Settings\Stores\SettingWriter; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Actions\SettingActions; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; /** diff --git a/tests/Feature/DefinitionsTest.php b/tests/Feature/DefinitionsTest.php index 91b3ac2..f07ce0f 100644 --- a/tests/Feature/DefinitionsTest.php +++ b/tests/Feature/DefinitionsTest.php @@ -6,15 +6,15 @@ use Illuminate\Support\Facades\Storage; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\Precedence; -use Simtabi\Laranail\Settings\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Exceptions\LockedSetting; use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; use Simtabi\Laranail\Settings\Exceptions\UndecryptableValue; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; +use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Exceptions\EncryptionUnavailable; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; enum Plan: string { diff --git a/tests/Feature/DriverContractTest.php b/tests/Feature/DriverContractTest.php index 33e8ec4..427d630 100644 --- a/tests/Feature/DriverContractTest.php +++ b/tests/Feature/DriverContractTest.php @@ -11,8 +11,8 @@ use Simtabi\Laranail\Settings\Contracts\Driver; use Simtabi\Laranail\Settings\Data\LayerConfig; use Simtabi\Laranail\Settings\Enums\DriverType; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** diff --git a/tests/Feature/FakeTest.php b/tests/Feature/FakeTest.php index 50193a2..48228b7 100644 --- a/tests/Feature/FakeTest.php +++ b/tests/Feature/FakeTest.php @@ -13,8 +13,8 @@ use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Tests\Fixtures\TestUser; use Simtabi\Laranail\Settings\Exceptions\DriverUnavailable; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; use Simtabi\Laranail\Settings\Contracts\Settings as SettingsContract; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; it('records writes in memory and asserts on them', function (): void { $fake = Settings::fake(); diff --git a/tests/Feature/GuardedSettingsTest.php b/tests/Feature/GuardedSettingsTest.php index bae3e45..c54824c 100644 --- a/tests/Feature/GuardedSettingsTest.php +++ b/tests/Feature/GuardedSettingsTest.php @@ -19,10 +19,10 @@ use Simtabi\Laranail\Settings\Exceptions\LockedSetting; use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; use Simtabi\Laranail\Settings\Definitions\DefinitionBuilder; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Exceptions\VerificationRequired; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Verification\PasswordConfirmationVerifier; function defineSetting(): DefinitionBuilder diff --git a/tests/Feature/OwnersTest.php b/tests/Feature/OwnersTest.php index 23b6c0c..f24392a 100644 --- a/tests/Feature/OwnersTest.php +++ b/tests/Feature/OwnersTest.php @@ -6,7 +6,7 @@ use Simtabi\Laranail\Settings\Contracts\Settable; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; beforeEach(function (): void { config()->set('laranail.settings.stores', [ diff --git a/tests/Feature/RuntimeConfigurationTest.php b/tests/Feature/RuntimeConfigurationTest.php index 383cd88..8a197a6 100644 --- a/tests/Feature/RuntimeConfigurationTest.php +++ b/tests/Feature/RuntimeConfigurationTest.php @@ -13,20 +13,20 @@ use Simtabi\Laranail\Settings\SettingsManager; use Simtabi\Laranail\Settings\Data\LayerConfig; use Simtabi\Laranail\Settings\Drivers\ArrayDriver; -use Simtabi\Laranail\Settings\Resolution\Resolver; -use Simtabi\Laranail\Settings\Stores\SettingWriter; -use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Audit\InMemoryAuditSink; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Simtabi\Laranail\Settings\Exceptions\UnknownStore; use Simtabi\Laranail\Settings\Exceptions\ActorRequired; use Simtabi\Laranail\Settings\Verification\NullVerifier; -use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Services\Resolution\Resolver; +use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Authorization\ClosureAuthorizer; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Exceptions\VerificationRequired; -use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; use Simtabi\Laranail\Settings\Authentication\ClosureActorResolver; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** A logger that keeps messages, for runtime logTo() tests. */ function memoryLogger(): AbstractLogger diff --git a/tests/Feature/SettingsCacheTest.php b/tests/Feature/SettingsCacheTest.php index bfe57a5..8f81eee 100644 --- a/tests/Feature/SettingsCacheTest.php +++ b/tests/Feature/SettingsCacheTest.php @@ -14,9 +14,9 @@ use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\CacheTarget; -use Simtabi\Laranail\Settings\Caching\SettingsCache; use Illuminate\Contracts\Cache\Factory as CacheFactory; use Illuminate\Contracts\Cache\Repository as CacheContract; +use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /* diff --git a/tests/Fixtures/Stubs/legacy-slack-message.php b/tests/Fixtures/Stubs/legacy-slack-message.php new file mode 100644 index 0000000..c37bfe9 --- /dev/null +++ b/tests/Fixtures/Stubs/legacy-slack-message.php @@ -0,0 +1,23 @@ +content = $content; + + return $this; + } + } +} diff --git a/tests/Pest.php b/tests/Pest.php index 1058fb3..73559de 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -8,10 +8,10 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Tests\TestCase; use Simtabi\Laranail\Settings\Contracts\Settings; -use Simtabi\Laranail\Settings\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Audit\InMemoryAuditSink; use Simtabi\Laranail\Settings\Tests\Fixtures\TestUser; use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; // Feature tests boot the application; Unit and Arch tests deliberately do not, so a unit // that quietly relies on the container fails instead of passing. diff --git a/tests/Unit/EventSummaryTest.php b/tests/Unit/EventSummaryTest.php new file mode 100644 index 0000000..6fef56b --- /dev/null +++ b/tests/Unit/EventSummaryTest.php @@ -0,0 +1,38 @@ +payload = new ArrayObject(['colour' => 'blue']); + } + }; + + expect(EventSummary::of($event))->toBe(['store' => 'settings', 'version' => 3]); +}); + +it('names an actor by type, alias and id, and a system actor by its type', function (): void { + $denied = new AccessWasDenied(Ability::Update, new Subject(new StoreName('settings'), new Key('site.name')), new Actor(ActorType::Token, '9', 'client'), 'access_denied'); + + expect(EventSummary::of($denied))->toMatchArray(['ability' => 'update', 'key' => 'site.name', 'actor' => 'token:client:9', 'refusal' => 'access_denied']) + ->and(EventSummary::actor(Actor::system()))->toBe('system') + ->and(EventSummary::actor(new Actor(ActorType::Service, '4')))->toBe('service:?:4'); +}); diff --git a/tests/Unit/SupportTest.php b/tests/Unit/SupportTest.php index 93a5c10..ec87f22 100644 --- a/tests/Unit/SupportTest.php +++ b/tests/Unit/SupportTest.php @@ -12,8 +12,8 @@ use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -use Simtabi\Laranail\Settings\Definitions\DatabaseDefinitions; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; it('stores and reads titles in both translation modes', function (): void { $lang = new Translations(TranslationsMode::Lang); diff --git a/tests/Unit/ValuesTest.php b/tests/Unit/ValuesTest.php index 8f2153c..c16ff5f 100644 --- a/tests/Unit/ValuesTest.php +++ b/tests/Unit/ValuesTest.php @@ -11,9 +11,9 @@ use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Contracts\Caster; use Simtabi\Laranail\Settings\Support\ValueEncoder; -use Simtabi\Laranail\Settings\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; +use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; it('keeps a stored null distinct from no value', function (): void { $encoder = new ValueEncoder; From ae53dcf90c179da8a2dcbea1dcc3b9ae6af739a3 Mon Sep 17 00:00:00 2001 From: Imani Manyara Date: Tue, 10 Nov 2026 08:12:12 -0500 Subject: [PATCH 2/4] Reuse migration copies in tests and raise the test memory limit --- phpunit.xml | 2 ++ tests/Pest.php | 14 +++++++++++++- tests/TestCase.php | 47 ++++++++++++++++++++++++++++++++++++++-------- 3 files changed, 54 insertions(+), 9 deletions(-) diff --git a/phpunit.xml b/phpunit.xml index b338a2f..27a9683 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -23,6 +23,8 @@ + + diff --git a/tests/Pest.php b/tests/Pest.php index 73559de..d295c24 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -82,7 +82,19 @@ function useDatabase(array $config = [], array $stores = [], array $ownerTables app()->forgetInstance(DriverFactory::class); app()->forgetScopedInstances(); - $directory = sys_get_temp_dir() . '/laranail-settings-migrations-' . bin2hex(random_bytes(4)); + // One directory per distinct set of files, reused: the migrator requires each file, and PHP + // keeps every compiled file for the life of the process, so a fresh path per call would leak + // a migration's worth of memory per test (the full switch matrix runs thousands of them). + $migration = (string) file_get_contents(__DIR__ . '/../database/migrations/create_laranail_settings_tables.php'); + $directory = sys_get_temp_dir() . '/laranail-settings-migrations-' . sha1(serialize([$migration, $stores, $ownerTables])); + + if (is_dir($directory)) { + Artisan::call('migrate:fresh', ['--path' => $directory, '--realpath' => true]); + app(ReadinessProbe::class)->flush(); + + return; + } + mkdir($directory); copy(__DIR__ . '/../database/migrations/create_laranail_settings_tables.php', $directory . '/2026_01_01_000000_create_laranail_settings_tables.php'); diff --git a/tests/TestCase.php b/tests/TestCase.php index 5f7f697..dd550bb 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -13,19 +13,34 @@ abstract class TestCase extends IsolatedTestCase { + /** @var array configuration applied while the application boots (rebootWith()) */ + private static array $bootConfig = []; + #[Override] protected function setUp(): void { parent::setUp(); - // The runtime layer writes through the `local` disk; keep every test's files apart. - Storage::fake('local'); - // No shipped file unless a test ships one. - config()->set('laranail.settings.layers.shipped.path', '/nonexistent/laranail-settings-defaults.php'); - // The schema-shape file goes to a path of this test's own, never the skeleton's database/. - config()->set('laranail.settings.schema.path', sys_get_temp_dir() . '/laranail-settings-schema-' . bin2hex(random_bytes(6)) . '.php'); - // File layers only unless a test asks for the database (useDatabase() in tests/Pest.php). - config()->set('laranail.settings.stores.settings.layers', ['runtime', 'shipped']); + $this->configureSettings(); + } + + /** + * Boot the application again with this configuration in place before the providers boot (the + * REST API registers its routes at boot, only when http.enabled is on). + * + * @param array $config full config keys + */ + public function rebootWith(array $config): void + { + self::$bootConfig = $config; + + try { + $this->refreshApplication(); + } finally { + self::$bootConfig = []; + } + + $this->configureSettings(); } /** @@ -38,6 +53,10 @@ protected function defineEnvironment($app): void { parent::defineEnvironment($app); + foreach (self::$bootConfig as $key => $value) { + $app['config']->set($key, $value); + } + $connection = getenv('DB_CONNECTION'); if (! in_array($connection, ['mysql', 'mariadb', 'pgsql'], true)) { @@ -67,4 +86,16 @@ protected function getPackageProviders($app): array // registry the package's seeders are registered into. return [PackageToolsServiceProvider::class, DbToolsServiceProvider::class, SettingsServiceProvider::class]; } + + private function configureSettings(): void + { + // The runtime layer writes through the `local` disk; keep every test's files apart. + Storage::fake('local'); + // No shipped file unless a test ships one. + config()->set('laranail.settings.layers.shipped.path', '/nonexistent/laranail-settings-defaults.php'); + // The schema-shape file goes to a path of this test's own, never the skeleton's database/. + config()->set('laranail.settings.schema.path', sys_get_temp_dir() . '/laranail-settings-schema-' . bin2hex(random_bytes(6)) . '.php'); + // File layers only unless a test asks for the database (useDatabase() in tests/Pest.php). + config()->set('laranail.settings.stores.settings.layers', ['runtime', 'shipped']); + } } From 11c8c57c71d3e920d47dba73b7fd61246565d84b Mon Sep 17 00:00:00 2001 From: Imani Manyara Date: Tue, 10 Nov 2026 08:12:13 -0500 Subject: [PATCH 3/4] Add approvals, import/export, REST API and typed settings (phases 4b, 4c, 5) --- CHANGELOG.md | 65 +++ README.md | 28 +- config/settings.php | 125 +++++- .../create_laranail_settings_tables.php | 90 +++++ docs/architecture.md | 10 +- docs/configuration.md | 22 +- docs/installation.md | 10 +- docs/recipes/approving-a-change.md | 38 ++ .../calling-the-rest-api-with-sanctum.md | 50 +++ .../migrating-from-spatie-laravel-settings.md | 49 +++ docs/tools/approvals.md | 78 ++++ docs/tools/commands.md | 20 +- docs/tools/import-export.md | 60 +++ docs/tools/importers.md | 55 +++ docs/tools/persisted-configuration.md | 42 ++ docs/tools/reencryption.md | 36 ++ docs/tools/rest-api.md | 108 +++++ docs/tools/settings-api.md | 10 +- docs/tools/typed-settings.md | 81 ++++ src/Actions/Approvals/ApprovalActions.php | 21 + src/Actions/Approvals/ApproveChange.php | 173 ++++++++ src/Actions/Approvals/CancelChange.php | 68 ++++ src/Actions/Approvals/ProposeChange.php | 98 +++++ src/Actions/Approvals/PruneChanges.php | 60 +++ src/Actions/Approvals/QueryChanges.php | 46 +++ src/Actions/Approvals/RejectChange.php | 63 +++ src/Actions/Categories/ListCategories.php | 29 ++ .../Configuration/ConfigurationActions.php | 17 + .../DeleteConfigurationEntry.php | 36 ++ .../Configuration/DeleteDefinition.php | 51 +++ .../ListConfigurationEntries.php | 41 ++ .../Configuration/SaveConfigurationEntry.php | 42 ++ src/Actions/Configuration/SaveDefinition.php | 75 ++++ src/Actions/DiagnoseSettings.php | 88 ++++- src/Actions/ForgetSetting.php | 10 +- src/Actions/LockSetting.php | 10 +- src/Actions/MigrateSettings.php | 117 ++++++ src/Actions/Reads/ExplainSetting.php | 25 ++ src/Actions/Reads/ListDefinitions.php | 46 +++ src/Actions/Reads/ListStores.php | 35 ++ src/Actions/Reads/ReadHistory.php | 31 ++ src/Actions/Reads/ReadSetting.php | 41 ++ src/Actions/Reads/ReadSettings.php | 74 ++++ src/Actions/ReencryptSettings.php | 90 +++++ src/Actions/RescopeOwners.php | 87 ++++ src/Actions/SetSetting.php | 10 +- src/Actions/SettingActions.php | 10 +- src/Actions/Transfer/DiffStore.php | 34 ++ src/Actions/Transfer/ExportStore.php | 45 +++ src/Actions/Transfer/ImportStore.php | 202 ++++++++++ src/Actions/Transfer/TransferActions.php | 15 + src/Actions/UnlockSetting.php | 10 +- src/Actions/WriteGuard.php | 23 +- src/Approvals/Approvals.php | 107 +++++ .../PersistedConfigurationEditor.php | 78 ++++ src/Console/DiffCommand.php | 64 +++ src/Console/ExportCommand.php | 82 ++++ src/Console/ImportCommand.php | 104 +++++ src/Console/OpenApiCommand.php | 52 +++ src/Console/PruneChangesCommand.php | 40 ++ src/Console/ReencryptCommand.php | 46 +++ src/Console/RescopeCommand.php | 46 +++ src/Contracts/Importer.php | 21 + src/Contracts/OwnerResolver.php | 19 + src/Contracts/Settings.php | 55 +++ src/Data/ApprovalPolicy.php | 32 ++ src/Data/ChangeDecision.php | 17 + src/Data/ChangeFilter.php | 25 ++ src/Data/ChangeProposal.php | 20 + src/Data/ChangeRequest.php | 101 +++++ src/Data/ConfigurationEntry.php | 29 ++ src/Data/Http/AddressInput.php | 17 + src/Data/Http/BodyInput.php | 60 +++ src/Data/Http/PageInput.php | 21 + src/Data/Http/WriteInput.php | 20 + src/Data/SettingAddress.php | 32 ++ src/Data/SettingTarget.php | 17 +- src/Data/SettingView.php | 27 ++ src/Data/SettingsMigrationStep.php | 29 ++ src/Data/Transfer/ExportDocument.php | 118 ++++++ src/Data/Transfer/ExportRequest.php | 17 + src/Data/Transfer/ExportedCategory.php | 78 ++++ src/Data/Transfer/ExportedSetting.php | 85 ++++ src/Data/Transfer/ImportReport.php | 45 +++ src/Data/Transfer/ImportRequest.php | 23 ++ src/Data/Transfer/StoreDiff.php | 40 ++ src/Database/SchemaNames.php | 25 +- src/Database/SchemaShape.php | 23 +- src/Drivers/DatabaseDriver.php | 82 ++++ src/Enums/AuditAction.php | 21 +- src/Enums/Capability.php | 199 ++++++++++ src/Enums/ChangeOperation.php | 38 ++ src/Enums/ChangeStatus.php | 45 +++ src/Enums/ExportMode.php | 29 ++ src/Events/ChangeApplied.php | 23 ++ src/Events/ChangeApproved.php | 23 ++ src/Events/ChangeCancelled.php | 22 ++ src/Events/ChangeRejected.php | 22 ++ src/Events/ChangeRequested.php | 22 ++ src/Events/ChangeStale.php | 22 ++ src/Exceptions/ApprovalUnavailable.php | 7 +- src/Exceptions/ChangeRequestClosed.php | 11 + src/Exceptions/InvalidImport.php | 8 + src/Exceptions/UnknownChangeRequest.php | 8 + src/Exceptions/UnknownOwner.php | 8 + src/Http/ApiRoutes.php | 119 ++++++ src/Http/Controllers/AuditController.php | 53 +++ src/Http/Controllers/CategoriesController.php | 85 ++++ src/Http/Controllers/ChangesController.php | 121 ++++++ .../Controllers/ConfigurationController.php | 74 ++++ src/Http/Controllers/HistoryController.php | 51 +++ src/Http/Controllers/SettingsController.php | 145 +++++++ src/Http/Controllers/StoresController.php | 38 ++ src/Http/Controllers/TransferController.php | 62 +++ src/Http/Middleware/FreshControllers.php | 31 ++ src/Http/Middleware/IdempotentWrites.php | 62 +++ src/Http/OpenApi/OpenApiDocument.php | 322 +++++++++++++++ src/Http/Requests/BodyRequest.php | 79 ++++ src/Http/Requests/Concerns/ReadsAddress.php | 31 ++ src/Http/Requests/PageRequest.php | 60 +++ src/Http/Requests/SettingRequest.php | 31 ++ src/Http/Requests/WriteSettingRequest.php | 54 +++ src/Http/Resources/CategoryResource.php | 27 ++ src/Http/Resources/ChangeRequestResource.php | 30 ++ src/Http/Resources/DefinitionResource.php | 43 ++ src/Http/Resources/ExplanationResource.php | 30 ++ src/Http/Resources/SettingResource.php | 55 +++ src/Http/Resources/StoreResource.php | 27 ++ src/Http/Support/Addresses.php | 26 ++ src/Http/Support/ApiActor.php | 32 ++ src/Http/Support/ListResponse.php | 17 + src/Http/Support/Problems.php | 121 ++++++ src/Importers/AkauntingSettingsImporter.php | 58 +++ src/Importers/ImportedKeys.php | 49 +++ src/Importers/SpatieSettingsImporter.php | 53 +++ src/Importers/ToolkitJsonImporter.php | 67 ++++ src/Listeners/SendSettingsAlert.php | 8 + src/Owners/MorphMapOwnerResolver.php | 56 +++ src/Providers/SettingsServiceProvider.php | 372 +++++++++++++++++- .../Configuration/PersistedConfiguration.php | 259 ++++++++++++ src/Services/Database/AuditRepository.php | 2 +- .../Database/ChangeRequestRepository.php | 312 +++++++++++++++ .../Database/DefinitionsRepository.php | 50 +++ src/Services/Database/HistoryRepository.php | 69 ++++ .../Definitions/DatabaseDefinitions.php | 18 + .../Definitions/DefinitionRegistry.php | 26 ++ src/Services/Resolution/SettingTargets.php | 72 ++++ src/Services/Stores/StoreRegistry.php | 62 ++- src/Services/Transfer/Importers.php | 45 +++ src/Services/Transfer/StoreSnapshots.php | 128 ++++++ src/SettingsManager.php | 69 ++++ src/Stores/Store.php | 15 + src/Testing/SettingsFake.php | 42 ++ src/Typed/Attributes/Encrypted.php | 13 + src/Typed/Attributes/Group.php | 19 + src/Typed/Attributes/Key.php | 18 + src/Typed/Attributes/Store.php | 18 + src/Typed/Attributes/Type.php | 19 + src/Typed/SettingsMigration.php | 46 +++ src/Typed/SettingsMigrator.php | 55 +++ src/Typed/TypedProperty.php | 114 ++++++ src/Typed/TypedSettings.php | 187 +++++++++ tests/Arch/ArchitectureTest.php | 7 +- tests/Arch/LayeringTest.php | 27 +- tests/Arch/RestApiTest.php | 89 +++++ tests/Arch/ServicesTest.php | 9 +- tests/Feature/Database/ApprovalsTest.php | 253 ++++++++++++ tests/Feature/Database/MaintenanceTest.php | 133 +++++++ .../Database/PersistedConfigurationTest.php | 124 ++++++ tests/Feature/Database/RestApiTest.php | 241 ++++++++++++ tests/Feature/Database/SchemaMatrixTest.php | 13 +- tests/Feature/Database/TransferTest.php | 224 +++++++++++ tests/Feature/Database/TypedSettingsTest.php | 182 +++++++++ tests/Fixtures/Typed/BrokenSettings.php | 13 + tests/Fixtures/Typed/MailSettings.php | 38 ++ tests/Fixtures/Typed/Plan.php | 11 + tests/Support/JsonSchema.php | 110 ++++++ tests/Unit/AccessValuesTest.php | 2 +- tests/Unit/DocsConformanceTest.php | 4 +- 179 files changed, 10552 insertions(+), 80 deletions(-) create mode 100644 docs/recipes/approving-a-change.md create mode 100644 docs/recipes/calling-the-rest-api-with-sanctum.md create mode 100644 docs/recipes/migrating-from-spatie-laravel-settings.md create mode 100644 docs/tools/approvals.md create mode 100644 docs/tools/import-export.md create mode 100644 docs/tools/importers.md create mode 100644 docs/tools/persisted-configuration.md create mode 100644 docs/tools/reencryption.md create mode 100644 docs/tools/rest-api.md create mode 100644 docs/tools/typed-settings.md create mode 100644 src/Actions/Approvals/ApprovalActions.php create mode 100644 src/Actions/Approvals/ApproveChange.php create mode 100644 src/Actions/Approvals/CancelChange.php create mode 100644 src/Actions/Approvals/ProposeChange.php create mode 100644 src/Actions/Approvals/PruneChanges.php create mode 100644 src/Actions/Approvals/QueryChanges.php create mode 100644 src/Actions/Approvals/RejectChange.php create mode 100644 src/Actions/Categories/ListCategories.php create mode 100644 src/Actions/Configuration/ConfigurationActions.php create mode 100644 src/Actions/Configuration/DeleteConfigurationEntry.php create mode 100644 src/Actions/Configuration/DeleteDefinition.php create mode 100644 src/Actions/Configuration/ListConfigurationEntries.php create mode 100644 src/Actions/Configuration/SaveConfigurationEntry.php create mode 100644 src/Actions/Configuration/SaveDefinition.php create mode 100644 src/Actions/MigrateSettings.php create mode 100644 src/Actions/Reads/ExplainSetting.php create mode 100644 src/Actions/Reads/ListDefinitions.php create mode 100644 src/Actions/Reads/ListStores.php create mode 100644 src/Actions/Reads/ReadHistory.php create mode 100644 src/Actions/Reads/ReadSetting.php create mode 100644 src/Actions/Reads/ReadSettings.php create mode 100644 src/Actions/ReencryptSettings.php create mode 100644 src/Actions/RescopeOwners.php create mode 100644 src/Actions/Transfer/DiffStore.php create mode 100644 src/Actions/Transfer/ExportStore.php create mode 100644 src/Actions/Transfer/ImportStore.php create mode 100644 src/Actions/Transfer/TransferActions.php create mode 100644 src/Approvals/Approvals.php create mode 100644 src/Configuration/PersistedConfigurationEditor.php create mode 100644 src/Console/DiffCommand.php create mode 100644 src/Console/ExportCommand.php create mode 100644 src/Console/ImportCommand.php create mode 100644 src/Console/OpenApiCommand.php create mode 100644 src/Console/PruneChangesCommand.php create mode 100644 src/Console/ReencryptCommand.php create mode 100644 src/Console/RescopeCommand.php create mode 100644 src/Contracts/Importer.php create mode 100644 src/Contracts/OwnerResolver.php create mode 100644 src/Data/ApprovalPolicy.php create mode 100644 src/Data/ChangeDecision.php create mode 100644 src/Data/ChangeFilter.php create mode 100644 src/Data/ChangeProposal.php create mode 100644 src/Data/ChangeRequest.php create mode 100644 src/Data/ConfigurationEntry.php create mode 100644 src/Data/Http/AddressInput.php create mode 100644 src/Data/Http/BodyInput.php create mode 100644 src/Data/Http/PageInput.php create mode 100644 src/Data/Http/WriteInput.php create mode 100644 src/Data/SettingAddress.php create mode 100644 src/Data/SettingView.php create mode 100644 src/Data/SettingsMigrationStep.php create mode 100644 src/Data/Transfer/ExportDocument.php create mode 100644 src/Data/Transfer/ExportRequest.php create mode 100644 src/Data/Transfer/ExportedCategory.php create mode 100644 src/Data/Transfer/ExportedSetting.php create mode 100644 src/Data/Transfer/ImportReport.php create mode 100644 src/Data/Transfer/ImportRequest.php create mode 100644 src/Data/Transfer/StoreDiff.php create mode 100644 src/Enums/Capability.php create mode 100644 src/Enums/ChangeOperation.php create mode 100644 src/Enums/ChangeStatus.php create mode 100644 src/Enums/ExportMode.php create mode 100644 src/Events/ChangeApplied.php create mode 100644 src/Events/ChangeApproved.php create mode 100644 src/Events/ChangeCancelled.php create mode 100644 src/Events/ChangeRejected.php create mode 100644 src/Events/ChangeRequested.php create mode 100644 src/Events/ChangeStale.php create mode 100644 src/Exceptions/ChangeRequestClosed.php create mode 100644 src/Exceptions/InvalidImport.php create mode 100644 src/Exceptions/UnknownChangeRequest.php create mode 100644 src/Exceptions/UnknownOwner.php create mode 100644 src/Http/ApiRoutes.php create mode 100644 src/Http/Controllers/AuditController.php create mode 100644 src/Http/Controllers/CategoriesController.php create mode 100644 src/Http/Controllers/ChangesController.php create mode 100644 src/Http/Controllers/ConfigurationController.php create mode 100644 src/Http/Controllers/HistoryController.php create mode 100644 src/Http/Controllers/SettingsController.php create mode 100644 src/Http/Controllers/StoresController.php create mode 100644 src/Http/Controllers/TransferController.php create mode 100644 src/Http/Middleware/FreshControllers.php create mode 100644 src/Http/Middleware/IdempotentWrites.php create mode 100644 src/Http/OpenApi/OpenApiDocument.php create mode 100644 src/Http/Requests/BodyRequest.php create mode 100644 src/Http/Requests/Concerns/ReadsAddress.php create mode 100644 src/Http/Requests/PageRequest.php create mode 100644 src/Http/Requests/SettingRequest.php create mode 100644 src/Http/Requests/WriteSettingRequest.php create mode 100644 src/Http/Resources/CategoryResource.php create mode 100644 src/Http/Resources/ChangeRequestResource.php create mode 100644 src/Http/Resources/DefinitionResource.php create mode 100644 src/Http/Resources/ExplanationResource.php create mode 100644 src/Http/Resources/SettingResource.php create mode 100644 src/Http/Resources/StoreResource.php create mode 100644 src/Http/Support/Addresses.php create mode 100644 src/Http/Support/ApiActor.php create mode 100644 src/Http/Support/ListResponse.php create mode 100644 src/Http/Support/Problems.php create mode 100644 src/Importers/AkauntingSettingsImporter.php create mode 100644 src/Importers/ImportedKeys.php create mode 100644 src/Importers/SpatieSettingsImporter.php create mode 100644 src/Importers/ToolkitJsonImporter.php create mode 100644 src/Owners/MorphMapOwnerResolver.php create mode 100644 src/Services/Configuration/PersistedConfiguration.php create mode 100644 src/Services/Database/ChangeRequestRepository.php create mode 100644 src/Services/Resolution/SettingTargets.php create mode 100644 src/Services/Transfer/Importers.php create mode 100644 src/Services/Transfer/StoreSnapshots.php create mode 100644 src/Typed/Attributes/Encrypted.php create mode 100644 src/Typed/Attributes/Group.php create mode 100644 src/Typed/Attributes/Key.php create mode 100644 src/Typed/Attributes/Store.php create mode 100644 src/Typed/Attributes/Type.php create mode 100644 src/Typed/SettingsMigration.php create mode 100644 src/Typed/SettingsMigrator.php create mode 100644 src/Typed/TypedProperty.php create mode 100644 src/Typed/TypedSettings.php create mode 100644 tests/Arch/RestApiTest.php create mode 100644 tests/Feature/Database/ApprovalsTest.php create mode 100644 tests/Feature/Database/MaintenanceTest.php create mode 100644 tests/Feature/Database/PersistedConfigurationTest.php create mode 100644 tests/Feature/Database/RestApiTest.php create mode 100644 tests/Feature/Database/TransferTest.php create mode 100644 tests/Feature/Database/TypedSettingsTest.php create mode 100644 tests/Fixtures/Typed/BrokenSettings.php create mode 100644 tests/Fixtures/Typed/MailSettings.php create mode 100644 tests/Fixtures/Typed/Plan.php create mode 100644 tests/Support/JsonSchema.php diff --git a/CHANGELOG.md b/CHANGELOG.md index c79d1e7..3ad0fc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Approvals (design §16.7, Phase 4b): a write (`set`, `forget`, `lock`, `unlock`) to a setting + whose definition is `requiresApproval()`, or whose key matches the store's new + `approvals.keys` globs, opens a change request instead of writing. A + `settings_change_requests` table (one per connection, ULID keys, tenant column in column-mode + tenancy) is created by the one migration when the new schema switch `approvals.table` is on (the + default). The proposed value is validated and stored as the values table would store it, so an + encrypted definition's value is encrypted at rest. `$settings->propose()` and + `$settings->approvals()` (`Approvals\Approvals`: `pending()`, `status()`, `key()`, `for()`, + `get()`, `find()`, `approve()`, `reject()`, `cancel()`). Approving needs `approve`; the + requester cannot approve their own request unless `approvals.allow_self`; `approvals.min_approvals` + approvals apply the change through the write pipeline against the base version, so a setting + that changed meanwhile makes the request `stale`; requests expire after `approvals.expire_after` + days. Events `ChangeRequested`, `ChangeApproved`, `ChangeApplied`, `ChangeRejected`, + `ChangeCancelled`, `ChangeStale` (the alert listener knows the first four of interest); audit + actions `propose`, `reject`, `cancel` with the change request's id in the `change_request` + column; `laranail::settings.prune-changes`. Enums `ChangeStatus`, `ChangeOperation`; exceptions + `UnknownChangeRequest`, `ChangeRequestClosed`. +- Export, import and store diff (G-10, G-42): `$settings->export(ExportMode)`, `import()`, + `previewImport()`, `compare()`; `laranail::settings.export` (`--with-secrets`, `--decrypt` with + the store name typed), `.import` (dry run unless `--apply`; `--trusted` for locks and system + categories) and `.diff`. Documents name categories by slug and settings by scope, key and locale, + never a numeric id. Imports create categories first and write each setting through the write + pipeline, in one transaction. Gated by `export` / `import`, audited. +- Importers (G-43) behind `Contracts\Importer`: `spatie` (spatie/laravel-settings' table), + `toolkit` (laranail/toolkit's JSON store) and `akaunting` (akaunting/laravel-setting's table), + configured in `importers`, used with `import --from=`. No dependency on any of them. +- `laranail::settings.reencrypt` (`Actions\ReencryptSettings`): encrypts live values, history and + change requests again under the current key, leaving unreadable payloads untouched and + reporting them. `laranail::settings.rescope {from} {to}` (`Actions\RescopeOwners`, G-30) renames + an owner alias in values (with `settable_type` and per-row slugs), history and change requests. +- `doctor` also reports encrypted values no key can read, open change requests past their expiry, + schema drift on the history, change requests and persisted configuration tables, and persisted + entries skipped as invalid. +- Persisted configuration (§16.11): with the new schema switch `configuration.persisted`, a + `settings_stores` table holds stores and layers saved through + `$settings->persistedConfiguration()` (and the REST API), and definitions are saved to the + definitions table. Validated like configuration, gated (`manage_stores`, `manage_definitions`), + audited, read on first use and merged in `configuration.sources` order; an invalid entry is + logged and skipped. +- The REST API (§16.10, Phase 4c), off unless `http.enabled`: 39 routes under `http.prefix`/v1 + named `laranail-settings.api.*`, through `http.middleware`, the `laranail-settings` rate limiter + and an `Idempotency-Key` cache for writes. Route → FormRequest → controller → the same actions + the PHP API runs (`Enums\Capability`), API resources, ETags with `If-Match` (412), `202` with a + change request for approvals, cursor-paginated lists, values the actor may not view left out, + RFC 9457 problem details, `Contracts\OwnerResolver` (morph map by default; unknown alias 404). + New read actions `Actions\Reads\{ReadSetting, ReadSettings, ExplainSetting, ReadHistory, + ListStores, ListDefinitions}` and `Actions\Categories\ListCategories`. + `laranail::settings.openapi` writes an OpenAPI 3.1 document; the tests validate responses + against it. +- Typed settings classes (Phase 5): `Typed\TypedSettings` with `load()`, `save()`, + `register()` and the attributes `#[Store]`, `#[Group]`, `#[Key]`, `#[Encrypted]`, `#[Type]`; + typed classes resolve from the container loaded, and `typed.classes` registers their + definitions. Settings migrations (G-17): `Typed\SettingsMigration` with `rename()`, `move()`, + `add()` and `delete()` (`Actions\MigrateSettings`, audited as `migrate`). - Value history (design §4.3, Phase 4): a `settings_history` table, one per connection like the audit table, created by the one migration when the new schema switch `history.enabled` is on (the default; recorded in the schema file as `history_table`, and read as off from a file @@ -125,6 +179,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- A write to a setting that needs approval opens a change request where the store can hold one; + `ApprovalUnavailable` is now raised only where it cannot (no active database layer, or no + change requests table). `SetSetting`, `ForgetSetting`, `LockSetting` and `UnlockSetting` return + the change request they opened (null when they wrote), and `WriteGuard::run()` takes an optional + proposal and returns it. +- The `Settings` contract gains `propose()`, `approvals()`, `export()`, `import()`, + `previewImport()`, `compare()` and `persistedConfiguration()` (pre-1.0; `SettingsManager` and + the fake implement them). +- The schema-switch matrix covers `approvals.table`: 11 pairwise shapes for 261 pairs per pull + request, 4,608 shapes in the weekly full product. +- The test suite runs with a 512 MB memory limit (`phpunit.xml`). - Every service now lives under `Services\` (Phase 4 plan §1), moved verbatim: `Services\Database\{AuditRepository, CategoryRepository, DefinitionsRepository, SchemaInspector, SchemaShapeRepository}`, `Services\Stores\{SettingWriter, StoreRegistry}`, diff --git a/README.md b/README.md index bf876ba..9e39b58 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,9 @@ They are added once each claim is true. Requires PHP 8.4.1+ or 8.5 and Laravel 13. Works on MySQL, PostgreSQL and SQLite; SQL Server is not supported in 0.x. -> **Pre-release.** The engine reads and writes through database, file and config layers; -> caching and history arrive in the next phases. See [Getting started](docs/getting-started.md). +> **Pre-release.** The engine, caching, history, approvals, import and export, the opt-in REST API +> and typed settings classes are built; the 0.1 release is being prepared. See +> [Getting started](docs/getting-started.md). ## Install @@ -24,7 +25,7 @@ composer require laranail/settings ### Getting started Publish the config and the package's one migration (it creates `settings_categories`, a values -table per database store, and `settings_audit`), migrate, and optionally seed the default +table per database store, `settings_audit`, `settings_history` and `settings_change_requests`), migrate, and optionally seed the default categories: the default store reads the database first, then its runtime file, then shipped defaults from `settings/defaults.php` when that file exists. @@ -61,6 +62,15 @@ Settings::for($user)->get('ui.theme', 'light'); Settings::as($user)->because('INC-123')->set('mail.from.address', 'ap@acme.test'); ``` +```php +// A typed class over the same keys (loaded and saved through the same write actions). +$mail = MailSettings::load(Settings::as($user)); +$mail->fromAddress = 'ops@acme.test'; +$mail->save(); +``` + +The JSON REST API is off until `http.enabled` is true; see [REST API](docs/tools/rest-api.md). + [Getting started](docs/getting-started.md) walks through stores, owners and definitions; the [Documentation](#documentation) index lists every page. @@ -83,7 +93,7 @@ The hosted docs live at [ | 'layers' => ['database'], @@ -61,6 +66,7 @@ 'strict' => false, 'inherits' => false, 'locks' => ['overridable' => false], + 'approvals' => ['keys' => []], 'bootstrap' => false, 'mode' => 'polymorphic', 'soft_deletes' => false, @@ -81,11 +87,13 @@ | name that is not this package's. */ 'tables' => [ - 'prefix' => env('LARANAIL_SETTINGS_TABLE_PREFIX', ''), - 'categories' => 'settings_categories', - 'audit' => 'settings_audit', - 'definitions' => 'settings_definitions', - 'history' => 'settings_history', + 'prefix' => env('LARANAIL_SETTINGS_TABLE_PREFIX', ''), + 'categories' => 'settings_categories', + 'audit' => 'settings_audit', + 'definitions' => 'settings_definitions', + 'history' => 'settings_history', + 'change_requests' => 'settings_change_requests', + 'stores' => 'settings_stores', ], /* @@ -418,4 +426,109 @@ 'rules' => [], ], + /* + |-------------------------------------------------------------------------- + | Approvals: four eyes (§16.7) + |-------------------------------------------------------------------------- + | + | A write to a definition marked requiresApproval(), or to a key matched by + | `stores..approvals.keys`, becomes a change request instead of a + | change. `table` is a schema switch (recorded in the schema file): it + | creates settings_change_requests on every connection a store uses. + | `min_approvals` approvals apply the change; the requester may approve + | their own request only with `allow_self`. A request expires after + | `expire_after` days; prune-changes marks expired requests and deletes + | decided ones older than `keep_days`. + */ + 'approvals' => [ + 'table' => true, + 'min_approvals' => 1, + 'allow_self' => false, + 'expire_after' => 7, + 'keep_days' => 90, + ], + + /* + |-------------------------------------------------------------------------- + | Persisted configuration (§16.11) + |-------------------------------------------------------------------------- + | + | `persisted` (a schema switch) creates settings_stores, where stores and + | layers saved through the API are kept; definitions saved through the API + | go to the definitions table (definitions.table). `sources` is the merge + | order, later wins: `config` (this file), `database` (persisted entries, + | read on first use, never at boot; an invalid entry is logged and skipped) + | and `runtime` (changes made in code for one request). + */ + 'configuration' => [ + 'persisted' => env('LARANAIL_SETTINGS_PERSISTED_CONFIGURATION', false), + 'sources' => ['config', 'database', 'runtime'], + ], + + /* + |-------------------------------------------------------------------------- + | Import and export (G-42, G-43) + |-------------------------------------------------------------------------- + | + | Importers that `laranail::settings.import --from=` can read, by + | name: a class implementing Simtabi\Laranail\Settings\Contracts\Importer. + | The three shipped ones need none of the packages they read. + */ + 'importers' => [ + 'spatie' => SpatieSettingsImporter::class, + 'toolkit' => ToolkitJsonImporter::class, + 'akaunting' => AkauntingSettingsImporter::class, + ], + + /* + |-------------------------------------------------------------------------- + | REST API (§16.10) + |-------------------------------------------------------------------------- + | + | Off by default; no route is registered until `enabled` is true. Routes + | live under `prefix`/v1, are named `laranail-settings.api.*`, and run + | through `middleware` (null: ['api', 'auth:sanctum'] when Sanctum is + | installed, else ['api', 'auth']) and the `laranail-settings` rate + | limiter (`rate_limit` requests per minute per actor, 0 for none). + | `routes` switches groups off. `idempotency` keeps the response to a + | write sent with an Idempotency-Key header for `ttl` seconds in `cache` + | (null: the default cache store), so a retried request is answered from + | there instead of applying twice. `owners` maps owner aliases the URL may + | name; null uses the morph map. + */ + /* + |-------------------------------------------------------------------------- + | Typed settings classes (Phase 5) + |-------------------------------------------------------------------------- + | + | Classes extending Simtabi\Laranail\Settings\Typed\TypedSettings whose + | properties are registered as definitions (type, default, encryption) + | when definitions are first read, so the key-value API casts them alike. + */ + 'typed' => [ + 'classes' => [], + ], + + 'http' => [ + 'enabled' => env('LARANAIL_SETTINGS_HTTP', false), + 'prefix' => 'api/settings', + 'middleware' => null, + 'rate_limit' => 60, + 'routes' => [ + 'stores' => true, + 'definitions' => true, + 'settings' => true, + 'history' => true, + 'audit' => true, + 'approvals' => true, + 'categories' => true, + 'configuration' => true, + 'transfer' => true, + ], + 'idempotency' => [ + 'cache' => null, + 'ttl' => 86400, + ], + 'page_size' => 50, + ], ]; diff --git a/database/migrations/create_laranail_settings_tables.php b/database/migrations/create_laranail_settings_tables.php index 4af0ff0..fbe6242 100644 --- a/database/migrations/create_laranail_settings_tables.php +++ b/database/migrations/create_laranail_settings_tables.php @@ -25,6 +25,9 @@ * 3. values one table per database store * 4. audit actions and denials, never values * 5. history every value by version (history.enabled), encrypted values still encrypted + * 6. change requests four-eyes approvals (approvals.table); proposed values encrypted as stored + * 7. stores persisted store and layer configuration (configuration.persisted), on the + * default store's connection * * The shape (key type, identity mode, owner keys, dedicated stores, soft deletes, translations, * tenancy, table names, connections) comes from the recorded schema file @@ -76,6 +79,14 @@ public function up(): void if ($tables['shared'] && $shape->historyTable && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->history()))) { $this->createHistory($connection, $shape); } + + if ($tables['shared'] && $shape->changeRequestsTable && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->changeRequests()))) { + $this->createChangeRequests($connection, $shape); + } + + if ($tables['definitions'] && $shape->storesTable) { + $this->createStores($connection, $shape); + } } } @@ -86,6 +97,14 @@ public function down(): void foreach (array_reverse($this->plan(), true) as $connection => $tables) { $schema = Schema::connection($connection); + if ($tables['definitions'] && $shape->storesTable) { + $schema->dropIfExists($shape->names->stores()); + } + + if ($tables['shared'] && $shape->changeRequestsTable) { + $schema->dropIfExists($shape->names->changeRequests()); + } + if ($tables['shared'] && $shape->historyTable) { $schema->dropIfExists($shape->names->history()); } @@ -368,6 +387,77 @@ private function createHistory(string $connection, SchemaShape $shape): void }); } + /** + * Change requests (§16.7): a write that needs approval waits here until enough approvers + * decide it. `payload` is the proposed value exactly as the values table would store it, so + * the value of an encrypted definition is encrypted at rest; `base_version` is the version the + * setting was at when the request was opened, and applying checks it, so a request whose + * setting changed since becomes `stale` instead of overwriting. Keyed by ULID, so the table + * never depends on `ids.type`. + */ + private function createChangeRequests(string $connection, SchemaShape $shape): void + { + $name = $shape->names->changeRequests(); + $binary = $this->binaryCollation($connection); + + Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $name, $shape): void { + $collate = static fn (ColumnDefinition $column): ColumnDefinition => $binary === null ? $column : $column->collation($binary); + + $table->char('id', 26)->primary(); + + if ($shape->tenancy === TenancyMode::Column) { + $collate($table->string('tenant', 64)->default('')); + } + + $table->string('store', 64); + $collate($table->string('scope', 128)); + $collate($table->string('key', 191)); + $collate($table->string('locale', 16)->default('')); + $table->string('operation', 16); + $table->longText('payload')->nullable(); + $table->string('type', 64)->nullable(); + $table->boolean('is_encrypted')->default(false); + $table->unsignedInteger('base_version')->default(0); + $table->string('status', 16); + $table->string('requested_by_type', 16); + $table->string('requested_by_alias', 64)->nullable(); + $table->string('requested_by_id', 64)->nullable(); + $table->json('approvals')->nullable(); + $table->string('decided_by_type', 16)->nullable(); + $table->string('decided_by_alias', 64)->nullable(); + $table->string('decided_by_id', 64)->nullable(); + $table->timestamp('decided_at')->nullable(); + $table->text('reason')->nullable(); + $table->text('decision_reason')->nullable(); + $table->timestamp('expires_at')->nullable(); + $table->timestamps(); + + $table->index([...$this->tenantColumns($shape), 'status', 'store'], $name . '_status_index'); + $table->index([...$this->tenantColumns($shape), 'store', 'scope', 'key', 'locale'], $name . '_subject_index'); + $table->index('expires_at', $name . '_expires_index'); + }); + } + + /** + * Persisted configuration (§16.11): store and layer entries edited through the API, merged + * with the configuration file in `configuration.sources` order. `config` holds the entry as + * the configuration file would (JSON, so its key order is never relied on). + */ + private function createStores(string $connection, SchemaShape $shape): void + { + $name = $shape->names->stores(); + + Schema::connection($connection)->create($name, function (Blueprint $table) use ($name): void { + $table->char('id', 26)->primary(); + $table->string('kind', 16); + $table->string('name', 64); + $table->json('config'); + $table->timestamps(); + + $table->unique(['kind', 'name'], $name . '_kind_name_unique'); + }); + } + /** * A key column typed per `ids.type`. The primary key is an explicit command, not the fluent * ->primary(): Laravel appends fluent indexes after every other command, so PostgreSQL would diff --git a/docs/architecture.md b/docs/architecture.md index 26c7942..e1f2c7c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -220,7 +220,15 @@ round trips per store on the first read of a request and none after it. ## Why headless? -The package ships no views, Blade components, Livewire, Filament or assets. A settings engine is consumed by many interfaces (an admin panel, a CLI, an API client, another package), and any UI bundled here would be the wrong one for most of them and would drag view dependencies into every host. Its surfaces are the PHP API, events, Artisan commands and, later, an opt-in JSON API; an admin UI is a separate companion package. An architecture test fails on any view, Blade, Livewire or Filament reference in `src/` and on a `resources/views` directory. +The package ships no views, Blade components, Livewire, Filament or assets. A settings engine is consumed by many interfaces (an admin panel, a CLI, an API client, another package), and any UI bundled here would be the wrong one for most of them and would drag view dependencies into every host. Its surfaces are the PHP API, events, Artisan commands and an opt-in JSON API; an admin UI is a separate companion package. An architecture test fails on any view, Blade, Livewire or Filament reference in `src/` and on a `resources/views` directory. + +## Why the REST API lives in the package + +The API is a channel, not a product: every endpoint runs an action the PHP API already runs (`Enums\Capability::actions()`), with the same authorizer, verifier, audit, locks and approvals. Shipped as a separate `settings-http` package it would have to reach into those actions from outside, keep its own copy of the capability list, and drift a release behind the engine whenever an action changed; the design moved it in (D-26) so one pull request changes a capability in every channel at once, and an architecture test fails when a route, the capability enum or a controller disagrees with the others. It costs nothing until it is used: no route is registered, no middleware or rate limiter defined, unless `http.enabled` is on, and it adds no dependency (Sanctum stays a suggestion). It returns JSON only, so the package stays headless. + +## Why change requests are a table + +A write that needs approval has to outlive the request that proposed it: the approver acts later, from another request, maybe another server, and a queue or a cache entry can be evicted before anyone looks. So a proposal is a row, written in the same transaction as its `pending` audit entry, on the store's own connection (one table per connection, like the history), with the proposed value stored exactly as the values table would store it, encrypted for an encrypted definition. Keeping the base version on the row is what makes applying it safe: the approval writes through the version-checked update, so a setting that changed in the meantime is never overwritten and the request becomes `stale`. Requests are keyed by ULID, so the table never depends on `ids.type`, and the table is a schema switch (`approvals.table`) like the history. ## Dependencies diff --git a/docs/configuration.md b/docs/configuration.md index c723c7d..38a7bd7 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -68,6 +68,26 @@ Every key in `config/laranail/settings.php`, read at `config('laranail.settings. | `history.enabled` | `true` (`LARANAIL_SETTINGS_HISTORY`) | schema switch: create the history table and record every change in it | | `history.keep_days` | `365` | how long `prune-history` keeps history entries; null for no age limit | | `history.keep_versions` | `null` | how many versions of each setting `prune-history` keeps; null for all | +| `stores..approvals.keys` | `[]` | key globs (`billing.*`) whose writes become change requests | +| `tables.change_requests` | `settings_change_requests` | the change requests table (after `tables.prefix`), one per connection | +| `tables.stores` | `settings_stores` | the persisted configuration table, on the default store's connection | +| `approvals.table` | `true` | schema switch: create the change requests table | +| `approvals.min_approvals` | `1` | approvals that apply a change | +| `approvals.allow_self` | `false` | let the requester approve their own request | +| `approvals.expire_after` | `7` | days before an open request expires; null for never | +| `approvals.keep_days` | `90` | days `prune-changes` keeps decided requests; null for ever | +| `configuration.persisted` | `false` (`LARANAIL_SETTINGS_PERSISTED_CONFIGURATION`) | schema switch: create `settings_stores` and read persisted stores and layers | +| `configuration.sources` | `['config', 'database', 'runtime']` | merge order of the file, persisted entries and runtime changes; later wins | +| `importers` | `spatie`, `toolkit`, `akaunting` | importers `import --from=` can use, name => class | +| `typed.classes` | `[]` | typed settings classes whose properties are registered as definitions | +| `http.enabled` | `false` (`LARANAIL_SETTINGS_HTTP`) | register the REST API's routes | +| `http.prefix` | `api/settings` | the routes' prefix; they live under `/v1` | +| `http.middleware` | `null` | the routes' middleware; null is `['api', 'auth:sanctum']` with Sanctum, else `['api', 'auth']` | +| `http.rate_limit` | `60` | requests per minute per user (or IP); `0` for none | +| `http.routes.` | `true` | switch a group off: `stores`, `definitions`, `settings`, `history`, `audit`, `approvals`, `categories`, `configuration`, `transfer` | +| `http.idempotency.cache` / `http.idempotency.ttl` | `null` / `86400` | where and how long a write's response is kept for an `Idempotency-Key` | +| `http.owners` | unset | owner alias => model class for URLs; unset uses the morph map | +| `http.page_size` | `50` | the default page size of lists | | `listeners.alerts` | `true` | register the alert listener (alerts still need `alerts.enabled`) | | `listeners.log` | `false` | write every settings event to the logging channel | | `alerts.enabled` | `false` (`LARANAIL_SETTINGS_ALERTS`) | send alerts | @@ -79,7 +99,7 @@ Store names, keys, locales and owner aliases are validated, and a misconfigurati Migration-time switches (`tenancy.mode` among them) are read by `install` and `make-store` and recorded in the schema file; after that the package reads the file, and `doctor` reports configuration that differs from it. See [Schema switches](tools/schema-switches.md). -History is described in [History](tools/history.md), events and the built-in listeners in [Events](tools/events.md), alerts in [Alerts](tools/alerts.md). The cache is described in [Caching](tools/caching.md). Access, audit and logging are described in [Access control](tools/access-control.md) and [Audit and logging](tools/audit-and-logging.md); per-request changes in [Runtime configuration](tools/runtime-configuration.md). +Approvals are described in [Approvals](tools/approvals.md), persisted configuration in [Persisted configuration](tools/persisted-configuration.md), the REST API in [REST API](tools/rest-api.md), typed classes in [Typed settings](tools/typed-settings.md), and import and export in [Import and export](tools/import-export.md). History is described in [History](tools/history.md), events and the built-in listeners in [Events](tools/events.md), alerts in [Alerts](tools/alerts.md). The cache is described in [Caching](tools/caching.md). Access, audit and logging are described in [Access control](tools/access-control.md) and [Audit and logging](tools/audit-and-logging.md); per-request changes in [Runtime configuration](tools/runtime-configuration.md). ## Publishing diff --git a/docs/installation.md b/docs/installation.md index 40e8e4d..5ae38eb 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -45,7 +45,9 @@ package's one migration (tag `laranail::settings-migrations`, `…_create_laranail_settings_tables.php`), and records the schema it will produce in `database/settings-schema.php`. The migration creates, in order, `settings_categories`, the optional `settings_definitions`, one values table per database store (`settings` for the default -store) and `settings_audit`, and `down()` drops them in reverse. Set the +store), `settings_audit`, `settings_history` (`history.enabled`), `settings_change_requests` +(`approvals.table`) and `settings_stores` (`configuration.persisted`), and `down()` drops them in +reverse. Set the [schema switches](tools/schema-switches.md) and `tenancy.mode` before installing. The default store reads the database first, so run the migrations before the first read; until then a read raises `DriverUnavailable`. @@ -87,6 +89,12 @@ and shipped PHP defaults, as before: To start on files and move to the database later, see [Moving from files to the database](recipes/moving-from-files-to-the-database.md). +## The REST API + +The JSON API is off until `http.enabled` is true; nothing is routed before that. It uses the +host's authentication middleware (`auth:sanctum` when laravel/sanctum is installed). See +[REST API](tools/rest-api.md). + ## Supported databases The package is tested on SQLite, MySQL 8.4 and PostgreSQL 17. SQL Server is not supported in diff --git a/docs/recipes/approving-a-change.md b/docs/recipes/approving-a-change.md new file mode 100644 index 0000000..f4cd52a --- /dev/null +++ b/docs/recipes/approving-a-change.md @@ -0,0 +1,38 @@ +# Approve a change + +Require a second person for sensitive settings, then review and apply their requests. + +## Require approval + +```php +$registry->define('billing.plan')->requiresApproval()->register(); +// or, for a group of keys: 'stores' => ['settings' => ['approvals' => ['keys' => ['billing.*']]]] +``` + +Writes now open change requests. Grant `laranail-settings.approve` to reviewers: + +```php +Gate::define('laranail-settings.approve', fn (User $user) => $user->is_admin); +``` + +## Propose, review, approve + +```php +settings()->as($editor)->because('upgrade for ACME')->set('billing.plan', 'pro'); // a change request + +foreach (settings()->as($reviewer)->approvals()->pending()->get() as $request) { + echo "{$request->id} {$request->operation->value} {$request->key} by {$request->requestedById}\n"; +} + +settings()->as($reviewer)->approvals()->approve($id, 'agreed with finance'); +``` + +The editor cannot approve their own request (`approvals.allow_self`). If `billing.plan` changed after the request was opened, approving marks it `stale` instead of overwriting; ask for a new request. Schedule `laranail::settings.prune-changes` daily to expire forgotten requests. + +Over HTTP the same steps are `PUT …/settings/billing.plan` (answers `202`), `GET stores/settings/changes?status=pending` and `POST stores/settings/changes/{id}/approve`. + +See [Approvals](../tools/approvals.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/calling-the-rest-api-with-sanctum.md b/docs/recipes/calling-the-rest-api-with-sanctum.md new file mode 100644 index 0000000..35b72b5 --- /dev/null +++ b/docs/recipes/calling-the-rest-api-with-sanctum.md @@ -0,0 +1,50 @@ +# Call the REST API with Sanctum + +Give a client a Sanctum token that may read settings and change only some of them. + +## Configure + +```bash +composer require laravel/sanctum +``` + +```php +// config/laranail/settings.php +'authentication' => ['resolver' => 'sanctum'], +'http' => ['enabled' => true], // middleware defaults to ['api', 'auth:sanctum'] +``` + +Define the gates (or use the `permissions` authorizer), as for any actor: + +```php +Gate::define('laranail-settings.view', fn (User $user) => true); +Gate::define('laranail-settings.update', fn (User $user) => $user->is_admin); +``` + +## Issue a token + +```php +$token = $user->createToken('deploy-bot', ['settings:view', 'settings:update'])->plainTextToken; +``` + +A token's `settings:` abilities are a ceiling on top of the gates: the token above can never `forget`, `rollback` or `approve`, even for an admin. `settings:*` lifts the ceiling. + +## Call it + +```bash +curl -s https://app.example/api/settings/v1/stores/settings/settings/site.name \ + -H "Authorization: Bearer $TOKEN" -H 'Accept: application/json' + +curl -s -X PUT https://app.example/api/settings/v1/stores/settings/settings/site.name \ + -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -H "If-Match: $ETAG" -H "Idempotency-Key: $(uuidgen)" \ + -d '{"value": "Acme Ltd", "reason": "rebrand"}' +``` + +`412` means the setting changed since you read its ETag; read it again. `428` means the ability needs step-up verification (`verification.abilities`): use the `actor` verifier and send a fresh `verifiedAt`, or leave such abilities to people. Generate a client from `php artisan laranail::settings.openapi`. + +See [REST API](../tools/rest-api.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/migrating-from-spatie-laravel-settings.md b/docs/recipes/migrating-from-spatie-laravel-settings.md new file mode 100644 index 0000000..3b75bef --- /dev/null +++ b/docs/recipes/migrating-from-spatie-laravel-settings.md @@ -0,0 +1,49 @@ +# Migrate from spatie/laravel-settings + +Move spatie/laravel-settings' values into this package, and keep typed classes. + +## 1. Install beside it + +Both packages default to a table named `settings`. Install this one under other names first: + +```php +// config/laranail/settings.php +'tables' => ['prefix' => 'app_'], // app_settings, app_settings_categories, … +``` + +```bash +php artisan laranail::settings.install +php artisan migrate +``` + +## 2. Import + +```bash +php artisan laranail::settings.import :settings --from=spatie # a dry run: read the report +php artisan laranail::settings.import :settings --from=spatie --apply --trusted +``` + +`:settings` is spatie's table on the default connection (`:`). Each row becomes the key `.`; `--trusted` keeps spatie's locks. Values spatie stored encrypted arrive as spatie's ciphertext: define those keys `encrypted()` here and set them again. + +## 3. Keep the typed classes + +A spatie class maps to a typed class with the same group: + +```php +// before: class GeneralSettings extends Spatie\LaravelSettings\Settings { public string $site_name; public static function group(): string { return 'general'; } } + +#[Group('general')] +final class GeneralSettings extends TypedSettings +{ + #[Key('general.site_name')] + public string $siteName = 'Acme'; +} +``` + +Properties map to snake-cased keys by default (`siteName` is `general.site_name`), so `#[Key]` is only needed where the names differ. Replace `GeneralSettings::class` injections with the new class (resolved from the container, it loads itself) and `$settings->save()` keeps working. + +spatie's settings migrations become [settings migrations](../tools/typed-settings.md#settings-migrations-g-17). When nothing reads spatie's table any more, drop it. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/approvals.md b/docs/tools/approvals.md new file mode 100644 index 0000000..3f82d87 --- /dev/null +++ b/docs/tools/approvals.md @@ -0,0 +1,78 @@ +# Approvals + +Four-eyes changes (§16.7): a write to a setting that needs approval becomes a change request, and is applied only after someone else approves it. + +## Which writes need approval + +A write needs approval when the setting's definition says so, or when its key matches one of the store's `approvals.keys` globs: + +```php +$registry->define('billing.plan')->requiresApproval()->register(); +``` + +```php +// config/laranail/settings.php +'stores' => [ + 'settings' => [ + 'layers' => ['database', 'runtime', 'shipped'], + 'approvals' => ['keys' => ['billing.*', 'mail.password']], + ], +], +``` + +Such a write (`set`, `forget`, `lock`, `unlock`) is not made. It opens a change request instead, and `set()` still returns nothing. `propose()` opens one for any setting and returns it: + +```php +$settings->as($editor)->because('INC-7')->set('billing.plan', 'pro'); // a change request +$request = $settings->as($editor)->propose('site.name', 'Acme Ltd'); // ChangeRequest +``` + +Proposing needs the ability of the write it proposes (`update` for a value). The value is validated, cast, encrypted for an encrypted definition, and encoded at once, so an invalid value is refused now and a secret is encrypted at rest in `settings_change_requests`. The request records the setting's current version as its base version. + +## Deciding + +```php +$approvals = $settings->as($reviewer)->approvals(); // the handle's store + +$approvals->pending()->get(); // newest first +$approvals->key('billing.plan')->for($team)->get(); +$approvals->find($id); + +$approvals->approve($id, 'checked the invoice'); +$approvals->reject($id, 'not this quarter'); +$settings->as($editor)->approvals()->cancel($id); // the requester only +``` + +| Rule | Default | Key | +|---|---|---| +| Approvals needed to apply | 1 | `approvals.min_approvals` | +| The requester may approve their own request | no | `approvals.allow_self` | +| Days before an open request expires | 7 | `approvals.expire_after` (null: never) | +| Days a decided request is kept | 90 | `approvals.keep_days` (null: for ever) | + +Approving and rejecting need `approve` on the setting. Listing needs `approve` to see everyone's requests; an actor without it sees only their own. Trusted code without an actor sees and decides everything. + +## Applying + +The last approval applies the change through the normal write pipeline, with the base version as the expected version. A setting that changed after the request was opened is never overwritten: the request becomes `stale` and is returned rather than thrown. An expired request is marked `expired` and refused with `ChangeRequestClosed`. Applied, rejected, cancelled, stale and expired requests cannot be decided again. + +| Status | Meaning | +|---|---| +| `pending` | waiting for its first approval | +| `approved` | has approvals, needs more | +| `applied` | written | +| `rejected`, `cancelled` | nothing written | +| `stale` | the setting changed first; nothing written | +| `expired` | not decided in time; nothing written | + +Events, all dispatched after commit and carrying identifiers only: `ChangeRequested`, `ChangeApproved` (with how many approvals remain), `ChangeApplied` (with the new version), `ChangeRejected`, `ChangeCancelled`, `ChangeStale`. The audit trail records the proposal (`propose`, outcome `pending`), each approval, the rejection or cancellation, and a self-approval refused, each with the change request's id. + +## Where requests are kept + +The `settings_change_requests` table, one per connection a store uses (like the history), created when `approvals.table` is on (the default; a schema switch recorded in the schema file). A store without an active database layer, or a schema recorded without the table, cannot hold requests: a write that needs approval there raises `ApprovalUnavailable`. + +Run `laranail::settings.prune-changes` on a schedule: it marks open requests past their expiry as `expired` and deletes decided ones older than `approvals.keep_days`. `doctor` warns about open requests past their expiry. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/commands.md b/docs/tools/commands.md index 4f5103d..6de2ac1 100644 --- a/docs/tools/commands.md +++ b/docs/tools/commands.md @@ -1,6 +1,6 @@ # Commands -Eleven Artisan commands, all named `laranail::settings.`. +Nineteen Artisan commands, all named `laranail::settings.`. ## The commands @@ -17,6 +17,13 @@ Eleven Artisan commands, all named `laranail::settings.`. | `laranail::settings.prune-history [--days=] [--versions=]` | removes history entries `history.keep_days` / `history.keep_versions` no longer keep | | `laranail::settings.warm [--store=*]` | loads each cached store's global scope into the cache | | `laranail::settings.clear-cache [--store=*]` | resets the cached settings of every store, or the named ones, for every tenant | +| `laranail::settings.prune-changes` | marks open change requests past `approvals.expire_after` as expired and deletes decided ones older than `approvals.keep_days` | +| `laranail::settings.export [path] [--store=] [--with-secrets] [--decrypt] [--confirm=]` | writes a store as a JSON document; secrets redacted unless asked for | +| `laranail::settings.import {source} [--store=] [--from=] [--apply] [--trusted]` | imports an export file, or another package's settings through an importer; a dry run without `--apply` | +| `laranail::settings.diff {path} [--store=]` | compares a store with an export file, by identity only; exits 1 when they differ | +| `laranail::settings.reencrypt` | encrypts every stored secret again under the current key (values, history, change requests) | +| `laranail::settings.rescope {from} {to}` | renames an owner alias in stored values, history and change requests | +| `laranail::settings.openapi [--output=]` | writes the OpenAPI 3.1 document of the REST API (needs `http.enabled`) | Each one delegates to an action (`Actions\PromoteStore`, `Actions\PruneOrphans`, …) that the PHP API uses too, so the console and the API cannot behave differently. @@ -85,6 +92,17 @@ values). `--diff` prints the value at two versions; an encrypted or sensitive va `[protected]` unless `--reveal` is given. `--rollback` writes the value of that version as a new version, through the same action as `rollback()`. See [History](history.md). +## Governance commands + +`export`, `import` and `diff` are described in [Import and export](import-export.md) and +[Importers](importers.md); `reencrypt` and `rescope` in [Re-encryption and rescoping](reencryption.md); +`prune-changes` in [Approvals](approvals.md); `openapi` in [REST API](rest-api.md). Each runs as the +system actor, is audited under its name, and delegates to the same action as the PHP API. + +`doctor` also checks, per database store: encrypted values no current or previous key can read, +open change requests past their expiry, schema drift on the history, change requests and +persisted configuration tables, and persisted configuration entries skipped as invalid. + ## Pruning and access Both prune commands run as the system actor and are audited (a `prune` entry recording what was diff --git a/docs/tools/import-export.md b/docs/tools/import-export.md new file mode 100644 index 0000000..c6a183b --- /dev/null +++ b/docs/tools/import-export.md @@ -0,0 +1,60 @@ +# Import and export + +A store as one portable JSON document: categories by slug, settings by scope, key and locale, never by a numeric id (G-42). + +## The document + +```json +{ + "format": "laranail/settings", + "version": 1, + "store": "settings", + "mode": "redacted", + "exported_at": "2026-11-10T09:00:00+00:00", + "categories": [{"slug": "mail", "title": "Mail"}, {"slug": "smtp", "title": "SMTP", "parent": "mail"}], + "settings": [ + {"scope": "global", "key": "mail.port", "locale": "", "value": 587}, + {"scope": "global", "key": "mail.password", "locale": "", "redacted": true, "encrypted": true}, + {"scope": "user:7", "key": "theme", "locale": "", "value": "dark", "locked": true} + ] +} +``` + +A value is the stored JSON exactly as it is, so nothing is lost whatever its type. Only the current tenant's rows are exported. + +## Secrets (G-10) + +| Mode | Encrypted values | How | +|---|---|---| +| `redacted` (default) | left out | `export()` / `laranail::settings.export` | +| `ciphertext` | the stored ciphertext: importable only under the same `APP_KEY`, or one in `APP_PREVIOUS_KEYS` | `ExportMode::Ciphertext` / `--with-secrets` | +| `plaintext` | decrypted; needs `view_sensitive` too | `ExportMode::Plaintext` / `--decrypt`, which asks you to type the store name (or `--confirm=`) | + +Nothing is ever logged, and the audit entry records the mode and the counts only. + +## Exporting, comparing, importing + +```php +$document = $settings->as($admin)->export(); // needs export +$diff = $settings->as($admin)->compare($document); // added, removed, changed, unchanged, unknown +$preview = $settings->as($admin)->previewImport($document); // what an import would do +$report = $settings->as($admin)->import($document); // needs import +``` + +```bash +php artisan laranail::settings.export storage/settings.json --with-secrets +php artisan laranail::settings.diff storage/settings.json # exits 1 when they differ +php artisan laranail::settings.import storage/settings.json # a dry run +php artisan laranail::settings.import storage/settings.json --apply +php artisan laranail::settings.import storage/settings.json --apply --trusted +``` + +An import creates missing categories first, by slug, parents before children, then writes each setting through the normal write pipeline as the actor: validated and cast under the destination's definition, encrypted, with history and one audit entry per key. A setting that needs approval opens a change request instead (the report lists them). Everything runs in one transaction, so one failed write leaves the store as it was. Redacted values, owners the store does not accept and global values for a dedicated store are skipped, each with its reason in the report. + +Locks and system categories in a document are applied only by a trusted import (`--trusted` on the console); the PHP `import()` and the REST API never apply them. `import` needs step-up verification by default (`verification.abilities`). + +Other packages' settings are read by [importers](importers.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/importers.md b/docs/tools/importers.md new file mode 100644 index 0000000..c5368af --- /dev/null +++ b/docs/tools/importers.md @@ -0,0 +1,55 @@ +# Importers + +Three importers read another package's settings into an export document (G-43), which the normal [import](import-export.md) then writes. None of those packages is needed. + +## Shipped importers + +| Name | Reads | Source | +|---|---|---| +| `spatie` | spatie/laravel-settings' table (`group`, `name`, `payload`, `locked`): each row becomes the global key `.`, its JSON payload decoded, its lock kept for a trusted import | `` or `:
` (default table `settings`) | +| `toolkit` | laranail/toolkit's JSON `SettingsStore` file, flattened (`{"mail": {"host": …}}` is `mail.host`); a list stays one value | the file's absolute path | +| `akaunting` | akaunting/laravel-setting's database table (`key`, `value`); rows its extra columns scope to a model or company are skipped | `` or `:
` | + +Keys are lower-cased and `-` and spaces become `_`; a key that still is not valid fails the import with `InvalidImport` naming it. + +```bash +php artisan laranail::settings.import legacy:settings --from=spatie # a dry run +php artisan laranail::settings.import legacy:settings --from=spatie --apply --trusted +php artisan laranail::settings.import /var/www/storage/app/laranail/settings.json --from=toolkit --apply +``` + +spatie/laravel-settings and this package both default to a table named `settings`. To read spatie's from the same database, point this package at other names (`tables.prefix` or `stores.settings.table`) before installing, or read spatie's table from another connection. + +Values spatie stored encrypted arrive as spatie's ciphertext: define those keys `encrypted()` here and set them again. + +## Your own importer + +Implement `Simtabi\Laranail\Settings\Contracts\Importer` and name it in `importers`: + +```php +final readonly class LegacyIniImporter implements Importer +{ + public function read(string $source, StoreName $store): ExportDocument + { + $settings = []; + + foreach (parse_ini_file($source) ?: [] as $key => $value) { + $settings[] = new ExportedSetting(Scope::global(), new Key($key), Locale::none(), $value); + } + + return new ExportDocument($store->value, settings: $settings, mode: ExportMode::Plaintext, source: 'ini'); + } +} +``` + +```php +'importers' => [ + 'ini' => App\Settings\LegacyIniImporter::class, +], +``` + +An importer only reads. It is built from the container, so it can take its dependencies in its constructor. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/persisted-configuration.md b/docs/tools/persisted-configuration.md new file mode 100644 index 0000000..554a950 --- /dev/null +++ b/docs/tools/persisted-configuration.md @@ -0,0 +1,42 @@ +# Persisted configuration + +Stores, layers and definitions saved in the database and edited through the PHP and REST APIs (§16.11), beside the configuration file. + +## Turning it on + +```php +// config/laranail/settings.php +'configuration' => [ + 'persisted' => true, // a schema switch: creates settings_stores + 'sources' => ['config', 'database', 'runtime'], // merge order, later wins +], +'definitions' => ['table' => true], // persisted definitions live here +``` + +Both are schema switches, recorded in the schema file: turn them on, then `laranail::settings.install` and `migrate`. + +## Editing + +```php +$editor = $settings->as($admin)->persistedConfiguration(); + +$editor->saveLayer('scratch', ['driver' => 'array']); +$editor->saveStore('reports', ['layers' => ['runtime'], 'owners' => ['team']]); +$editor->entries(); // list +$editor->deleteStore('reports'); + +$editor->saveDefinition('site.theme', ['type' => 'string', 'default' => 'light', 'rules' => ['in:light,dark']]); +$editor->deleteDefinition('site.theme'); +``` + +Store and layer entries take the shape the configuration file gives `stores.` and `layers.`; definitions take the attributes of `definitions.`. Each change is validated exactly like configuration before it is stored, needs `manage_stores` (step-up verification by default) or `manage_definitions`, and is audited. A definition from code or configuration cannot be overridden or deleted here, and a persisted store may not change the layers the configuration file gives a store: moving data between drivers is [promote](commands.md)'s job. + +## Loading + +Persisted entries are read on first use, never at boot, once per request or job. An entry that fails validation (a layer that no longer exists, a driver that is not registered) is logged to the operational log and skipped, so a bad row never stops the application from booting; `doctor` lists what was skipped. + +`configuration.sources` decides precedence: with `['config', 'database', 'runtime']` a persisted entry overrides the file, and a change made in code for one request ([runtime configuration](runtime-configuration.md)) overrides both. Put `database` first to let the file win. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/reencryption.md b/docs/tools/reencryption.md new file mode 100644 index 0000000..4a0270f --- /dev/null +++ b/docs/tools/reencryption.md @@ -0,0 +1,36 @@ +# Re-encryption and rescoping + +Two maintenance commands that rewrite stored rows: re-encrypting secrets after a key rotation (§6), and renaming an owner alias (G-30). + +## After rotating `APP_KEY` + +Encrypted values stay readable after a rotation as long as the old key is in `APP_PREVIOUS_KEYS`. To retire the old key, encrypt everything again under the new one: + +```bash +# .env: APP_KEY=, APP_PREVIOUS_KEYS= +php artisan laranail::settings.reencrypt +# then drop the old key from APP_PREVIOUS_KEYS +``` + +It rewrites every encrypted payload of every database store: live values (every tenant's, trashed rows too), the history's old and new values, and pending change requests. A payload no key can read is counted, reported and left exactly as it was, and the command exits 1. Cached values of every store it touched are forgotten. + +From PHP, `ReencryptSettings::handle($actor)` returns the counts. It needs `manage_stores`, which `verification.abilities` lists by default, and is audited (`reencrypt`). + +`doctor` reports encrypted values no current or previous key can read. + +## After renaming a morph alias + +The `scope` of a stored value embeds its owner's morph alias (`user:42`). After renaming an alias in the morph map, rename it in stored settings: + +```bash +php artisan laranail::settings.rescope user member +php artisan laranail::settings.rescope 'App\Models\User' user # rows from before the alias allow-list (G-6) +``` + +Every scope `:` becomes `:` in every database store, with `settable_type` and the per-row slug of `slug_per_row`, in the history, and in change requests, in chunks of 500. The audit trail is left as it was: it records what happened under the old name. Then update the stores' `owners` lists to the new alias. A row whose new identity already exists makes the database refuse the rename, inside a transaction, so nothing changes. + +`doctor` reports scopes whose alias the store does not list. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/rest-api.md b/docs/tools/rest-api.md new file mode 100644 index 0000000..2de20f7 --- /dev/null +++ b/docs/tools/rest-api.md @@ -0,0 +1,108 @@ +# REST API + +A JSON API over every capability of the PHP API (§16.10), in this package and off by default. + +## Turning it on + +```php +// config/laranail/settings.php +'http' => [ + 'enabled' => true, + 'prefix' => 'api/settings', // routes live under api/settings/v1 + 'middleware' => null, // null: ['api', 'auth:sanctum'] with Sanctum, else ['api', 'auth'] + 'rate_limit' => 60, // per minute, per user (or IP); 0 for none + 'routes' => ['approvals' => false], // switch groups off +], +``` + +No route is registered until `enabled` is true. Controllers are built afresh for every request, so under Octane no request's actor, tenant or stores reach the next one. Routes are named `laranail-settings.api.` (the owner form of a settings route adds `owners.`), run through `http.middleware` and the `laranail-settings` rate limiter, and every write runs through the idempotency middleware. The host's middleware authenticates; the configured actor resolver turns the request into an [actor](access-control.md) on the `rest` channel, so with the `sanctum` resolver a token's `settings:` abilities are a ceiling on what it may do. A request nobody is authenticated for is refused (`401`); the API never runs as trusted code. + +## Endpoints + +All under `/{prefix}/v1`. `{owner}` is either nothing (the global value) or `owners/{alias}/{id}/`, an owner by morph alias and id. + +| Method and path | Capability | Ability | +|---|---|---| +| `GET stores` | `stores.index` | `view` (stores the actor may not view are left out) | +| `GET stores/{store}/definitions` | `definitions.index` | `view` | +| `GET stores/{store}/{owner}settings` | `settings.index` | `view`; keys the actor may not view are left out | +| `GET stores/{store}/{owner}settings/{key}` | `settings.show` | `view` (`view_sensitive` for the value) | +| `PUT stores/{store}/{owner}settings/{key}` | `settings.update` | `update` | +| `DELETE stores/{store}/{owner}settings/{key}` | `settings.destroy` | `forget` | +| `POST`, `DELETE stores/{store}/{owner}settings/{key}/lock` | `settings.lock`, `settings.unlock` | `lock`, `unlock` | +| `GET stores/{store}/{owner}settings/{key}/explain` | `settings.explain` | `view` | +| `GET stores/{store}/{owner}settings/{key}/history` | `settings.history` | `view_history` | +| `POST stores/{store}/{owner}settings/{key}/rollback` | `settings.rollback` | `rollback` | +| `GET audit` | `audit.index` | `view_audit` | +| `GET`, `POST stores/{store}/changes` | `changes.index`, `changes.store` | `approve` to see all; the write's ability to propose | +| `GET stores/{store}/changes/{id}` | `changes.show` | as listing | +| `POST stores/{store}/changes/{id}/approve`, `/reject`, `/cancel` | `changes.approve`, … | `approve`; cancel: the requester | +| `GET`, `POST stores/{store}/categories`, `PATCH`, `DELETE …/{slug}` | `categories.*` | `view`, `manage_categories` | +| `GET configuration`, `PUT`, `DELETE configuration/{stores\|layers}/{name}` | `configuration.*` | `manage_stores` | +| `PUT`, `DELETE stores/{store}/definitions/{key}` | `definitions.update`, `definitions.destroy` | `manage_definitions` | +| `POST stores/{store}/export`, `/import`, `/diff` | `transfer.*` | `export` (`view_sensitive` for plaintext), `import` | + +Each capability runs the same action the PHP API runs (`Enums\Capability::actions()`), and an architecture test fails if a route, the capability list or a controller drifts from the others. + +## Requests and responses + +A setting: + +```http +PUT /api/settings/v1/stores/settings/settings/site.name +Content-Type: application/json +If-Match: "4f1c…" +Idempotency-Key: 6c0d1e8e-… + +{"value": "Acme Ltd", "reason": "INC-7"} +``` + +```json +{"data": {"store": "settings", "scope": "global", "key": "site.name", "locale": "", "found": true, + "layer": "database", "from": "global", "version": 2, "redacted": false, "value": "Acme Ltd"}} +``` + +- **ETags.** Every setting response carries an `ETag` derived from store, scope, key, locale and version. Send it back as `If-Match` and the write is checked against that version; a mismatch answers `412`. +- **Approvals.** A write to a setting that needs approval answers `202 Accepted` with the change request. +- **Lists** are `{"data": [...], "meta": {"next_cursor": …}}`; pass `?cursor=` for the next page and `?limit=` (1-200). +- **Locales**: `?locale=fr`. +- **Values the actor may not view** are left out, not masked: a list skips the key, a single setting answers `"redacted": true` without `value`. +- **Idempotency.** A write with an `Idempotency-Key` header is answered from cache when retried (same user, method, path and key) for `http.idempotency.ttl` seconds (24 hours), with `Idempotent-Replayed: true`. + +## Errors + +RFC 9457 problem details, `application/problem+json`: + +```json +{"type": "https://opensource.simtabi.com/documentation/laranail/settings/problems/locked", "title": "Locked", "status": 423, + "detail": "Setting [theme] in store [settings] is locked for scope [user:1].", "instance": "/api/settings/v1/…"} +``` + +| Status | Raised by | +|---|---| +| 401 | no authenticated actor (`actor-required`, `unauthenticated`) | +| 403 | `AccessDenied` | +| 404 | `UnknownStore`, `UnknownSetting`, `UnknownOwner`, `UnknownCategory`, `UnknownChangeRequest` | +| 409 | `ApprovalUnavailable`, `ChangeRequestClosed`, `OwnerNotAllowed`, `StoreNotWritable`, `HistoryUnavailable` | +| 412 | `ConcurrentModification` (`If-Match`) | +| 422 | invalid values, identifiers, imports, definitions or configuration, and request validation (with `errors`) | +| 423 | `LockedSetting` | +| 428 | `VerificationRequired` | +| 429 | the rate limit | +| 503 | `DriverUnavailable` | + +## Owners + +`owners/{alias}/{id}` resolves through the `OwnerResolver` contract. The default takes the alias from `http.owners` (alias => class) or the morph map; an alias in neither is `404`, never a class name from the URL. A `Settable` model is loaded, so its parents take part in reads; a missing record is `404`. Bind your own `OwnerResolver` to change that. + +## OpenAPI + +```bash +php artisan laranail::settings.openapi --output=public/settings-openapi.json +``` + +writes an OpenAPI 3.1 document of the routes as registered, with a schema per resource. The package's tests validate real responses against it. See [Call the REST API with Sanctum](../recipes/calling-the-rest-api-with-sanctum.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/settings-api.md b/docs/tools/settings-api.md index 7258515..017a9d1 100644 --- a/docs/tools/settings-api.md +++ b/docs/tools/settings-api.md @@ -62,10 +62,16 @@ A stored `null` is an answer: `has()` is true and `get()` returns `null`, not th | `history()` | the value history of the handle's store, owner and locale (needs `view_history`); see [History](history.md) | | `rollback($key, $toVersion)` | writes the value of an earlier version as a new version (needs `rollback`); returns the new version | | `historyDiff($key, $from, $to)` | the value at two versions, decrypted only for an actor holding `view_sensitive` | +| `propose($key, $value)` | opens a change request for a value instead of writing it; returns the `ChangeRequest`; see [Approvals](approvals.md) | +| `approvals()` | the store's change requests: list, approve, reject, cancel | +| `export(ExportMode)` | the store as a portable document; see [Import and export](import-export.md) | +| `import($document)` / `previewImport($document)` | write a document through the write pipeline, or report what that would do | +| `compare($document)` | how the store differs from a document, by identity | +| `persistedConfiguration()` | stores, layers and definitions kept in the database; see [Persisted configuration](persisted-configuration.md) | -Writes raise `UnknownSetting` (strict store, no definition), `OwnerNotAllowed`, `LockedSetting`, `InvalidSettingValue`, `EncryptionUnavailable` or `StoreNotWritable`. A handle with an actor can also raise `AccessDenied` or `VerificationRequired`, any handle `ActorRequired` (when an actor is required) and `ApprovalUnavailable`. `history()`, `rollback()` and `historyDiff()` raise `HistoryUnavailable` for a store that keeps no history or a version it does not hold. Every exception extends `SettingsException`. +Writes raise `UnknownSetting` (strict store, no definition), `OwnerNotAllowed`, `LockedSetting`, `InvalidSettingValue`, `EncryptionUnavailable` or `StoreNotWritable`. A handle with an actor can also raise `AccessDenied` or `VerificationRequired`, any handle `ActorRequired` (when an actor is required) and, for a setting that needs approval on a store that cannot hold change requests, `ApprovalUnavailable` (on one that can, the write opens a change request instead). `history()`, `rollback()` and `historyDiff()` raise `HistoryUnavailable` for a store that keeps no history or a version it does not hold. Every exception extends `SettingsException`. -Each write is one action in `Simtabi\Laranail\Settings\Actions` (`SetSetting`, `ForgetSetting`, `LockSetting`, `UnlockSetting`), taking a DTO and the actor. The handle delegates to them, and later channels (console, REST) will too, so behaviour cannot differ between them. +Each write is one action in `Simtabi\Laranail\Settings\Actions` (`SetSetting`, `ForgetSetting`, `LockSetting`, `UnlockSetting`), taking a DTO and the actor. The handle, the console commands and the [REST API](rest-api.md) all delegate to them, so behaviour cannot differ between them. [Typed settings](typed-settings.md) classes read and write through a handle. ## Keys diff --git a/docs/tools/typed-settings.md b/docs/tools/typed-settings.md new file mode 100644 index 0000000..435d469 --- /dev/null +++ b/docs/tools/typed-settings.md @@ -0,0 +1,81 @@ +# Typed settings + +Classes whose typed properties are settings, loaded and saved through the key-value engine (Phase 5). The idea comes from [spatie/laravel-settings](https://github.com/spatie/laravel-settings), credited with thanks; here a typed class is a view over keys, not a store of its own. + +## A typed class + +```php +use Simtabi\Laranail\Settings\Typed\TypedSettings; +use Simtabi\Laranail\Settings\Typed\Attributes\{Encrypted, Group, Key, Store, Type}; + +#[Store('settings')] // optional: the handle's store otherwise +#[Group('mail')] // the key prefix +final class MailSettings extends TypedSettings +{ + public string $fromAddress = 'hello@example.com'; // mail.from_address + public int $port = 25; // mail.port + public Plan $plan = Plan::Free; // a backed enum, stored as its value + public ?DateTimeImmutable $launchedAt = null; // stored as ISO 8601 + #[Encrypted] public ?string $password = null; // defined encrypted by register() + #[Key('site.name')] public string $siteName = 'Acme'; // an exact key + #[Type('enum:region')] public string $region = 'eu'; // the caster alias register() uses +} +``` + +Supported property types: `string`, `int`, `float`, `bool`, `array`, a backed enum, and `DateTimeImmutable` / `CarbonImmutable`, each nullable. Another type is refused with `InvalidDefinition`. + +## Loading and saving + +```php +$mail = MailSettings::load($settings); // or app(MailSettings::class) +$mail->fromAddress; // the stored value, else the default + +$mail = MailSettings::load($settings->as($admin)->for($team)); +$mail->port = 587; +$mail->save(); // writes mail.port only +$mail->save($settings->for($otherTeam)); // writes every property there +``` + +`load()` reads each key through the handle, so the store, owner, locale and actor apply exactly as for `get()`, including the cascade and `view` / `view_sensitive`. `save()` writes each property that changed through `set()`: validation, casting, encryption, locks, approvals, history and audit all apply, as the handle's actor. A stored value the property cannot hold raises `TypeMismatch` naming the key. + +Resolving a typed class from the container loads it through the request's settings handle. + +## Definitions + +`MailSettings::register($registry)` registers a definition per property (its caster alias, its declared default, `#[Encrypted]`) in the class's store, so the key-value API reads the same values with the same types. Keys already defined in code or configuration are left alone. List classes in `typed.classes` to have them registered when definitions are first read: + +```php +'typed' => ['classes' => [App\Settings\MailSettings::class]], +``` + +Register a class with an `#[Encrypted]` property before saving it, or the value is stored like any other. + +## Settings migrations (G-17) + +Rename, move, add and delete keys in a migration, in order with the application's other migrations: + +```php +use Simtabi\Laranail\Settings\Typed\SettingsMigration; + +return new class extends SettingsMigration +{ + public function up(): void + { + $this->settings()->rename('mail.from', 'mail.from_address'); // every owner and locale + $this->settings()->move('legacy.flag', 'settings', 'archive'); + $this->settings()->add('site.name', 'Acme'); // unless a global value exists + $this->settings()->delete('mail.debug'); + } + + public function down(): void + { + $this->settings()->rename('mail.from_address', 'mail.from'); + } +}; +``` + +Values move through the value pipeline (re-validated, re-cast and re-encrypted under the destination's definition) with their history, and locks move with them. A migration runs as the system actor, writes past approvals as trusted code does, and is audited once per step (`migrate`). On a database store every scope is migrated; on a file-only store, the global value. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/src/Actions/Approvals/ApprovalActions.php b/src/Actions/Approvals/ApprovalActions.php new file mode 100644 index 0000000..0fa8851 --- /dev/null +++ b/src/Actions/Approvals/ApprovalActions.php @@ -0,0 +1,21 @@ +store; + $repository = ChangeRequestRepository::of($store); + $request = $repository->get($store->name, $decision->id); + $key = new Key($request->key); + $definition = ($this->definitions)($store, $key); + $subject = Subject::of($store->name, $key, new Locale($request->locale), $request->owner(), $definition); + $now = CarbonImmutable::now(); + + $this->access->authorize($actor, Ability::Approve, $subject); + $this->assertOpen($repository, $request, $now); + + if ($actor instanceof Actor && ! $this->policy->allowSelf && $request->isRequestedBy($actor)) { + $this->access->auditor()->record(AuditAction::Approve, AuditOutcome::Denied, $subject, $actor, $decision->reason, meta: ['change_request' => $request->id, 'refusal' => 'self_approval']); + + throw AccessDenied::for(Ability::Approve, $subject, 'the requester cannot approve their own change request'); + } + + $approvals = array_values(array_unique([...$request->approvals, ChangeRequest::actorKey($actor ?? Actor::system())])); + $remaining = max(0, $this->policy->minApprovals - count($approvals)); + + if ($remaining > 0) { + return $this->record($repository, $request, $subject, $actor, $decision->reason, $approvals, $remaining, $now); + } + + try { + $version = $store->transaction(function () use ($repository, $request, $store, $key, $definition, $subject, $actor, $decision, $approvals, $now): int { + if (! $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Applied, $actor ?? Actor::system(), $decision->reason, $now, $approvals)) { + throw new ChangeRequestClosed(sprintf('Change request [%s] was decided by somebody else first.', $request->id)); + } + + $version = $this->apply($request, $store, $key, $definition, $actor, $decision->reason); + + $this->access->auditor()->record(AuditAction::Approve, AuditOutcome::Allowed, $subject, $actor, $decision->reason, $request->baseVersion > 0 ? $request->baseVersion : null, $version, [ + 'change_request' => $request->id, + 'operation' => $request->operation->value, + ]); + + return $version; + }); + } catch (ConcurrentModification) { + // The setting moved on since the request was opened: never overwrite it. + $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Stale, $actor ?? Actor::system(), $decision->reason, $now, $approvals); + $this->access->auditor()->record(AuditAction::Approve, AuditOutcome::Failed, $subject, $actor, $decision->reason, meta: ['change_request' => $request->id, 'refusal' => 'stale']); + $this->events->dispatch(new ChangeStale($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); + + return $repository->get($store->name, $request->id); + } + + $this->events->dispatch(new ChangeApproved($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); + $this->events->dispatch(new ChangeApplied($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value, $version)); + + return $repository->get($store->name, $request->id); + } + + /** @param list $approvals */ + private function record(ChangeRequestRepository $repository, ChangeRequest $request, Subject $subject, ?Actor $actor, ?string $reason, array $approvals, int $remaining, CarbonImmutable $now): ChangeRequest + { + if (! $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Approved, null, null, $now, $approvals)) { + throw new ChangeRequestClosed(sprintf('Change request [%s] was decided by somebody else first.', $request->id)); + } + + $this->access->auditor()->record(AuditAction::Approve, AuditOutcome::Pending, $subject, $actor, $reason, meta: ['change_request' => $request->id, 'remaining' => $remaining]); + $this->events->dispatch(new ChangeApproved($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value, $remaining)); + + return $repository->get($subject->store, $request->id); + } + + private function assertOpen(ChangeRequestRepository $repository, ChangeRequest $request, CarbonImmutable $now): void + { + if ($request->status->isOpen() && $request->isExpired($now)) { + $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Expired, null, null, $now); + + throw new ChangeRequestClosed(sprintf('Change request [%s] expired at %s.', $request->id, $request->expiresAt?->toIso8601String())); + } + + if (! $request->status->isOpen()) { + throw new ChangeRequestClosed(sprintf('Change request [%s] is %s and can no longer be decided.', $request->id, $request->status->value)); + } + } + + /** + * Write the requested change, checked against the base version; returns the new version. + * + * @throws ConcurrentModification when the setting is no longer at the base version + */ + private function apply(ChangeRequest $request, Store $store, Key $key, ?Definition $definition, ?Actor $actor, ?string $reason): int + { + $locale = new Locale($request->locale); + $owner = $request->owner(); + $scope = Scope::of($owner); + $writer = $this->writer->causedBy($actor, $reason ?? 'change request ' . $request->id); + + if ($request->operation === ChangeOperation::Set) { + $value = $this->pipeline->fromRecord(new Record($scope, $key, $locale, $request->payload, $request->type, $request->encrypted), $definition); + + return $writer->setExpecting($store, $key, $locale, $owner, $definition, $value, $request->baseVersion)->version; + } + + $current = $store->writableLayer()->driver->load($store->name, [$scope])->find($scope, $key, $locale)->version ?? 0; + + if ($current !== $request->baseVersion) { + throw new ConcurrentModification(sprintf('Setting [%s] in store [%s] for scope [%s] is at version %d, not %d.', $key, $store->name, $scope, $current, $request->baseVersion)); + } + + return match ($request->operation) { + ChangeOperation::Forget => $writer->forget($store, $key, $locale, $owner, $definition)->version ?? $current, + ChangeOperation::Lock => $writer->lock($store, $key, $locale, $owner, $definition)->version, + default => $writer->unlock($store, $key, $locale, $owner, $definition)->version, + }; + } +} diff --git a/src/Actions/Approvals/CancelChange.php b/src/Actions/Approvals/CancelChange.php new file mode 100644 index 0000000..d4b04b3 --- /dev/null +++ b/src/Actions/Approvals/CancelChange.php @@ -0,0 +1,68 @@ +store; + $repository = ChangeRequestRepository::of($store); + $request = $repository->get($store->name, $decision->id); + $subject = new Subject($store->name, new Key($request->key), $request->owner(), new Locale($request->locale)); + + if ($actor instanceof Actor && ! $actor->isSystem() && ! $request->isRequestedBy($actor)) { + $this->access->auditor()->record(AuditAction::Cancel, AuditOutcome::Denied, $subject, $actor, $decision->reason, meta: ['change_request' => $request->id, 'refusal' => 'not_requester']); + + throw AccessDenied::for(Ability::Update, $subject, 'only the requester can cancel a change request'); + } + + if (! $actor instanceof Actor) { + $this->access->assertActorNotRequired(Ability::Update, $subject); + } + + $store->transaction(function () use ($repository, $request, $actor, $decision, $subject): void { + if (! $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Cancelled, $actor ?? Actor::system(), $decision->reason, CarbonImmutable::now())) { + throw new ChangeRequestClosed(sprintf('Change request [%s] is %s and can no longer be cancelled.', $request->id, $request->status->value)); + } + + $this->access->auditor()->record(AuditAction::Cancel, AuditOutcome::Allowed, $subject, $actor, $decision->reason, meta: ['change_request' => $request->id]); + }); + + $this->events->dispatch(new ChangeCancelled($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); + + return $repository->get($store->name, $request->id); + } +} diff --git a/src/Actions/Approvals/ProposeChange.php b/src/Actions/Approvals/ProposeChange.php new file mode 100644 index 0000000..b85507b --- /dev/null +++ b/src/Actions/Approvals/ProposeChange.php @@ -0,0 +1,98 @@ +target; + $store = $target->store; + $subject = $target->subject(); + + $this->access->authorize($actor, $proposal->operation->ability(), $subject); + $repository = ChangeRequestRepository::of($store); + + if (! $target->definition instanceof Definition && $store->strict) { + throw new UnknownSetting(sprintf('Store [%s] is strict and has no definition for [%s].', $store->name, $target->key)); + } + + if ($target->owner instanceof OwnerRef && ! $store->accepts($target->owner->alias)) { + throw new OwnerNotAllowed(sprintf('Store [%s] does not accept owner alias [%s].', $store->name, $target->owner->alias)); + } + + $scope = $subject->scope(); + $payload = $proposal->operation === ChangeOperation::Set ? $this->pipeline->toPayload($target->key, $proposal->value, $target->definition) : null; + $base = $store->writableLayer()->driver->load($store->name, [$scope])->find($scope, $target->key, $target->locale)->version ?? 0; + $now = CarbonImmutable::now(); + $requester = $actor ?? Actor::system($target->reason); + + $request = $store->transaction(function () use ($repository, $store, $scope, $target, $proposal, $payload, $base, $now, $requester, $subject, $actor): ChangeRequest { + $request = $repository->create([ + 'store' => $store->name->value, + 'scope' => $scope->value, + 'key' => $target->key->value, + 'locale' => $target->locale->value, + 'operation' => $proposal->operation, + 'payload' => $payload, + 'type' => $target->definition?->type, + 'encrypted' => $payload !== null && $target->definition instanceof Definition && $target->definition->encrypted, + 'base_version' => $base, + 'reason' => $target->reason, + 'expires_at' => $this->policy->expireAfterDays === null ? null : $now->addDays($this->policy->expireAfterDays), + ], $requester, $now); + + $this->access->auditor()->record(AuditAction::Propose, AuditOutcome::Pending, $subject, $actor, $target->reason, versionFrom: $base > 0 ? $base : null, meta: [ + 'change_request' => $request->id, + 'operation' => $proposal->operation->value, + ]); + + return $request; + }); + + $this->events->dispatch(new ChangeRequested($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); + + return $request; + } +} diff --git a/src/Actions/Approvals/PruneChanges.php b/src/Actions/Approvals/PruneChanges.php new file mode 100644 index 0000000..7256e49 --- /dev/null +++ b/src/Actions/Approvals/PruneChanges.php @@ -0,0 +1,60 @@ +stores->default()->name); + $this->access->authorize($actor, Ability::Prune, $subject); + + $now = CarbonImmutable::now(); + $cutoff = $this->policy->keepDays === null ? null : $now->subDays($this->policy->keepDays); + $totals = ['expired' => 0, 'deleted' => 0]; + $seen = []; + + foreach ($this->stores->all() as $store) { + $database = $store->database(); + + if (! $database instanceof DatabaseDriver || ! $database->shape()->changeRequestsTable || isset($seen[$database->connectionName()])) { + continue; + } + + $seen[$database->connectionName()] = true; + [$expired, $deleted] = new ChangeRequestRepository($database)->sweep($now, $cutoff, $store->name); + $totals['expired'] += $expired; + $totals['deleted'] += $deleted; + } + + $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'change_requests'] + $totals); + + return $totals; + } +} diff --git a/src/Actions/Approvals/QueryChanges.php b/src/Actions/Approvals/QueryChanges.php new file mode 100644 index 0000000..1206a2f --- /dev/null +++ b/src/Actions/Approvals/QueryChanges.php @@ -0,0 +1,46 @@ + */ + public function handle(ChangeFilter $filter, ?Actor $actor = null, int $limit = 100, ?string $after = null): array + { + $store = $this->stores->get($filter->store); + $subject = new Subject($store->name); + + if (! $actor instanceof Actor) { + $this->access->assertActorNotRequired(Ability::Approve, $subject); + } + + $requests = ChangeRequestRepository::of($store)->list($filter, $limit, $after); + + if (! $actor instanceof Actor || $actor->isSystem() || $this->access->allows($actor, Ability::Approve, $subject)) { + return $requests; + } + + return array_values(array_filter($requests, static fn (ChangeRequest $request): bool => $request->isRequestedBy($actor))); + } +} diff --git a/src/Actions/Approvals/RejectChange.php b/src/Actions/Approvals/RejectChange.php new file mode 100644 index 0000000..9e11a38 --- /dev/null +++ b/src/Actions/Approvals/RejectChange.php @@ -0,0 +1,63 @@ +store; + $repository = ChangeRequestRepository::of($store); + $request = $repository->get($store->name, $decision->id); + $key = new Key($request->key); + $subject = Subject::of($store->name, $key, new Locale($request->locale), $request->owner(), ($this->definitions)($store, $key)); + + $this->access->authorize($actor, Ability::Approve, $subject); + + $store->transaction(function () use ($repository, $request, $actor, $decision, $subject): void { + if (! $repository->transition($request, [ChangeStatus::Pending, ChangeStatus::Approved], ChangeStatus::Rejected, $actor ?? Actor::system(), $decision->reason, CarbonImmutable::now())) { + throw new ChangeRequestClosed(sprintf('Change request [%s] is %s and can no longer be decided.', $request->id, $request->status->value)); + } + + $this->access->auditor()->record(AuditAction::Reject, AuditOutcome::Allowed, $subject, $actor, $decision->reason, meta: ['change_request' => $request->id]); + }); + + $this->events->dispatch(new ChangeRejected($request->id, $request->store, $request->scope, $request->key, $request->locale, $request->operation->value)); + + return $repository->get($store->name, $request->id); + } +} diff --git a/src/Actions/Categories/ListCategories.php b/src/Actions/Categories/ListCategories.php new file mode 100644 index 0000000..bda515b --- /dev/null +++ b/src/Actions/Categories/ListCategories.php @@ -0,0 +1,29 @@ + */ + public function handle(Store $store, ?Actor $actor = null): array + { + $this->access->authorize($actor, Ability::View, new Subject($store->name)); + + return CategoryRepository::of($store)->all(); + } +} diff --git a/src/Actions/Configuration/ConfigurationActions.php b/src/Actions/Configuration/ConfigurationActions.php new file mode 100644 index 0000000..28c5e67 --- /dev/null +++ b/src/Actions/Configuration/ConfigurationActions.php @@ -0,0 +1,17 @@ +stores->default()->name); + $this->access->authorize($actor, Ability::ManageStores, $subject); + + $deleted = $this->persisted->delete($entry->kind, $entry->name); + $this->access->auditor()->record(AuditAction::ManageStores, AuditOutcome::Allowed, $subject, $actor, meta: ['operation' => 'delete', 'kind' => $entry->kind, 'name' => $entry->name, 'existed' => $deleted]); + + return $deleted; + } +} diff --git a/src/Actions/Configuration/DeleteDefinition.php b/src/Actions/Configuration/DeleteDefinition.php new file mode 100644 index 0000000..8f37546 --- /dev/null +++ b/src/Actions/Configuration/DeleteDefinition.php @@ -0,0 +1,51 @@ +name, $settingKey); + $this->access->authorize($actor, Ability::ManageDefinitions, $subject); + + $database = $store->database(); + + if (! $database instanceof DatabaseDriver || ! $database->shape()->definitionsTable) { + throw new InvalidConfiguration(sprintf('Store [%s] has no definitions table.', $store->name)); + } + + $deleted = new DefinitionsRepository($database, $this->encoder)->delete($store->name, $settingKey); + $this->definitions->forget($store); + $this->access->auditor()->record(AuditAction::ManageDefinitions, AuditOutcome::Allowed, $subject, $actor, meta: ['operation' => 'delete', 'existed' => $deleted]); + + return $deleted; + } +} diff --git a/src/Actions/Configuration/ListConfigurationEntries.php b/src/Actions/Configuration/ListConfigurationEntries.php new file mode 100644 index 0000000..81d5cb0 --- /dev/null +++ b/src/Actions/Configuration/ListConfigurationEntries.php @@ -0,0 +1,41 @@ + */ + public function handle(?Actor $actor = null): array + { + $this->access->authorize($actor, Ability::ManageStores, new Subject($this->stores->default()->name)); + + $entries = []; + + foreach ($this->persisted->layers() as $name => $config) { + $entries[] = new ConfigurationEntry(ConfigurationEntry::LAYER, (string) $name, $config); + } + + foreach ($this->persisted->stores() as $name => $config) { + $entries[] = new ConfigurationEntry(ConfigurationEntry::STORE, (string) $name, $config); + } + + return $entries; + } +} diff --git a/src/Actions/Configuration/SaveConfigurationEntry.php b/src/Actions/Configuration/SaveConfigurationEntry.php new file mode 100644 index 0000000..609d9ed --- /dev/null +++ b/src/Actions/Configuration/SaveConfigurationEntry.php @@ -0,0 +1,42 @@ +stores->default()->name); + $this->access->authorize($actor, Ability::ManageStores, $subject); + + $entry->kind === ConfigurationEntry::STORE + ? $this->persisted->saveStore($entry->name, $entry->config) + : $this->persisted->saveLayer($entry->name, $entry->config); + + $this->access->auditor()->record(AuditAction::ManageStores, AuditOutcome::Allowed, $subject, $actor, meta: ['operation' => 'save', 'kind' => $entry->kind, 'name' => $entry->name]); + } +} diff --git a/src/Actions/Configuration/SaveDefinition.php b/src/Actions/Configuration/SaveDefinition.php new file mode 100644 index 0000000..a20eb8d --- /dev/null +++ b/src/Actions/Configuration/SaveDefinition.php @@ -0,0 +1,75 @@ + $attributes + * + * @throws InvalidDefinition + * @throws InvalidConfiguration when the store has no definitions table + */ + public function handle(Store $store, string $key, array $attributes, ?Actor $actor = null): Definition + { + $settingKey = new Key($key); + $subject = new Subject($store->name, $settingKey); + $this->access->authorize($actor, Ability::ManageDefinitions, $subject); + + if ($this->registry->find($store->name, $settingKey) instanceof Definition) { + throw new InvalidDefinition(sprintf('Setting [%s] in store [%s] is defined in code or configuration; change it there.', $settingKey, $store->name)); + } + + $definition = $this->registry->fromAttributes($key, $attributes, $store->name); + $this->repository($store)->save($store->name, $definition); + $this->definitions->forget($store); + + $this->access->auditor()->record(AuditAction::ManageDefinitions, AuditOutcome::Allowed, $subject, $actor, meta: ['operation' => 'save']); + + return $definition; + } + + /** @throws InvalidConfiguration */ + private function repository(Store $store): DefinitionsRepository + { + $database = $store->database(); + + if (! $database instanceof DatabaseDriver || ! $database->shape()->definitionsTable) { + throw new InvalidConfiguration(sprintf('Store [%s] has no definitions table: turn on laranail.settings.definitions.table and migrate.', $store->name)); + } + + return new DefinitionsRepository($database, $this->encoder); + } +} diff --git a/src/Actions/DiagnoseSettings.php b/src/Actions/DiagnoseSettings.php index d0b4d4e..621b8f0 100644 --- a/src/Actions/DiagnoseSettings.php +++ b/src/Actions/DiagnoseSettings.php @@ -4,6 +4,8 @@ namespace Simtabi\Laranail\Settings\Actions; +use Closure; +use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Enums\IdType; use Simtabi\Laranail\Settings\Stores\Store; @@ -11,17 +13,21 @@ use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; +use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Package\Tools\Services\Doctor\DoctorResult; use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; +use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** * What `laranail::settings.doctor` reports, per store with a database layer: readiness (the * connection answers and the tables exist), schema drift (columns this release reads that the * tables lack), scopes naming a class instead of a morph alias or an alias the store does not - * list (G-6, G-30), and rows whose category belongs to another store (G-33). Read-only. + * list (G-6, G-30), rows whose category belongs to another store (G-33), encrypted values no key + * can read any more (§6), open change requests past their expiry (§16.7) and persisted + * configuration entries that were skipped as invalid (§16.11). Read-only. * * Schema drift is three comparisons (§4.0): the schema file against the configuration (a switch * changed after migrating changes nothing until a migration does), the file's shape version @@ -40,9 +46,18 @@ private const array AUDIT_COLUMNS = ['id', 'occurred_at', 'action', 'outcome', 'store', 'scope', 'key', 'locale', 'version_from', 'version_to', 'change_request', 'actor_type', 'actor_alias', 'actor_id', 'channel', 'ip', 'user_agent', 'request_id', 'reason', 'meta']; + private const array HISTORY_COLUMNS = ['id', 'store', 'setting_ref', 'scope', 'key', 'locale', 'operation', 'old_value', 'new_value', 'old_type', 'new_type', 'old_encrypted', 'new_encrypted', 'version', 'causer_type', 'causer_alias', 'causer_id', 'reason', 'created_at']; + + private const array CHANGE_REQUEST_COLUMNS = ['id', 'store', 'scope', 'key', 'locale', 'operation', 'payload', 'type', 'is_encrypted', 'base_version', 'status', 'requested_by_type', 'requested_by_alias', 'requested_by_id', 'approvals', 'decided_by_type', 'decided_by_alias', 'decided_by_id', 'decided_at', 'reason', 'decision_reason', 'expires_at', 'created_at', 'updated_at']; + + private const array STORES_COLUMNS = ['id', 'kind', 'name', 'config', 'created_at', 'updated_at']; + + /** @param (Closure(): list)|null $persisted problems found in the persisted configuration */ public function __construct( private StoreRegistry $stores, private ?SchemaShapeRepository $shapes = null, + private ?ValueEncrypter $encrypter = null, + private ?Closure $persisted = null, ) {} /** @return list */ @@ -71,6 +86,21 @@ public function handle(): array $findings[] = $this->drift($store, $database); $findings[] = $this->scopes($store, $database); $findings[] = $this->categories($store, $database); + + if ($this->encrypter instanceof ValueEncrypter) { + $findings[] = $this->encryption($store, $database, $this->encrypter); + } + + if ($database->shape()->changeRequestsTable) { + $findings[] = $this->changeRequests($store, $database); + } + } + + if ($this->persisted instanceof Closure) { + $problems = ($this->persisted)(); + $findings[] = new Finding('persisted configuration', 'Every persisted store and layer entry is valid', $problems === [] + ? DoctorResult::pass('Every persisted entry is valid (or persisted configuration is off).') + : DoctorResult::warn('Persisted entries skipped as invalid: ' . implode('; ', $problems), ['problems' => $problems])); } return $findings; @@ -149,6 +179,18 @@ private function drift(Store $store, DatabaseDriver $database): Finding $expected[$shape->names->definitions()] = self::DEFINITION_COLUMNS; } + if ($shape->historyTable) { + $expected[$shape->names->history()] = [...self::HISTORY_COLUMNS, ...$tenant]; + } + + if ($shape->changeRequestsTable) { + $expected[$shape->names->changeRequests()] = [...self::CHANGE_REQUEST_COLUMNS, ...$tenant]; + } + + if ($shape->storesTable && $database->connectionName() === $this->stores->default()->database()?->connectionName()) { + $expected[$shape->names->stores()] = self::STORES_COLUMNS; + } + $inspector = new SchemaInspector($database); foreach ($expected as $table => $columns) { @@ -231,6 +273,50 @@ private function scopes(Store $store, DatabaseDriver $database): Finding : DoctorResult::warn('Scopes use aliases the store does not list (renamed or removed?): ' . implode(', ', array_keys($unlisted)), ['aliases' => array_keys($unlisted)])); } + /** + * Encrypted values no current or previous key can read (a key rotated without `reencrypt`, + * or with the old key dropped from APP_PREVIOUS_KEYS). The current tenant's rows. + */ + private function encryption(Store $store, DatabaseDriver $database, ValueEncrypter $encrypter): Finding + { + $unreadable = []; + $encrypted = 0; + + try { + $records = $database->load($store->name, array_values(array_filter(array_map(Scope::fromString(...), $database->scopes($store->name)))))->all(); + } catch (SettingsException $exception) { + return new Finding("{$store->name}: encryption", 'Every encrypted value can be decrypted', DoctorResult::fail($exception->getMessage())); + } + + foreach ($records as $record) { + if (! $record->encrypted || $record->payload === null) { + continue; + } + + $encrypted++; + + try { + $encrypter->decrypt($record->payload); + } catch (SettingsException) { + $unreadable[] = $record->identity(); + } + } + + return new Finding("{$store->name}: encryption", 'Every encrypted value can be decrypted', $unreadable === [] + ? DoctorResult::pass(sprintf('%d encrypted value(s), all readable.', $encrypted)) + : DoctorResult::fail(sprintf('%d encrypted value(s) cannot be decrypted with the current or previous keys (put the old key in APP_PREVIOUS_KEYS, then run laranail::settings.reencrypt): %s', count($unreadable), implode(', ', $unreadable)), ['unreadable' => $unreadable])); + } + + /** Open change requests past their expiry: prune-changes has not run. */ + private function changeRequests(Store $store, DatabaseDriver $database): Finding + { + $overdue = new ChangeRequestRepository($database)->overdue(CarbonImmutable::now(), $store->name); + + return new Finding("{$store->name}: change requests", 'No open change request is past its expiry', $overdue === 0 + ? DoctorResult::pass('No overdue change requests.') + : DoctorResult::warn(sprintf('%d open change request(s) are past their expiry: schedule laranail::settings.prune-changes.', $overdue))); + } + private function categories(Store $store, DatabaseDriver $database): Finding { $count = new SchemaInspector($database)->crossStoreCategoryLinks($store->name); diff --git a/src/Actions/ForgetSetting.php b/src/Actions/ForgetSetting.php index e86284c..dc41947 100644 --- a/src/Actions/ForgetSetting.php +++ b/src/Actions/ForgetSetting.php @@ -6,7 +6,10 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Data\SettingTarget; +use Simtabi\Laranail\Settings\Data\ChangeProposal; +use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; /** @@ -20,14 +23,15 @@ public function __construct( private WriteGuard $guard, ) {} - public function handle(SettingTarget $target, ?Actor $actor = null): void + /** @return ?ChangeRequest the change request opened instead, when the setting needs approval */ + public function handle(SettingTarget $target, ?Actor $actor = null): ?ChangeRequest { - $this->guard->run(Ability::Forget, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target, $actor): array { + return $this->guard->run(Ability::Forget, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target, $actor): array { $removed = $override ? $this->writer->causedBy($actor, $target->reason)->forgetOverridingLock($target->store, $target->key, $target->locale, $target->owner, $target->definition) : $this->writer->causedBy($actor, $target->reason)->forget($target->store, $target->key, $target->locale, $target->owner, $target->definition); return [$removed?->version, null]; - }); + }, proposal: new ChangeProposal($target, ChangeOperation::Forget)); } } diff --git a/src/Actions/LockSetting.php b/src/Actions/LockSetting.php index ea204a4..9d27973 100644 --- a/src/Actions/LockSetting.php +++ b/src/Actions/LockSetting.php @@ -6,7 +6,10 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Data\SettingTarget; +use Simtabi\Laranail\Settings\Data\ChangeProposal; +use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; /** @@ -19,12 +22,13 @@ public function __construct( private WriteGuard $guard, ) {} - public function handle(SettingTarget $target, ?Actor $actor = null): void + /** @return ?ChangeRequest the change request opened instead, when the setting needs approval */ + public function handle(SettingTarget $target, ?Actor $actor = null): ?ChangeRequest { - $this->guard->run(Ability::Lock, $target, $actor, respectsLocks: false, write: function () use ($target, $actor): array { + return $this->guard->run(Ability::Lock, $target, $actor, respectsLocks: false, write: function () use ($target, $actor): array { $after = $this->writer->causedBy($actor, $target->reason)->lock($target->store, $target->key, $target->locale, $target->owner, $target->definition); return [$after->version > 1 ? $after->version - 1 : null, $after->version]; - }); + }, proposal: new ChangeProposal($target, ChangeOperation::Lock)); } } diff --git a/src/Actions/MigrateSettings.php b/src/Actions/MigrateSettings.php new file mode 100644 index 0000000..ca3f697 --- /dev/null +++ b/src/Actions/MigrateSettings.php @@ -0,0 +1,117 @@ +stores->get($step->fromStore); + $subject = new Subject($from->name, $step->fromKey); + $this->access->authorize($actor, Ability::ManageDefinitions, $subject); + + $writer = $this->writer->causedBy($actor ?? Actor::system('settings migration'), 'settings migration: ' . $step->operation . ' ' . $step->fromKey); + $records = $this->records($from, $step->fromKey); + + $touched = $from->transaction(function () use ($step, $from, $records, $writer): int { + if ($step->operation === SettingsMigrationStep::ADD) { + return $records === [] || ! array_any($records, static fn (Record $record): bool => $record->scope->isGlobal()) + ? $this->add($from, $step, $writer) + : 0; + } + + $to = $step->toStore instanceof StoreName ? $this->stores->get($step->toStore) : null; + $touched = 0; + + foreach ($records as $record) { + $owner = $record->scope->owner(); + + if ($to instanceof Store && $step->toKey instanceof Key && $record->payload !== null) { + $value = $this->pipeline->fromRecord($record, ($this->definitions)($from, $step->fromKey)); + $writer->set($to, $step->toKey, $record->locale, $owner, ($this->definitions)($to, $step->toKey), $value); + + if ($record->locked) { + $writer->lock($to, $step->toKey, $record->locale, $owner); + } + } + + if ($record->locked) { + $writer->unlock($from, $step->fromKey, $record->locale, $owner); + } + + $writer->forget($from, $step->fromKey, $record->locale, $owner, null); + $touched++; + } + + return $touched; + }); + + $this->access->auditor()->record(AuditAction::Migrate, AuditOutcome::Allowed, $subject, $actor, meta: [ + 'operation' => $step->operation, + 'to_store' => $step->toStore?->value, + 'to_key' => $step->toKey?->value, + 'touched' => $touched, + ]); + + return $touched; + } + + private function add(Store $store, SettingsMigrationStep $step, SettingWriter $writer): int + { + $writer->set($store, $step->fromKey, Locale::none(), null, ($this->definitions)($store, $step->fromKey), $step->value); + + return 1; + } + + /** @return list every row of the key: every scope on a database store, else the global one */ + private function records(Store $store, Key $key): array + { + $database = $store->database(); + $scopes = $database instanceof DatabaseDriver + ? array_values(array_filter(array_map(Scope::fromString(...), $database->scopes($store->name)))) + : [Scope::global()]; + $layer = $database instanceof DatabaseDriver ? $database : $store->writableLayer()->driver; + + return array_values(array_filter($layer->load($store->name, $scopes)->all(), static fn (Record $record): bool => $record->key->value === $key->value)); + } +} diff --git a/src/Actions/Reads/ExplainSetting.php b/src/Actions/Reads/ExplainSetting.php new file mode 100644 index 0000000..c7c8c4c --- /dev/null +++ b/src/Actions/Reads/ExplainSetting.php @@ -0,0 +1,25 @@ +targets->handle($this->settings, $address, $actor)->explain($address->key); + } +} diff --git a/src/Actions/Reads/ListDefinitions.php b/src/Actions/Reads/ListDefinitions.php new file mode 100644 index 0000000..d9ee0d2 --- /dev/null +++ b/src/Actions/Reads/ListDefinitions.php @@ -0,0 +1,46 @@ + */ + public function handle(Store $store, ?Actor $actor = null): array + { + $this->access->authorize($actor, Ability::View, new Subject($store->name)); + + $definitions = $this->database->all($store); + + foreach ($this->registry->all() as $definition) { + if ($definition->store->value === $store->name->value) { + $definitions[$definition->key->value] = $definition; + } + } + + ksort($definitions); + + return array_values($definitions); + } +} diff --git a/src/Actions/Reads/ListStores.php b/src/Actions/Reads/ListStores.php new file mode 100644 index 0000000..6876222 --- /dev/null +++ b/src/Actions/Reads/ListStores.php @@ -0,0 +1,35 @@ + */ + public function handle(?Actor $actor = null): array + { + $stores = array_values($this->stores->all()); + + if (! $actor instanceof Actor) { + $this->access->assertActorNotRequired(Ability::View, new Subject($this->stores->default()->name)); + + return $stores; + } + + return array_values(array_filter($stores, fn (Store $store): bool => $actor->isSystem() || $this->access->allows($actor, Ability::View, new Subject($store->name)))); + } +} diff --git a/src/Actions/Reads/ReadHistory.php b/src/Actions/Reads/ReadHistory.php new file mode 100644 index 0000000..273fe75 --- /dev/null +++ b/src/Actions/Reads/ReadHistory.php @@ -0,0 +1,31 @@ +targets->handle($this->settings, $address, $actor)->history()->key($address->key); + + return ($address->owner === null ? $history->global() : $history)->paginate($perPage, $cursor); + } +} diff --git a/src/Actions/Reads/ReadSetting.php b/src/Actions/Reads/ReadSetting.php new file mode 100644 index 0000000..01acdf1 --- /dev/null +++ b/src/Actions/Reads/ReadSetting.php @@ -0,0 +1,41 @@ +targets->handle($this->settings, $address, $actor); + $explanation = $handle->explain($address->key); + $lookup = $explanation->lookup; + $version = $this->targets->version($address); + + if ($lookup->isRedacted()) { + return new SettingView($address, true, null, $lookup->layer(), $lookup->scope()?->value, $version, redacted: true); + } + + return new SettingView($address, $lookup->isFound(), $lookup->isFound() ? $lookup->value() : null, $lookup->layer(), $lookup->scope()?->value, $version); + } +} diff --git a/src/Actions/Reads/ReadSettings.php b/src/Actions/Reads/ReadSettings.php new file mode 100644 index 0000000..d00d04d --- /dev/null +++ b/src/Actions/Reads/ReadSettings.php @@ -0,0 +1,74 @@ +, next: ?string} */ + public function handle(SettingAddress $scope, ?Actor $actor = null, int $limit = 50, ?string $after = null): array + { + $store = $this->targets->store($scope->store); + $owner = Scope::of($scope->ownerRef()); + $keys = []; + + foreach ($store->load([$owner]) as $records) { + foreach ($records->all() as $record) { + $keys[$record->key->value] = true; + } + } + + foreach ($this->definitions->all() as $definition) { + if ($definition->store->value === $store->name->value) { + $keys[$definition->key->value] = true; + } + } + + $keys = array_keys($keys); + sort($keys); + $keys = array_values(array_filter($keys, static fn (string $key): bool => $after === null || strcmp($key, $after) > 0)); + $items = []; + $last = null; + + foreach ($keys as $key) { + if (count($items) >= $limit) { + return ['items' => $items, 'next' => $last]; + } + + $last = $key; + + try { + $view = $this->read->handle(new SettingAddress($scope->store, $key, $scope->owner, $scope->locale), $actor); + } catch (AccessDenied) { + continue; + } + + if ($view->found && ! $view->redacted) { + $items[] = $view; + } + } + + return ['items' => $items, 'next' => null]; + } +} diff --git a/src/Actions/ReencryptSettings.php b/src/Actions/ReencryptSettings.php new file mode 100644 index 0000000..85ea9a1 --- /dev/null +++ b/src/Actions/ReencryptSettings.php @@ -0,0 +1,90 @@ +stores->default()->name); + $this->access->authorize($actor, Ability::ManageStores, $subject); + + $rewrite = function (string $ciphertext): ?string { + try { + return $this->encrypter->encrypt($this->encrypter->decrypt($ciphertext)); + } catch (SettingsException) { + return null; + } + }; + + $totals = ['values' => 0, 'history' => 0, 'changes' => 0, 'failed' => 0]; + $connections = []; + + foreach ($this->stores->all() as $store) { + $database = $store->database(); + + if (! $database instanceof DatabaseDriver || ! $database->isWritable()) { + continue; + } + + [$rewritten, $failed] = $database->rewriteEncrypted($store->name, $rewrite); + $totals['values'] += $rewritten; + $totals['failed'] += $failed; + $store->forgetCachedStore(); + + // The history and change requests tables are per connection, so once each. + if (isset($connections[$database->connectionName()])) { + continue; + } + + $connections[$database->connectionName()] = true; + + if ($database->shape()->historyTable) { + [$rewritten, $failed] = new HistoryRepository($database)->rewriteEncrypted($store->name, $rewrite); + $totals['history'] += $rewritten; + $totals['failed'] += $failed; + } + + if ($database->shape()->changeRequestsTable) { + [$rewritten, $failed] = new ChangeRequestRepository($database)->rewriteEncrypted($store->name, $rewrite); + $totals['changes'] += $rewritten; + $totals['failed'] += $failed; + } + } + + $this->access->auditor()->record(AuditAction::Reencrypt, $totals['failed'] === 0 ? AuditOutcome::Allowed : AuditOutcome::Failed, $subject, $actor, meta: $totals); + + return $totals; + } +} diff --git a/src/Actions/RescopeOwners.php b/src/Actions/RescopeOwners.php new file mode 100644 index 0000000..d7e72ed --- /dev/null +++ b/src/Actions/RescopeOwners.php @@ -0,0 +1,87 @@ +:` becomes `:` in every database store (with `settable_type` + * and per-row slugs), in the history and in change requests, in chunks (G-44). `$from` may be a + * class name, which is how rows written before the alias allow-list look (G-6). The audit trail is + * left as it was: it records what happened under the old name. Needs `manage_stores`; audited. + * Update the stores' `owners` lists to the new alias as well. + */ +final readonly class RescopeOwners +{ + public function __construct( + private StoreRegistry $stores, + private AccessGuard $access, + ) {} + + /** @return array{values: int, history: int, changes: int} */ + public function handle(string $from, string $to, ?Actor $actor = null): array + { + if ($from === '' || $from === Scope::GLOBAL || str_contains($from, ':')) { + throw new InvalidIdentifier(sprintf('rescope: [%s] is not an owner alias.', $from)); + } + + $to = new OwnerRef($to, '0')->alias; + + if ($from === $to) { + throw new InvalidIdentifier(sprintf('rescope: [%s] is already the alias.', $from)); + } + + $subject = new Subject($this->stores->default()->name); + $this->access->authorize($actor, Ability::ManageStores, $subject); + + $totals = ['values' => 0, 'history' => 0, 'changes' => 0]; + + foreach ($this->stores->all() as $store) { + $database = $store->database(); + + if (! $database instanceof DatabaseDriver || ! $database->isWritable()) { + continue; + } + + $store->transaction(function () use ($database, $store, $from, $to, &$totals): void { + $totals['values'] += $database->rescope($store->name, $from, $to); + + if ($database->shape()->historyTable) { + $totals['history'] += new HistoryRepository($database)->rescope($store->name, $from, $to); + } + }); + + $store->forgetCachedStore(); + } + + $seen = []; + + foreach ($this->stores->all() as $store) { + $database = $store->database(); + + if ($database instanceof DatabaseDriver && $database->shape()->changeRequestsTable && ! isset($seen[$database->connectionName()])) { + $seen[$database->connectionName()] = true; + $totals['changes'] += new ChangeRequestRepository($database)->rescope($store->name, $from, $to); + } + } + + $this->access->auditor()->record(AuditAction::Rescope, AuditOutcome::Allowed, $subject, $actor, meta: ['from' => $from, 'to' => $to] + $totals); + + return $totals; + } +} diff --git a/src/Actions/SetSetting.php b/src/Actions/SetSetting.php index 6e68401..16927fa 100644 --- a/src/Actions/SetSetting.php +++ b/src/Actions/SetSetting.php @@ -7,6 +7,9 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\SettingWrite; +use Simtabi\Laranail\Settings\Data\ChangeRequest; +use Simtabi\Laranail\Settings\Data\ChangeProposal; +use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; /** @@ -21,11 +24,12 @@ public function __construct( private WriteGuard $guard, ) {} - public function handle(SettingWrite $write, ?Actor $actor = null): void + /** @return ?ChangeRequest the change request opened instead, when the setting needs approval */ + public function handle(SettingWrite $write, ?Actor $actor = null): ?ChangeRequest { $target = $write->target; - $this->guard->run(Ability::Update, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target, $write, $actor): array { + return $this->guard->run(Ability::Update, $target, $actor, respectsLocks: true, write: function (bool $override) use ($target, $write, $actor): array { $after = match (true) { $write->expectedVersion !== null => $this->writer->causedBy($actor, $target->reason)->setExpecting($target->store, $target->key, $target->locale, $target->owner, $target->definition, $write->value, $write->expectedVersion, $override), $override => $this->writer->causedBy($actor, $target->reason)->setOverridingLock($target->store, $target->key, $target->locale, $target->owner, $target->definition, $write->value), @@ -33,6 +37,6 @@ public function handle(SettingWrite $write, ?Actor $actor = null): void }; return [$after->version > 1 ? $after->version - 1 : null, $after->version]; - }); + }, proposal: new ChangeProposal($target, ChangeOperation::Set, $write->value)); } } diff --git a/src/Actions/SettingActions.php b/src/Actions/SettingActions.php index b41010b..32ba315 100644 --- a/src/Actions/SettingActions.php +++ b/src/Actions/SettingActions.php @@ -6,6 +6,7 @@ use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange; /** * The write actions a settings handle delegates to, held together so a handle is built from @@ -20,10 +21,13 @@ public function __construct( public UnlockSetting $unlock, ) {} - /** The four actions over one writer, enforced by one access guard. */ - public static function using(SettingWriter $writer, AccessGuard $access): self + /** + * The four actions over one writer, enforced by one access guard; with a proposer, a write to + * a setting that needs approval opens a change request instead (§16.7). + */ + public static function using(SettingWriter $writer, AccessGuard $access, ?ProposeChange $proposer = null): self { - $guard = new WriteGuard($access, $writer); + $guard = new WriteGuard($access, $writer, $proposer); return new self( new SetSetting($writer, $guard), diff --git a/src/Actions/Transfer/DiffStore.php b/src/Actions/Transfer/DiffStore.php new file mode 100644 index 0000000..9dee1bb --- /dev/null +++ b/src/Actions/Transfer/DiffStore.php @@ -0,0 +1,34 @@ +access->authorize($actor, Ability::Export, new Subject($store->name)); + + return $this->snapshots->diff($store, $document); + } +} diff --git a/src/Actions/Transfer/ExportStore.php b/src/Actions/Transfer/ExportStore.php new file mode 100644 index 0000000..f48b3f5 --- /dev/null +++ b/src/Actions/Transfer/ExportStore.php @@ -0,0 +1,45 @@ +store->name); + + $this->access->authorize($actor, Ability::Export, $subject); + + if ($request->mode === ExportMode::Plaintext) { + $this->access->authorize($actor, Ability::ViewSensitive, $subject); + } + + $document = $this->snapshots->export($request->store, $request->mode); + $this->access->auditor()->record(AuditAction::Export, AuditOutcome::Allowed, $subject, $actor, meta: ['mode' => $request->mode->value, 'settings' => count($document->settings), 'categories' => count($document->categories)]); + + return $document; + } +} diff --git a/src/Actions/Transfer/ImportStore.php b/src/Actions/Transfer/ImportStore.php new file mode 100644 index 0000000..90d117a --- /dev/null +++ b/src/Actions/Transfer/ImportStore.php @@ -0,0 +1,202 @@ +store; + $subject = new Subject($store->name); + + $this->access->authorize($actor, Ability::Import, $subject); + + $current = $this->snapshots->export($store, ExportMode::Ciphertext)->settingsByIdentity(); + $existingCategories = array_map(static fn (Category $category): string => $category->slug->value, CategoryRepository::of($store)->all()); + $plan = $this->plan($request, $current); + $categories = $this->categoriesToCreate($request->document->categories, $existingCategories); + + if (! $request->apply) { + return new ImportReport(false, $plan['created'], $plan['updated'], $plan['unchanged'], $plan['skipped'], array_map(static fn (ExportedCategory $category): string => $category->slug->value, $categories)); + } + + return $store->transaction(function () use ($request, $store, $subject, $actor, $plan, $categories): ImportReport { + foreach ($categories as $category) { + $this->createCategory->handle($store, $category->toNewCategory($request->trusted), $actor); + } + + $proposed = []; + + foreach ($plan['write'] as $setting) { + $target = $this->target($store, $setting, $request->reason); + $value = $this->pipeline->fromRecord(new Record( + $setting->scope, + $setting->key, + $setting->locale, + $setting->ciphertext ?? $this->encoder->encode($setting->key, $setting->value), + $setting->type, + $setting->ciphertext !== null, + ), $target->definition); + $change = $this->set->handle(new SettingWrite($target, $value), $actor); + + if ($change instanceof ChangeRequest) { + $proposed[] = $change->id; + } elseif ($request->trusted && $setting->locked) { + $this->lock->handle($target, $actor); + } + } + + $this->access->auditor()->record(AuditAction::Import, AuditOutcome::Allowed, $subject, $actor, $request->reason, meta: [ + 'created' => count($plan['created']), + 'updated' => count($plan['updated']), + 'skipped' => count($plan['skipped']), + 'categories' => count($categories), + 'trusted' => $request->trusted, + 'source' => $request->document->source, + ]); + + return new ImportReport(true, $plan['created'], $plan['updated'], $plan['unchanged'], $plan['skipped'], array_map(static fn (ExportedCategory $category): string => $category->slug->value, $categories), $proposed); + }); + } + + /** + * What each setting of the document would do. + * + * @param array $current + * + * @return array{created: list, updated: list, unchanged: list, skipped: array, write: list} + */ + private function plan(ImportRequest $request, array $current): array + { + $plan = ['created' => [], 'updated' => [], 'unchanged' => [], 'skipped' => [], 'write' => []]; + $store = $request->store; + + foreach ($request->document->settings as $setting) { + $identity = $setting->identity(); + $owner = $setting->scope->owner(); + + $skip = match (true) { + $setting->redacted => 'the export left its value out (encrypted); export it with --with-secrets or --decrypt', + ! $setting->hasValue => 'it has no value (a lock without a value)', + $owner instanceof OwnerRef && ! $store->accepts($owner->alias) => sprintf('store [%s] does not accept owner alias [%s]', $store->name, $owner->alias), + ! $owner instanceof OwnerRef && $store->isDedicated() => sprintf('store [%s] is dedicated and holds no global values', $store->name), + default => null, + }; + + if ($skip !== null) { + $plan['skipped'][$identity] = $skip; + + continue; + } + + $existing = $current[$identity] ?? null; + + if ($existing instanceof ExportedSetting && StoreSnapshots::same($existing, $setting)) { + $plan['unchanged'][] = $identity; + + continue; + } + + $plan[$existing instanceof ExportedSetting ? 'updated' : 'created'][] = $identity; + $plan['write'][] = $setting; + } + + return $plan; + } + + /** + * The categories the store lacks, parents before children. + * + * @param list $incoming + * @param list $existing slugs + * + * @return list + */ + private function categoriesToCreate(array $incoming, array $existing): array + { + $known = array_fill_keys($existing, true); + $pending = array_values(array_filter($incoming, static fn (ExportedCategory $category): bool => ! isset($known[$category->slug->value]))); + $ordered = []; + + while ($pending !== []) { + $ready = array_values(array_filter($pending, static fn (ExportedCategory $category): bool => ! $category->parent instanceof CategorySlug || isset($known[$category->parent->value]))); + + // A parent the file names but does not hold: create the child at the top level. + $ready = $ready === [] ? [array_shift($pending)] : $ready; + + foreach ($ready as $category) { + $known[$category->slug->value] = true; + $ordered[] = $category->parent === null || isset($known[$category->parent->value]) ? $category : new ExportedCategory($category->slug, $category->title, null, $category->description, $category->icon, $category->sortOrder, $category->system, $category->titles); + } + + $pending = array_values(array_filter($pending, static fn (ExportedCategory $category): bool => ! in_array($category, $ready, true))); + } + + return $ordered; + } + + private function target(Store $store, ExportedSetting $setting, ?string $reason): SettingTarget + { + try { + $definition = ($this->definitions)($store, $setting->key); + } catch (SettingsException) { + $definition = null; + } + + return new SettingTarget($store, $setting->key, $setting->locale, $setting->scope->owner(), $definition, $reason); + } +} diff --git a/src/Actions/Transfer/TransferActions.php b/src/Actions/Transfer/TransferActions.php new file mode 100644 index 0000000..6129c7a --- /dev/null +++ b/src/Actions/Transfer/TransferActions.php @@ -0,0 +1,15 @@ +guard->run(Ability::Unlock, $target, $actor, respectsLocks: false, write: function () use ($target, $actor): array { + return $this->guard->run(Ability::Unlock, $target, $actor, respectsLocks: false, write: function () use ($target, $actor): array { $after = $this->writer->causedBy($actor, $target->reason)->unlock($target->store, $target->key, $target->locale, $target->owner, $target->definition); return [$after->version > 1 ? $after->version - 1 : null, $after->version]; - }); + }, proposal: new ChangeProposal($target, ChangeOperation::Unlock)); } } diff --git a/src/Actions/WriteGuard.php b/src/Actions/WriteGuard.php index 656810a..9798764 100644 --- a/src/Actions/WriteGuard.php +++ b/src/Actions/WriteGuard.php @@ -8,16 +8,20 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; +use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Data\SettingTarget; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Data\ChangeProposal; use Simtabi\Laranail\Settings\Support\AuditedTransaction; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; +use Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange; /** * What every write action does around its write, in this order: authorize the ability (or - * check that an actor is not required), refuse settings that need approval, decide whether a + * check that an actor is not required), turn a write to a setting that needs approval into a + * change request (or refuse it where the store cannot hold one), decide whether a * locked row may be overridden, run the write, and audit the outcome. Denials are audited by * the {@see AccessGuard}; failures and successes here. An allowed write and its audit entry run * in one transaction on the store's database connection (when it has one), so a failed audit @@ -29,13 +33,17 @@ public function __construct( private AccessGuard $access, private SettingWriter $writer, + private ?ProposeChange $proposer = null, ) {} /** * @param bool $respectsLocks whether a locked row stops this write (set and forget, not lock and unlock) * @param Closure(bool): array{?int, ?int} $write runs the write (told whether to override a lock); returns [version before, version after] + * @param ?ChangeProposal $proposal the change request to open instead, when the setting needs approval (§16.7) + * + * @return ?ChangeRequest the change request opened instead of writing, or null when the write ran */ - public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool $respectsLocks, Closure $write): void + public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool $respectsLocks, Closure $write, ?ChangeProposal $proposal = null): ?ChangeRequest { $subject = $target->subject(); $action = AuditAction::fromAbility($ability); @@ -43,9 +51,16 @@ public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool $this->access->authorize($actor, $ability, $subject); if ($subject->requiresApproval) { + // A store that can hold change requests turns the write into one (§16.7). + if ($this->proposer instanceof ProposeChange && $proposal instanceof ChangeProposal && $target->store->acceptsChangeRequests()) { + return $this->proposer->handle($proposal, $actor); + } + $this->access->auditor()->record($action, AuditOutcome::Failed, $subject, $actor, $target->reason, meta: ['refusal' => 'approval_unavailable']); - throw new ApprovalUnavailable(sprintf('Setting [%s] in store [%s] requires approval, which needs the database layer (a later release).', $target->key, $target->store->name)); + throw new ApprovalUnavailable($proposal instanceof ChangeProposal + ? sprintf('Setting [%s] in store [%s] requires approval, and the store cannot hold change requests (it needs an active database layer and the change requests table).', $target->key, $target->store->name) + : sprintf('Setting [%s] in store [%s] requires approval; propose the change instead of making it directly.', $target->key, $target->store->name)); } $override = $respectsLocks && $this->mayOverrideLock($target, $actor); @@ -60,6 +75,8 @@ public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool static fn (array $versions): array => ['from' => $versions[0], 'to' => $versions[1], 'meta' => $override ? ['override_lock' => true] : []], reason: $target->reason, ); + + return null; } /** diff --git a/src/Approvals/Approvals.php b/src/Approvals/Approvals.php new file mode 100644 index 0000000..7e3dbc0 --- /dev/null +++ b/src/Approvals/Approvals.php @@ -0,0 +1,107 @@ +pending()`, + * `->status()`, `->key()`, `->for($owner)`, then `->get()`), and approve, reject or cancel one by + * id. Immutable: every narrowing returns a new query. + */ +final readonly class Approvals +{ + public function __construct( + private ApprovalActions $actions, + private Store $store, + private ?Actor $actor = null, + private ?ChangeFilter $filter = null, + ) {} + + /** Open requests only (pending, or approved and waiting for more approvals). */ + public function pending(): self + { + return $this->with($this->filter()->with(status: ChangeStatus::Pending)); + } + + public function status(ChangeStatus $status): self + { + return $this->with($this->filter()->with(status: $status)); + } + + public function key(string $key): self + { + return $this->with($this->filter()->with(key: new Key($key))); + } + + public function for(Settable|OwnerRef $owner): self + { + return $this->with($this->filter()->with(scope: Scope::of($owner instanceof Settable ? $owner->settingsOwner() : $owner))); + } + + /** + * Newest first. An actor without `approve` sees only their own requests. + * + * @return list + */ + public function get(int $limit = 100, ?string $after = null): array + { + return $this->actions->query->handle($this->filter(), $this->actor, $limit, $after); + } + + /** + * One request, if the actor may see it. + * + * @throws UnknownChangeRequest + */ + public function find(string $id): ChangeRequest + { + return $this->actions->query->handle(new ChangeFilter($this->store->name, id: $id), $this->actor, 1)[0] ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $this->store->name, $id)); + } + + /** + * @throws AccessDenied + * @throws ChangeRequestClosed + */ + public function approve(string $id, ?string $reason = null): ChangeRequest + { + return $this->actions->approve->handle(new ChangeDecision($this->store, $id, $reason), $this->actor); + } + + /** @throws ChangeRequestClosed */ + public function reject(string $id, ?string $reason = null): ChangeRequest + { + return $this->actions->reject->handle(new ChangeDecision($this->store, $id, $reason), $this->actor); + } + + /** @throws ChangeRequestClosed */ + public function cancel(string $id, ?string $reason = null): ChangeRequest + { + return $this->actions->cancel->handle(new ChangeDecision($this->store, $id, $reason), $this->actor); + } + + private function filter(): ChangeFilter + { + return $this->filter ?? new ChangeFilter($this->store->name); + } + + private function with(ChangeFilter $filter): self + { + return new self($this->actions, $this->store, $this->actor, $filter); + } +} diff --git a/src/Configuration/PersistedConfigurationEditor.php b/src/Configuration/PersistedConfigurationEditor.php new file mode 100644 index 0000000..942edd1 --- /dev/null +++ b/src/Configuration/PersistedConfigurationEditor.php @@ -0,0 +1,78 @@ + */ + public function entries(): array + { + return $this->actions->list->handle($this->actor); + } + + /** + * @param array $config as `stores.` would hold it + * + * @throws InvalidConfiguration + */ + public function saveStore(string $name, array $config): void + { + $this->actions->save->handle(new ConfigurationEntry(ConfigurationEntry::STORE, $name, $config), $this->actor); + } + + /** + * @param array $config as `layers.` would hold it + * + * @throws InvalidConfiguration + */ + public function saveLayer(string $name, array $config): void + { + $this->actions->save->handle(new ConfigurationEntry(ConfigurationEntry::LAYER, $name, $config), $this->actor); + } + + public function deleteStore(string $name): bool + { + return $this->actions->delete->handle(new ConfigurationEntry(ConfigurationEntry::STORE, $name), $this->actor); + } + + public function deleteLayer(string $name): bool + { + return $this->actions->delete->handle(new ConfigurationEntry(ConfigurationEntry::LAYER, $name), $this->actor); + } + + /** + * @param array $attributes as `definitions.` would hold them + * + * @throws InvalidDefinition + */ + public function saveDefinition(string $key, array $attributes): Definition + { + return $this->actions->saveDefinition->handle($this->store, $key, $attributes, $this->actor); + } + + public function deleteDefinition(string $key): bool + { + return $this->actions->deleteDefinition->handle($this->store, $key, $this->actor); + } +} diff --git a/src/Console/DiffCommand.php b/src/Console/DiffCommand.php new file mode 100644 index 0000000..4143d2f --- /dev/null +++ b/src/Console/DiffCommand.php @@ -0,0 +1,64 @@ +argument('path'); + $path = is_string($path) ? $path : ''; + $storeOption = $this->option('store'); + + try { + $store = is_string($storeOption) && $storeOption !== '' ? $stores->get(new StoreName($storeOption)) : $stores->default(); + + if (! $files->isFile($path)) { + throw new InvalidImport(sprintf('[%s] is not a file.', $path)); + } + + $diff = $transfer->diff->handle($store, ExportDocument::fromJson($files->get($path)), Actor::system('laranail::settings.diff')); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + foreach (['added' => '+', 'removed' => '-', 'changed' => '~', 'unknown' => '?'] as $bucket => $mark) { + foreach ($diff->toArray()[$bucket] as $identity) { + $this->line(sprintf('%s %s', $mark, $identity)); + } + } + + $this->info($diff->isEmpty() + ? sprintf('No differences (%d setting(s) equal).', count($diff->unchanged)) + : sprintf('%d to add, %d only in the store, %d changed, %d not comparable (redacted).', count($diff->added), count($diff->removed), count($diff->changed), count($diff->unknown))); + + return $diff->isEmpty() ? self::SUCCESS : self::FAILURE; + } +} diff --git a/src/Console/ExportCommand.php b/src/Console/ExportCommand.php new file mode 100644 index 0000000..5ddb914 --- /dev/null +++ b/src/Console/ExportCommand.php @@ -0,0 +1,82 @@ +`). Runs as + * the system actor and is audited; never logs a value. + */ +final class ExportCommand extends Command +{ + use SupportsNamespacedNames; + + protected $signature = 'laranail::settings.export + {path? : Where to write the file (default: standard output)} + {--store= : The store (default: the default store)} + {--with-secrets : Export encrypted values as their ciphertext} + {--decrypt : Export encrypted values decrypted} + {--confirm= : The store name, confirming --decrypt without a prompt}'; + + protected $description = 'Export a settings store as JSON'; + + public function handle(Settings $settings, Filesystem $files): int + { + $store = $this->option('store'); + $handle = $settings->asSystem('laranail::settings.export'); + $handle = is_string($store) && $store !== '' ? $handle->store($store) : $handle; + $name = is_string($store) && $store !== '' ? $store : null; + $mode = match (true) { + $this->option('decrypt') === true => ExportMode::Plaintext, + $this->option('with-secrets') === true => ExportMode::Ciphertext, + default => ExportMode::Redacted, + }; + + try { + $document = $handle->export($mode); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + if ($mode === ExportMode::Plaintext) { + $confirm = $this->option('confirm'); + $typed = is_string($confirm) ? $confirm : $this->ask(sprintf('This writes decrypted secrets. Type the store name [%s] to continue', $document->store)); + + if ($typed !== ($name ?? $document->store)) { + $this->error('The store name did not match; nothing was written.'); + + return self::FAILURE; + } + } + + $path = $this->argument('path'); + + if (is_string($path) && $path !== '') { + $files->put($path, $document->toJson()); + $this->info(sprintf('Exported %d setting(s) and %d categor%s of store [%s] to %s.', count($document->settings), count($document->categories), count($document->categories) === 1 ? 'y' : 'ies', $document->store, $path)); + + if ($mode === ExportMode::Ciphertext) { + $this->comment('Encrypted values are ciphertext: importable only under the same APP_KEY, or one listed in APP_PREVIOUS_KEYS.'); + } + + return self::SUCCESS; + } + + $this->output->write($document->toJson()); + + return self::SUCCESS; + } +} diff --git a/src/Console/ImportCommand.php b/src/Console/ImportCommand.php new file mode 100644 index 0000000..c32029e --- /dev/null +++ b/src/Console/ImportCommand.php @@ -0,0 +1,104 @@ +` + * another package's settings (G-43: `spatie`, `toolkit`, `akaunting`, or one configured in + * `importers`). A dry run unless `--apply`: it prints what would be created, updated and skipped. + * `--trusted` lets the file set locks and system categories (G-10). Everything is written through + * the write pipeline as the system actor, in one transaction, and audited. + */ +final class ImportCommand extends Command +{ + use SupportsNamespacedNames; + + protected $signature = 'laranail::settings.import + {source : An export file, or what the importer reads (a connection, connection:table or file)} + {--store= : The store (default: the default store)} + {--from= : Read with an importer instead of an export file} + {--apply : Write the changes (without it, a dry run)} + {--trusted : Let the file set locks and system categories}'; + + protected $description = 'Import settings from an export file or another package (dry run by default)'; + + public function handle(TransferActions $transfer, StoreRegistry $stores, Importers $importers, Filesystem $files): int + { + $source = $this->argument('source'); + $source = is_string($source) ? $source : ''; + $from = $this->option('from'); + $storeOption = $this->option('store'); + + try { + $store = is_string($storeOption) && $storeOption !== '' ? $stores->get(new StoreName($storeOption)) : $stores->default(); + + if (is_string($from) && $from !== '') { + $document = $importers->get($from)->read($source, $store->name); + } else { + if (! $files->isFile($source)) { + throw new InvalidImport(sprintf('[%s] is not a file.', $source)); + } + + $document = ExportDocument::fromJson($files->get($source)); + } + + $report = $transfer->import->handle(new ImportRequest( + $store, + $document, + apply: $this->option('apply') === true, + trusted: $this->option('trusted') === true, + reason: 'laranail::settings.import', + ), Actor::system('laranail::settings.import')); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->report($report); + + return self::SUCCESS; + } + + private function report(ImportReport $report): void + { + $this->info(sprintf( + '%s %d created, %d updated, %d unchanged, %d skipped; %d categor%s created.', + $report->applied ? 'Imported:' : 'Dry run (add --apply to write):', + count($report->created), + count($report->updated), + count($report->unchanged), + count($report->skipped), + count($report->categories), + count($report->categories) === 1 ? 'y' : 'ies', + )); + + foreach ([...array_map(static fn (string $id): string => '+ ' . $id, $report->created), ...array_map(static fn (string $id): string => '~ ' . $id, $report->updated)] as $line) { + $this->line(' ' . $line); + } + + foreach ($report->skipped as $identity => $reason) { + $this->line(sprintf(' ! %s skipped: %s', $identity, $reason)); + } + + if ($report->proposed !== []) { + $this->comment(sprintf('%d setting(s) need approval: change requests %s.', count($report->proposed), implode(', ', $report->proposed))); + } + } +} diff --git a/src/Console/OpenApiCommand.php b/src/Console/OpenApiCommand.php new file mode 100644 index 0000000..e4ff35c --- /dev/null +++ b/src/Console/OpenApiCommand.php @@ -0,0 +1,52 @@ +getRoutes()->getRoutes(), static fn (Route $route): bool => str_starts_with((string) $route->getName(), ApiRoutes::NAME_PREFIX)); + + if ($routes === []) { + $this->error('The settings REST API is off: set laranail.settings.http.enabled to true first.'); + + return self::FAILURE; + } + + $json = json_encode(OpenApiDocument::build($routes), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n"; + $output = $this->option('output'); + + if (is_string($output) && $output !== '') { + $files->put($output, $json); + $this->info(sprintf('Wrote the OpenAPI document (%d operation(s)) to %s.', count($routes), $output)); + + return self::SUCCESS; + } + + $this->output->write($json); + + return self::SUCCESS; + } +} diff --git a/src/Console/PruneChangesCommand.php b/src/Console/PruneChangesCommand.php new file mode 100644 index 0000000..a138a96 --- /dev/null +++ b/src/Console/PruneChangesCommand.php @@ -0,0 +1,40 @@ +prune->handle(Actor::system('laranail::settings.prune-changes')); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(sprintf('Expired %d change request(s); deleted %d decided one(s).', $result['expired'], $result['deleted'])); + + return self::SUCCESS; + } +} diff --git a/src/Console/ReencryptCommand.php b/src/Console/ReencryptCommand.php new file mode 100644 index 0000000..b97a392 --- /dev/null +++ b/src/Console/ReencryptCommand.php @@ -0,0 +1,46 @@ +handle(Actor::system('laranail::settings.reencrypt')); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(sprintf('Re-encrypted %d value(s), %d history entr%s and %d change request(s).', $result['values'], $result['history'], $result['history'] === 1 ? 'y' : 'ies', $result['changes'])); + + if ($result['failed'] > 0) { + $this->error(sprintf('%d payload(s) could not be decrypted with the current or previous keys and were left as they were.', $result['failed'])); + + return self::FAILURE; + } + + return self::SUCCESS; + } +} diff --git a/src/Console/RescopeCommand.php b/src/Console/RescopeCommand.php new file mode 100644 index 0000000..0579f8b --- /dev/null +++ b/src/Console/RescopeCommand.php @@ -0,0 +1,46 @@ +argument('from'); + $to = $this->argument('to'); + $from = is_string($from) ? $from : ''; + $to = is_string($to) ? $to : ''; + + try { + $result = $rescope->handle($from, $to, Actor::system('laranail::settings.rescope')); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(sprintf('Renamed [%s] to [%s] in %d value(s), %d history entr%s and %d change request(s). Update the stores\' owners lists to match.', $from, $to, $result['values'], $result['history'], $result['history'] === 1 ? 'y' : 'ies', $result['changes'])); + + return self::SUCCESS; + } +} diff --git a/src/Contracts/Importer.php b/src/Contracts/Importer.php new file mode 100644 index 0000000..37be780 --- /dev/null +++ b/src/Contracts/Importer.php @@ -0,0 +1,21 @@ + $expireAfterDays, 'keep_days' => $keepDays] as $name => $days) { + if ($days !== null && $days < 1) { + throw new InvalidConfiguration(sprintf('laranail.settings.approvals.%s: [%d] must be at least 1, or null.', $name, $days)); + } + } + } +} diff --git a/src/Data/ChangeDecision.php b/src/Data/ChangeDecision.php new file mode 100644 index 0000000..3e64240 --- /dev/null +++ b/src/Data/ChangeDecision.php @@ -0,0 +1,17 @@ +store, $status ?? $this->status, $scope ?? $this->scope, $key ?? $this->key, $id ?? $this->id); + } +} diff --git a/src/Data/ChangeProposal.php b/src/Data/ChangeProposal.php new file mode 100644 index 0000000..6464211 --- /dev/null +++ b/src/Data/ChangeProposal.php @@ -0,0 +1,20 @@ + $approvals */ + public function __construct( + public string $id, + public string $store, + public string $scope, + public string $key, + public string $locale, + public ChangeOperation $operation, + public ?string $payload, + public ?string $type, + public bool $encrypted, + public int $baseVersion, + public ChangeStatus $status, + public ActorType $requestedByType, + public ?string $requestedByAlias, + public ?string $requestedById, + public array $approvals = [], + public ?ActorType $decidedByType = null, + public ?string $decidedByAlias = null, + public ?string $decidedById = null, + public ?CarbonImmutable $decidedAt = null, + public ?string $reason = null, + public ?string $decisionReason = null, + public ?CarbonImmutable $expiresAt = null, + public ?CarbonImmutable $createdAt = null, + ) {} + + /** How an actor is written in `approvals`, and compared with the requester. */ + public static function actorKey(Actor $actor): string + { + return $actor->type->value . ':' . ($actor->alias ?? '') . ':' . ($actor->id ?? ''); + } + + public function requesterKey(): string + { + return $this->requestedByType->value . ':' . ($this->requestedByAlias ?? '') . ':' . ($this->requestedById ?? ''); + } + + public function isRequestedBy(Actor $actor): bool + { + return ! $actor->isSystem() && self::actorKey($actor) === $this->requesterKey(); + } + + public function isExpired(CarbonImmutable $now): bool + { + return $this->expiresAt instanceof CarbonImmutable && $this->expiresAt->lessThanOrEqualTo($now); + } + + /** The owner the request writes for, or null for the global value. */ + public function owner(): ?OwnerRef + { + return Scope::fromString($this->scope)?->owner(); + } + + /** + * Everything but the payload: a change request is safe to list and render. + * + * @return array + */ + public function toArray(): array + { + return [ + 'id' => $this->id, + 'store' => $this->store, + 'scope' => $this->scope, + 'key' => $this->key, + 'locale' => $this->locale, + 'operation' => $this->operation->value, + 'encrypted' => $this->encrypted, + 'base_version' => $this->baseVersion, + 'status' => $this->status->value, + 'requested_by' => ['type' => $this->requestedByType->value, 'alias' => $this->requestedByAlias, 'id' => $this->requestedById], + 'approvals' => $this->approvals, + 'decided_by' => $this->decidedByType instanceof ActorType ? ['type' => $this->decidedByType->value, 'alias' => $this->decidedByAlias, 'id' => $this->decidedById] : null, + 'decided_at' => $this->decidedAt?->toIso8601String(), + 'reason' => $this->reason, + 'decision_reason' => $this->decisionReason, + 'expires_at' => $this->expiresAt?->toIso8601String(), + 'created_at' => $this->createdAt?->toIso8601String(), + ]; + } +} diff --git a/src/Data/ConfigurationEntry.php b/src/Data/ConfigurationEntry.php new file mode 100644 index 0000000..288851e --- /dev/null +++ b/src/Data/ConfigurationEntry.php @@ -0,0 +1,29 @@ +` or `layers.`. + */ +final readonly class ConfigurationEntry +{ + public const string STORE = 'store'; + + public const string LAYER = 'layer'; + + /** @param array $config */ + public function __construct( + public string $kind, + public string $name, + public array $config = [], + ) { + if (! in_array($kind, [self::STORE, self::LAYER], true)) { + throw new InvalidConfiguration(sprintf('A persisted configuration entry is a [store] or a [layer], not [%s].', $kind)); + } + } +} diff --git a/src/Data/Http/AddressInput.php b/src/Data/Http/AddressInput.php new file mode 100644 index 0000000..45c6c4e --- /dev/null +++ b/src/Data/Http/AddressInput.php @@ -0,0 +1,17 @@ + $params route parameters + * @param array $body validated body + * @param bool $hasParent whether the body named `parent` at all (null moves to the top level) + */ + public function __construct( + public array $params, + public array $body, + public bool $hasParent = false, + ) {} + + public function param(string $name): string + { + return $this->params[$name] ?? ''; + } + + public function text(string $name): ?string + { + $value = $this->body[$name] ?? null; + + return is_string($value) && $value !== '' ? $value : null; + } + + public function integer(string $name, int $default = 0): int + { + $value = $this->body[$name] ?? null; + + return is_numeric($value) ? (int) $value : $default; + } + + public function boolean(string $name): bool + { + return filter_var($this->body[$name] ?? false, FILTER_VALIDATE_BOOL); + } + + /** @return array */ + public function array(string $name): array + { + $value = $this->body[$name] ?? []; + + return is_array($value) ? $value : []; + } + + public function value(string $name): mixed + { + return $this->body[$name] ?? null; + } +} diff --git a/src/Data/Http/PageInput.php b/src/Data/Http/PageInput.php new file mode 100644 index 0000000..028846e --- /dev/null +++ b/src/Data/Http/PageInput.php @@ -0,0 +1,21 @@ + $filters */ + public function __construct( + public int $limit = 50, + public ?string $cursor = null, + public array $filters = [], + ) {} + + public function filter(string $name): ?string + { + return $this->filters[$name] ?? null; + } +} diff --git a/src/Data/Http/WriteInput.php b/src/Data/Http/WriteInput.php new file mode 100644 index 0000000..96899c1 --- /dev/null +++ b/src/Data/Http/WriteInput.php @@ -0,0 +1,20 @@ +owner instanceof Settable ? $this->owner->settingsOwner() : $this->owner; + } + + /** `store|scope|key|locale@version`, hashed: the ETag of the setting at that version (§16.10). */ + public function etag(int $version): string + { + return '"' . sha1($this->store . '|' . Scope::of($this->ownerRef())->value . '|' . $this->key . '|' . new Locale($this->locale)->value . '@' . $version) . '"'; + } +} diff --git a/src/Data/SettingTarget.php b/src/Data/SettingTarget.php index c6b16ea..80ba896 100644 --- a/src/Data/SettingTarget.php +++ b/src/Data/SettingTarget.php @@ -21,8 +21,23 @@ public function __construct( public ?string $reason = null, ) {} + /** + * The subject abilities are checked against. A key matched by the store's `approvals.keys` + * needs approval as if its definition said so (§16.7). + */ public function subject(): Subject { - return Subject::of($this->store->name, $this->key, $this->locale, $this->owner, $this->definition); + $subject = Subject::of($this->store->name, $this->key, $this->locale, $this->owner, $this->definition); + + return $subject->requiresApproval || ! $this->store->requiresApproval($this->key) ? $subject : new Subject( + $subject->store, + $subject->key, + $subject->owner, + $subject->locale, + $subject->category, + $subject->sensitive, + $subject->requiresVerification, + requiresApproval: true, + ); } } diff --git a/src/Data/SettingView.php b/src/Data/SettingView.php new file mode 100644 index 0000000..4fd659e --- /dev/null +++ b/src/Data/SettingView.php @@ -0,0 +1,27 @@ +address->etag($this->version); + } +} diff --git a/src/Data/SettingsMigrationStep.php b/src/Data/SettingsMigrationStep.php new file mode 100644 index 0000000..aeaf567 --- /dev/null +++ b/src/Data/SettingsMigrationStep.php @@ -0,0 +1,29 @@ + $categories + * @param list $settings + */ + public function __construct( + public string $store, + public array $categories = [], + public array $settings = [], + public ExportMode $mode = ExportMode::Redacted, + public ?string $exportedAt = null, + public ?string $source = null, + ) {} + + /** + * Read a document; anything malformed raises InvalidImport naming the entry. + * + * @throws InvalidImport + */ + public static function fromJson(string $json): self + { + $data = json_decode($json, true); + + if (! is_array($data)) { + throw new InvalidImport('The export file is not a JSON object.'); + } + + return self::fromArray($data); + } + + /** + * @param array $data + * + * @throws InvalidImport + */ + public static function fromArray(array $data): self + { + if (($data['format'] ?? null) !== self::FORMAT) { + throw new InvalidImport(sprintf('The export file is not a %s export (format: %s).', self::FORMAT, is_scalar($data['format'] ?? null) ? (string) $data['format'] : 'missing')); + } + + if (! is_int($data['version'] ?? null) || $data['version'] > self::VERSION) { + throw new InvalidImport(sprintf('The export file has version [%s]; this release reads version %d.', is_scalar($data['version'] ?? null) ? (string) $data['version'] : '?', self::VERSION)); + } + + $categories = is_array($data['categories'] ?? null) ? $data['categories'] : []; + $settings = is_array($data['settings'] ?? null) ? $data['settings'] : []; + + return new self( + is_string($data['store'] ?? null) ? $data['store'] : 'settings', + array_values(array_map( + static fn (mixed $entry, int|string $index): ExportedCategory => ExportedCategory::fromArray(is_array($entry) ? $entry : [], $index), + $categories, + array_keys($categories), + )), + array_values(array_map( + static fn (mixed $entry, int|string $index): ExportedSetting => ExportedSetting::fromArray(is_array($entry) ? $entry : [], $index), + $settings, + array_keys($settings), + )), + ExportMode::tryFrom(is_string($data['mode'] ?? null) ? $data['mode'] : '') ?? ExportMode::Redacted, + is_string($data['exported_at'] ?? null) ? $data['exported_at'] : null, + is_string($data['source'] ?? null) ? $data['source'] : null, + ); + } + + /** @return array */ + public function toArray(): array + { + return array_filter([ + 'format' => self::FORMAT, + 'version' => self::VERSION, + 'store' => $this->store, + 'mode' => $this->mode->value, + 'exported_at' => $this->exportedAt, + 'source' => $this->source, + 'categories' => array_map(static fn (ExportedCategory $category): array => $category->toArray(), $this->categories), + 'settings' => array_map(static fn (ExportedSetting $setting): array => $setting->toArray(), $this->settings), + ], static fn (mixed $value): bool => $value !== null); + } + + public function toJson(): string + { + return json_encode($this->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR) . "\n"; + } + + /** @return array by identity */ + public function settingsByIdentity(): array + { + $indexed = []; + + foreach ($this->settings as $setting) { + $indexed[$setting->identity()] = $setting; + } + + return $indexed; + } +} diff --git a/src/Data/Transfer/ExportRequest.php b/src/Data/Transfer/ExportRequest.php new file mode 100644 index 0000000..2790f25 --- /dev/null +++ b/src/Data/Transfer/ExportRequest.php @@ -0,0 +1,17 @@ + $titles locale => title (json translations mode) */ + public function __construct( + public CategorySlug $slug, + public string $title, + public ?CategorySlug $parent = null, + public ?string $description = null, + public ?string $icon = null, + public int $sortOrder = 0, + public bool $system = false, + public array $titles = [], + ) {} + + public static function of(Category $category): self + { + return new self($category->slug, $category->title, $category->parent, $category->description, $category->icon, $category->sortOrder, $category->system, $category->titles); + } + + /** + * @param array $data + * + * @throws InvalidImport + */ + public static function fromArray(array $data, int|string $index): self + { + try { + $titles = is_array($data['titles'] ?? null) ? array_filter($data['titles'], is_string(...)) : []; + + return new self( + new CategorySlug(is_string($data['slug'] ?? null) ? $data['slug'] : ''), + is_string($data['title'] ?? null) ? $data['title'] : '', + is_string($data['parent'] ?? null) ? new CategorySlug($data['parent']) : null, + is_string($data['description'] ?? null) ? $data['description'] : null, + is_string($data['icon'] ?? null) ? $data['icon'] : null, + is_int($data['sort_order'] ?? null) ? $data['sort_order'] : 0, + ($data['system'] ?? false) === true, + array_combine(array_map(strval(...), array_keys($titles)), array_values($titles)), + ); + } catch (SettingsException $exception) { + throw new InvalidImport(sprintf('categories.%s: %s', $index, $exception->getMessage()), 0, $exception); + } + } + + /** The category to create on import; `system` only when the import is trusted (G-10). */ + public function toNewCategory(bool $trusted): NewCategory + { + return new NewCategory($this->slug->value, $this->title === '' ? $this->slug->value : $this->title, $this->parent?->value, $this->description, $this->icon, $this->sortOrder, $this->titles, $trusted && $this->system); + } + + /** @return array */ + public function toArray(): array + { + return array_filter([ + 'slug' => $this->slug->value, + 'title' => $this->title, + 'titles' => $this->titles === [] ? null : $this->titles, + 'parent' => $this->parent?->value, + 'description' => $this->description, + 'icon' => $this->icon, + 'sort_order' => $this->sortOrder, + 'system' => $this->system ?: null, + ], static fn (mixed $value): bool => $value !== null); + } +} diff --git a/src/Data/Transfer/ExportedSetting.php b/src/Data/Transfer/ExportedSetting.php new file mode 100644 index 0000000..1722371 --- /dev/null +++ b/src/Data/Transfer/ExportedSetting.php @@ -0,0 +1,85 @@ + $data + * + * @throws InvalidImport + */ + public static function fromArray(array $data, int|string $index): self + { + try { + $scope = Scope::fromString(is_string($data['scope'] ?? null) ? $data['scope'] : '') ?? throw new InvalidImport('bad scope'); + + return new self( + $scope, + new Key(is_string($data['key'] ?? null) ? $data['key'] : ''), + new Locale(is_string($data['locale'] ?? null) ? $data['locale'] : ''), + $data['value'] ?? null, + is_string($data['ciphertext'] ?? null) ? $data['ciphertext'] : null, + ($data['redacted'] ?? false) === true, + is_string($data['type'] ?? null) ? $data['type'] : null, + ($data['encrypted'] ?? false) === true, + ($data['locked'] ?? false) === true, + array_key_exists('value', $data) || is_string($data['ciphertext'] ?? null) || ($data['redacted'] ?? false) === true, + ); + } catch (SettingsException $exception) { + throw new InvalidImport(sprintf('settings.%s: %s', $index, $exception->getMessage()), 0, $exception); + } + } + + /** `scope|key|locale`: how two documents' settings are matched. */ + public function identity(): string + { + return $this->scope->value . '|' . $this->key->value . '|' . $this->locale->value; + } + + /** @return array */ + public function toArray(): array + { + $entry = ['scope' => $this->scope->value, 'key' => $this->key->value, 'locale' => $this->locale->value]; + + if ($this->redacted) { + $entry['redacted'] = true; + } elseif ($this->ciphertext !== null) { + $entry['ciphertext'] = $this->ciphertext; + } elseif ($this->hasValue) { + $entry['value'] = $this->value; + } + + return $entry + array_filter([ + 'type' => $this->type, + 'encrypted' => $this->encrypted ?: null, + 'locked' => $this->locked ?: null, + ], static fn (mixed $value): bool => $value !== null); + } +} diff --git a/src/Data/Transfer/ImportReport.php b/src/Data/Transfer/ImportReport.php new file mode 100644 index 0000000..ffae349 --- /dev/null +++ b/src/Data/Transfer/ImportReport.php @@ -0,0 +1,45 @@ + $created + * @param list $updated + * @param list $unchanged + * @param array $skipped identity => reason + * @param list $categories slugs created + * @param list $proposed change request ids + */ + public function __construct( + public bool $applied, + public array $created = [], + public array $updated = [], + public array $unchanged = [], + public array $skipped = [], + public array $categories = [], + public array $proposed = [], + ) {} + + /** @return array */ + public function toArray(): array + { + return [ + 'applied' => $this->applied, + 'created' => $this->created, + 'updated' => $this->updated, + 'unchanged' => $this->unchanged, + 'skipped' => $this->skipped, + 'categories' => $this->categories, + 'proposed' => $this->proposed, + ]; + } +} diff --git a/src/Data/Transfer/ImportRequest.php b/src/Data/Transfer/ImportRequest.php new file mode 100644 index 0000000..75b3df9 --- /dev/null +++ b/src/Data/Transfer/ImportRequest.php @@ -0,0 +1,23 @@ + $added + * @param list $removed + * @param list $changed + * @param list $unchanged + * @param list $unknown + */ + public function __construct( + public array $added = [], + public array $removed = [], + public array $changed = [], + public array $unchanged = [], + public array $unknown = [], + ) {} + + public function isEmpty(): bool + { + return $this->added === [] && $this->removed === [] && $this->changed === []; + } + + /** @return array> */ + public function toArray(): array + { + return ['added' => $this->added, 'removed' => $this->removed, 'changed' => $this->changed, 'unchanged' => $this->unchanged, 'unknown' => $this->unknown]; + } +} diff --git a/src/Database/SchemaNames.php b/src/Database/SchemaNames.php index e920857..b49f8c3 100644 --- a/src/Database/SchemaNames.php +++ b/src/Database/SchemaNames.php @@ -9,7 +9,8 @@ /** * The package's table names: `tables.prefix` (D-4) prepended to `tables.categories`, - * `tables.audit`, `tables.definitions`, `tables.history` and each store's values table (`stores..table`, default the store name). + * `tables.audit`, `tables.definitions`, `tables.history`, `tables.change_requests`, + * `tables.stores` and each store's values table (`stores..table`, default the store name). * Every name is validated, because it is interpolated into SQL identifiers. */ final readonly class SchemaNames @@ -20,6 +21,8 @@ public function __construct( private string $audit = 'settings_audit', private string $definitions = 'settings_definitions', private string $history = 'settings_history', + private string $changeRequests = 'settings_change_requests', + private string $storesTable = 'settings_stores', ) { if (preg_match('/^[a-z0-9_]{0,32}$/', $prefix) !== 1) { throw new InvalidConfiguration(sprintf('laranail.settings.tables.prefix: [%s] must be [a-z0-9_], at most 32 characters.', $prefix)); @@ -29,6 +32,8 @@ public function __construct( self::assertTable($audit, 'laranail.settings.tables.audit'); self::assertTable($definitions, 'laranail.settings.tables.definitions'); self::assertTable($history, 'laranail.settings.tables.history'); + self::assertTable($changeRequests, 'laranail.settings.tables.change_requests'); + self::assertTable($storesTable, 'laranail.settings.tables.stores'); } /** @param array $tables `laranail.settings.tables` */ @@ -40,6 +45,8 @@ public static function fromConfig(array $tables): self self::string($tables, 'audit', 'settings_audit'), self::string($tables, 'definitions', 'settings_definitions'), self::string($tables, 'history', 'settings_history'), + self::string($tables, 'change_requests', 'settings_change_requests'), + self::string($tables, 'stores', 'settings_stores'), ); } @@ -72,10 +79,22 @@ public function history(): string return $this->prefix . $this->history; } - /** @return array{prefix: string, categories: string, audit: string, definitions: string, history: string} the unprefixed names */ + /** The change requests table (§16.7), one per connection like the history table. */ + public function changeRequests(): string + { + return $this->prefix . $this->changeRequests; + } + + /** The persisted configuration table (§16.11), on the default store's connection. */ + public function stores(): string + { + return $this->prefix . $this->storesTable; + } + + /** @return array{prefix: string, categories: string, audit: string, definitions: string, history: string, change_requests: string, stores: string} the unprefixed names */ public function toArray(): array { - return ['prefix' => $this->prefix, 'categories' => $this->categories, 'audit' => $this->audit, 'definitions' => $this->definitions, 'history' => $this->history]; + return ['prefix' => $this->prefix, 'categories' => $this->categories, 'audit' => $this->audit, 'definitions' => $this->definitions, 'history' => $this->history, 'change_requests' => $this->changeRequests, 'stores' => $this->storesTable]; } /** A store's values table: its configured table, or its name, after the prefix. */ diff --git a/src/Database/SchemaShape.php b/src/Database/SchemaShape.php index 519f2b5..18a1822 100644 --- a/src/Database/SchemaShape.php +++ b/src/Database/SchemaShape.php @@ -44,6 +44,8 @@ public function __construct( public array $stores = [], public TenancyMode $tenancy = TenancyMode::None, public bool $historyTable = false, + public bool $changeRequestsTable = false, + public bool $storesTable = false, ) {} /** @@ -86,6 +88,18 @@ public static function fromConfig(array $settings, mixed $dbToolsIdType = null): throw new InvalidConfiguration('laranail.settings.history.enabled: true or false.'); } + $approvals = self::section($settings, 'approvals')['table'] ?? true; + + if (! is_bool($approvals)) { + throw new InvalidConfiguration('laranail.settings.approvals.table: true or false.'); + } + + $persisted = self::section($settings, 'configuration')['persisted'] ?? false; + + if (! is_bool($persisted)) { + throw new InvalidConfiguration('laranail.settings.configuration.persisted: true or false.'); + } + $default = $settings['default'] ?? 'settings'; $default = new StoreName(is_string($default) ? $default : 'settings'); @@ -102,6 +116,8 @@ public static function fromConfig(array $settings, mixed $dbToolsIdType = null): self::storesFromConfig($settings, $followed ?? IdType::Bigint, $default), $tenancy, $history, + $approvals, + $persisted, ); } @@ -146,6 +162,9 @@ public static function fromArray(array $data): self TenancyMode::tryFrom(self::text($switches, 'tenancy', 'none')) ?? throw $invalid('tenancy'), // A file recorded before the history table existed describes a schema without it. ($switches['history_table'] ?? false) === true, + // Likewise for the change requests and persisted configuration tables (Phase 4b). + ($switches['change_requests_table'] ?? false) === true, + ($switches['stores_table'] ?? false) === true, ); } @@ -172,6 +191,8 @@ public function toArray(): array 'definitions_table' => $this->definitionsTable, 'tenancy' => $this->tenancy->value, 'history_table' => $this->historyTable, + 'change_requests_table' => $this->changeRequestsTable, + 'stores_table' => $this->storesTable, ], 'tables' => $this->names->toArray(), 'stores' => $stores, @@ -196,7 +217,7 @@ public function withStore(StoreSchema $store): self return $this; } - return new self($this->version, $this->identity, $this->ids, $this->ownerKey, $this->ownerKeyType, $this->translations, $this->categoriesSoftDeletes, $this->definitionsTable, $this->names, [...$this->stores, $store->name->value => $store], $this->tenancy, $this->historyTable); + return new self($this->version, $this->identity, $this->ids, $this->ownerKey, $this->ownerKeyType, $this->translations, $this->categoriesSoftDeletes, $this->definitionsTable, $this->names, [...$this->stores, $store->name->value => $store], $this->tenancy, $this->historyTable, $this->changeRequestsTable, $this->storesTable); } /** diff --git a/src/Drivers/DatabaseDriver.php b/src/Drivers/DatabaseDriver.php index f89fa7e..240dc47 100644 --- a/src/Drivers/DatabaseDriver.php +++ b/src/Drivers/DatabaseDriver.php @@ -358,6 +358,88 @@ public function scopes(StoreName $store): array ))); } + /** + * Rewrite every encrypted payload of the store, every tenant's and trashed rows included + * (re-encryption after a key rotation), in chunks by primary key. `$rewrite` returns the new + * payload, or null when it could not read the old one (counted as failed, left as it was). + * Returns [rewritten, failed]. + * + * @param Closure(string): ?string $rewrite + * + * @return array{int, int} + */ + public function rewriteEncrypted(StoreName $store, Closure $rewrite): array + { + $this->assertWritable($store); + + return $this->attempt($store, function () use ($store, $rewrite): array { + $rewritten = 0; + $failed = 0; + + $this->connection()->table($this->tableFor($store)) + ->where('is_encrypted', true) + ->whereNotNull('value') + ->select(['id', 'value']) + ->chunkById(500, function ($rows) use ($store, $rewrite, &$rewritten, &$failed): void { + foreach ($rows as $row) { + $row = (array) $row; + $new = is_string($row['value'] ?? null) ? $rewrite($row['value']) : null; + + if ($new === null) { + $failed++; + + continue; + } + + $rewritten += $this->connection()->table($this->tableFor($store))->where('id', $row['id'])->update(['value' => $new]); + } + }); + + return [$rewritten, $failed]; + }); + } + + /** + * Rename an owner alias in the store (G-30): every scope `:` becomes `:`, + * with `settable_type` in a polymorphic store and the per-row slug of `slug_per_row`, for + * every tenant and trashed rows too, in chunks. Returns how many rows changed. A row whose new + * identity already exists makes the database refuse the rename (DriverFailure). + */ + public function rescope(StoreName $store, string $from, string $to): int + { + $this->assertWritable($store); + + return $this->attempt($store, function () use ($store, $from, $to): int { + $changed = 0; + $polymorphic = ! $this->schemaOf($store)->isDedicated(); + $perRow = $this->shape()->identity === IdentityMode::SlugPerRow; + + $this->connection()->table($this->tableFor($store)) + ->where('scope', '>=', $from . ':') + ->where('scope', '<', $from . ';') + ->select(['id', 'scope', 'key', 'locale']) + ->chunkById(500, function ($rows) use ($store, $from, $to, $polymorphic, $perRow, &$changed): void { + foreach ($rows as $row) { + $row = (array) $row; + $scope = $to . substr(is_string($row['scope'] ?? null) ? $row['scope'] : '', strlen($from)); + $columns = ['scope' => $scope]; + + if ($polymorphic) { + $columns['settable_type'] = $to; + } + + if ($perRow) { + $columns['slug'] = sha1($scope . '|' . (is_string($row['key'] ?? null) ? $row['key'] : '') . '|' . (is_string($row['locale'] ?? null) ? $row['locale'] : '')); + } + + $changed += $this->connection()->table($this->tableFor($store))->where('id', $row['id'])->update($columns); + } + }); + + return $changed; + }); + } + /** * Run a callback in one transaction on this layer's connection. The store only names the * store in an outage message. diff --git a/src/Enums/AuditAction.php b/src/Enums/AuditAction.php index 2b0732d..38a35ca 100644 --- a/src/Enums/AuditAction.php +++ b/src/Enums/AuditAction.php @@ -9,7 +9,8 @@ use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; /** - * What an audit entry records: every {@see Ability}, plus configuration changes. + * What an audit entry records: every {@see Ability}, plus configuration changes and the + * governance operations (proposals and their decisions, re-encryption, rescoping, settings migrations). */ enum AuditAction: string implements Enumerator { @@ -72,6 +73,24 @@ enum AuditAction: string implements Enumerator #[Label('Configure')] case Configure = 'configure'; + #[Label('Propose a change')] + case Propose = 'propose'; + + #[Label('Reject a change')] + case Reject = 'reject'; + + #[Label('Cancel a change')] + case Cancel = 'cancel'; + + #[Label('Re-encrypt values')] + case Reencrypt = 'reencrypt'; + + #[Label('Rename an owner alias')] + case Rescope = 'rescope'; + + #[Label('Migrate settings')] + case Migrate = 'migrate'; + public static function fromAbility(Ability $ability): self { return self::from($ability->value); diff --git a/src/Enums/Capability.php b/src/Enums/Capability.php new file mode 100644 index 0000000..d18aa2d --- /dev/null +++ b/src/Enums/Capability.php @@ -0,0 +1,199 @@ +`, and `laranail-settings.api.owners.` for the owner + * form) and backed by the actions the PHP API uses. An architecture test holds the routes, this + * list and the controllers to each other, so no channel can grow a capability the others lack. + */ +enum Capability: string implements Enumerator +{ + use HasEnumeratorBehavior; + + #[Label('List stores')] + case StoresIndex = 'stores.index'; + + #[Label('List definitions')] + case DefinitionsIndex = 'definitions.index'; + + #[Label('List settings')] + case SettingsIndex = 'settings.index'; + + #[Label('Read a setting')] + case SettingsShow = 'settings.show'; + + #[Label('Write a setting')] + case SettingsUpdate = 'settings.update'; + + #[Label('Forget a setting')] + case SettingsDestroy = 'settings.destroy'; + + #[Label('Lock a setting')] + case SettingsLock = 'settings.lock'; + + #[Label('Unlock a setting')] + case SettingsUnlock = 'settings.unlock'; + + #[Label('Explain a setting')] + case SettingsExplain = 'settings.explain'; + + #[Label('A setting\'s history')] + case SettingsHistory = 'settings.history'; + + #[Label('Roll a setting back')] + case SettingsRollback = 'settings.rollback'; + + #[Label('The audit trail')] + case AuditIndex = 'audit.index'; + + #[Label('List change requests')] + case ChangesIndex = 'changes.index'; + + #[Label('Read a change request')] + case ChangesShow = 'changes.show'; + + #[Label('Propose a change')] + case ChangesStore = 'changes.store'; + + #[Label('Approve a change')] + case ChangesApprove = 'changes.approve'; + + #[Label('Reject a change')] + case ChangesReject = 'changes.reject'; + + #[Label('Cancel a change')] + case ChangesCancel = 'changes.cancel'; + + #[Label('List categories')] + case CategoriesIndex = 'categories.index'; + + #[Label('Create a category')] + case CategoriesStore = 'categories.store'; + + #[Label('Rename or move a category')] + case CategoriesUpdate = 'categories.update'; + + #[Label('Delete a category')] + case CategoriesDestroy = 'categories.destroy'; + + #[Label('List persisted configuration')] + case ConfigurationIndex = 'configuration.index'; + + #[Label('Save a persisted store or layer')] + case ConfigurationUpdate = 'configuration.update'; + + #[Label('Delete a persisted store or layer')] + case ConfigurationDestroy = 'configuration.destroy'; + + #[Label('Save a definition')] + case DefinitionsUpdate = 'definitions.update'; + + #[Label('Delete a definition')] + case DefinitionsDestroy = 'definitions.destroy'; + + #[Label('Export a store')] + case TransferExport = 'transfer.export'; + + #[Label('Import into a store')] + case TransferImport = 'transfer.import'; + + #[Label('Compare a store with an export')] + case TransferDiff = 'transfer.diff'; + + /** + * The actions this capability runs, as the PHP API runs them. + * + * @return list + */ + public function actions(): array + { + return match ($this) { + self::StoresIndex => [ListStores::class], + self::DefinitionsIndex => [ListDefinitions::class], + self::SettingsIndex => [ReadSettings::class], + self::SettingsShow => [ReadSetting::class], + self::SettingsUpdate => [SetSetting::class], + self::SettingsDestroy => [ForgetSetting::class], + self::SettingsLock => [LockSetting::class], + self::SettingsUnlock => [UnlockSetting::class], + self::SettingsExplain => [ExplainSetting::class], + self::SettingsHistory => [ReadHistory::class], + self::SettingsRollback => [RollbackSetting::class], + self::AuditIndex => [QueryAudit::class], + self::ChangesIndex => [QueryChanges::class], + self::ChangesShow => [QueryChanges::class], + self::ChangesStore => [ProposeChange::class], + self::ChangesApprove => [ApproveChange::class], + self::ChangesReject => [RejectChange::class], + self::ChangesCancel => [CancelChange::class], + self::CategoriesIndex => [ListCategories::class], + self::CategoriesStore => [CreateCategory::class], + self::CategoriesUpdate => [RenameCategory::class, MoveCategory::class], + self::CategoriesDestroy => [DeleteCategory::class], + self::ConfigurationIndex => [ListConfigurationEntries::class], + self::ConfigurationUpdate => [SaveConfigurationEntry::class], + self::ConfigurationDestroy => [DeleteConfigurationEntry::class], + self::DefinitionsUpdate => [SaveDefinition::class], + self::DefinitionsDestroy => [DeleteDefinition::class], + self::TransferExport => [ExportStore::class], + self::TransferImport => [ImportStore::class], + self::TransferDiff => [DiffStore::class], + }; + } + + /** The `http.routes` group that switches this capability's routes on or off. */ + public function group(): string + { + return match ($this) { + self::SettingsHistory, self::SettingsRollback => 'history', + self::ChangesIndex, self::ChangesShow, self::ChangesStore, + self::ChangesApprove, self::ChangesReject, self::ChangesCancel => 'approvals', + self::DefinitionsUpdate, self::DefinitionsDestroy => 'configuration', + default => explode('.', $this->value)[0], + }; + } + + /** Whether the capability has an owner form (`/owners/{alias}/{id}/settings/…`). */ + public function hasOwnerForm(): bool + { + return str_starts_with($this->value, 'settings.'); + } +} diff --git a/src/Enums/ChangeOperation.php b/src/Enums/ChangeOperation.php new file mode 100644 index 0000000..c4f63c4 --- /dev/null +++ b/src/Enums/ChangeOperation.php @@ -0,0 +1,38 @@ + Ability::Update, + self::Forget => Ability::Forget, + self::Lock => Ability::Lock, + self::Unlock => Ability::Unlock, + }; + } +} diff --git a/src/Enums/ChangeStatus.php b/src/Enums/ChangeStatus.php new file mode 100644 index 0000000..567ba47 --- /dev/null +++ b/src/Enums/ChangeStatus.php @@ -0,0 +1,45 @@ +` (the owner form of a settings route + * adds `owners.`), through `http.middleware`, the `laranail-settings` rate limiter and, on writes, + * the idempotency middleware. Groups listed false in `http.routes` are left out. + */ +final readonly class ApiRoutes +{ + public const string NAME_PREFIX = 'laranail-settings.api.'; + + /** + * Every route: [method, uri under /v1, capability, controller, controller method]. + * + * @var list + */ + private const array ROUTES = [ + ['GET', 'stores', Capability::StoresIndex, StoresController::class, 'index'], + ['GET', 'stores/{store}/definitions', Capability::DefinitionsIndex, StoresController::class, 'definitions'], + ['GET', '{owner}settings', Capability::SettingsIndex, SettingsController::class, 'index'], + ['GET', '{owner}settings/{key}', Capability::SettingsShow, SettingsController::class, 'show'], + ['PUT', '{owner}settings/{key}', Capability::SettingsUpdate, SettingsController::class, 'update'], + ['DELETE', '{owner}settings/{key}', Capability::SettingsDestroy, SettingsController::class, 'destroy'], + ['POST', '{owner}settings/{key}/lock', Capability::SettingsLock, SettingsController::class, 'lock'], + ['DELETE', '{owner}settings/{key}/lock', Capability::SettingsUnlock, SettingsController::class, 'unlock'], + ['GET', '{owner}settings/{key}/explain', Capability::SettingsExplain, SettingsController::class, 'explain'], + ['GET', '{owner}settings/{key}/history', Capability::SettingsHistory, HistoryController::class, 'index'], + ['POST', '{owner}settings/{key}/rollback', Capability::SettingsRollback, HistoryController::class, 'rollback'], + ['GET', 'audit', Capability::AuditIndex, AuditController::class, 'index'], + ['GET', 'stores/{store}/changes', Capability::ChangesIndex, ChangesController::class, 'index'], + ['POST', 'stores/{store}/changes', Capability::ChangesStore, ChangesController::class, 'store'], + ['GET', 'stores/{store}/changes/{id}', Capability::ChangesShow, ChangesController::class, 'show'], + ['POST', 'stores/{store}/changes/{id}/approve', Capability::ChangesApprove, ChangesController::class, 'approve'], + ['POST', 'stores/{store}/changes/{id}/reject', Capability::ChangesReject, ChangesController::class, 'reject'], + ['POST', 'stores/{store}/changes/{id}/cancel', Capability::ChangesCancel, ChangesController::class, 'cancel'], + ['GET', 'stores/{store}/categories', Capability::CategoriesIndex, CategoriesController::class, 'index'], + ['POST', 'stores/{store}/categories', Capability::CategoriesStore, CategoriesController::class, 'store'], + ['PATCH', 'stores/{store}/categories/{slug}', Capability::CategoriesUpdate, CategoriesController::class, 'update'], + ['DELETE', 'stores/{store}/categories/{slug}', Capability::CategoriesDestroy, CategoriesController::class, 'destroy'], + ['GET', 'configuration', Capability::ConfigurationIndex, ConfigurationController::class, 'index'], + ['PUT', 'configuration/{kind}/{name}', Capability::ConfigurationUpdate, ConfigurationController::class, 'update'], + ['DELETE', 'configuration/{kind}/{name}', Capability::ConfigurationDestroy, ConfigurationController::class, 'destroy'], + ['PUT', 'stores/{store}/definitions/{key}', Capability::DefinitionsUpdate, ConfigurationController::class, 'updateDefinition'], + ['DELETE', 'stores/{store}/definitions/{key}', Capability::DefinitionsDestroy, ConfigurationController::class, 'destroyDefinition'], + ['POST', 'stores/{store}/export', Capability::TransferExport, TransferController::class, 'export'], + ['POST', 'stores/{store}/import', Capability::TransferImport, TransferController::class, 'import'], + ['POST', 'stores/{store}/diff', Capability::TransferDiff, TransferController::class, 'diff'], + ]; + + /** + * @return list + */ + public static function definitions(): array + { + $routes = []; + + foreach (self::ROUTES as [$method, $uri, $capability, $controller, $action]) { + $forms = str_starts_with($uri, '{owner}') + ? ['' => 'stores/{store}/', 'owners.' => 'stores/{store}/owners/{alias}/{id}/'] + : ['' => '']; + + foreach ($forms as $prefix => $path) { + $routes[] = [ + 'method' => $method, + 'uri' => $path . str_replace('{owner}', '', $uri), + 'name' => self::NAME_PREFIX . $prefix . $capability->value, + 'capability' => $capability, + 'controller' => $controller, + 'action' => $action, + ]; + } + } + + return $routes; + } + + /** + * @param list $middleware + * @param array $groups `http.routes` + */ + public static function register(Router $router, string $prefix, array $middleware, array $groups): void + { + $router->prefix(trim($prefix, '/') . '/v1') + ->middleware([FreshControllers::class, ...$middleware, 'throttle:laranail-settings']) + ->group(static function (Router $router) use ($groups): void { + foreach (self::definitions() as $route) { + if (($groups[$route['capability']->group()] ?? true) === false) { + continue; + } + + $registered = $router->addRoute($route['method'], $route['uri'], [$route['controller'], $route['action']]) + ->name($route['name']) + ->where(['store' => '[a-z][a-z0-9_]*', 'key' => '[A-Za-z0-9_.]+', 'alias' => '[a-z][a-z0-9_]*', 'kind' => 'stores|layers']); + + if ($route['method'] !== 'GET') { + $registered->middleware(IdempotentWrites::class); + } + } + }); + } +} diff --git a/src/Http/Controllers/AuditController.php b/src/Http/Controllers/AuditController.php new file mode 100644 index 0000000..4de3acf --- /dev/null +++ b/src/Http/Controllers/AuditController.php @@ -0,0 +1,53 @@ +toData(); + $result = $this->audit->paginate($this->filter($page), $this->actors->of($request), $page->limit, $page->cursor); + + return ListResponse::make(array_map(static fn (AuditEntry $entry): array => $entry->toArray(), $result->entries), $result->nextCursor); + } + + private function filter(PageInput $page): AuditFilter + { + $text = $page->filter(...); + + return new AuditFilter( + $text('store') === null ? null : new StoreName($text('store')), + $text('scope') === null ? null : (Scope::fromString($text('scope')) ?? throw new InvalidIdentifier('scope: use global or alias:id.')), + $text('key') === null ? null : new Key($text('key')), + $text('action') === null ? null : (AuditAction::tryFrom($text('action')) ?? throw new InvalidIdentifier(sprintf('action: [%s] is not an audit action.', $text('action')))), + $text('outcome') === null ? null : (AuditOutcome::tryFrom($text('outcome')) ?? throw new InvalidIdentifier(sprintf('outcome: [%s] is not an outcome.', $text('outcome')))), + $text('since') === null ? null : CarbonImmutable::parse($text('since')), + $text('until') === null ? null : CarbonImmutable::parse($text('until')), + ); + } +} diff --git a/src/Http/Controllers/CategoriesController.php b/src/Http/Controllers/CategoriesController.php new file mode 100644 index 0000000..0ccba25 --- /dev/null +++ b/src/Http/Controllers/CategoriesController.php @@ -0,0 +1,85 @@ +list->handle($this->targets->store($request->addressData()->store), $this->actors->of($request)); + + return ListResponse::make(array_map(CategoryResource::fields(...), $categories)); + } + + public function store(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $category = $this->create->handle($this->targets->store($input->param('store')), new NewCategory( + (string) $input->text('slug'), + (string) $input->text('title'), + $input->text('parent'), + $input->text('description'), + $input->text('icon'), + $input->integer('sort_order'), + $input->array('titles'), + ), $this->actors->of($request)); + + return new JsonResponse(['data' => CategoryResource::fields($category)], 201); + } + + public function update(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $actor = $this->actors->of($request); + $store = $this->targets->store($input->param('store')); + $slug = $input->param('slug'); + + if ($input->text('title') !== null) { + $this->rename->handle($store, $slug, $input->text('title'), $actor); + } + + if ($input->hasParent) { + $this->move->handle($store, $slug, $input->text('parent'), $actor); + } + + $categories = array_values(array_filter($this->list->handle($store, $actor), static fn (Category $category): bool => $category->slug->value === $slug)); + + return new JsonResponse(['data' => $categories === [] ? null : CategoryResource::fields($categories[0])]); + } + + public function destroy(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $this->delete->handle($this->targets->store($input->param('store')), $input->param('slug'), $this->actors->of($request)); + + return new JsonResponse(null, 204); + } +} diff --git a/src/Http/Controllers/ChangesController.php b/src/Http/Controllers/ChangesController.php new file mode 100644 index 0000000..c9379de --- /dev/null +++ b/src/Http/Controllers/ChangesController.php @@ -0,0 +1,121 @@ +toData(); + $store = $this->targets->store($request->addressData()->store); + $status = $page->filter('status'); + $key = $page->filter('key'); + $filter = new ChangeFilter( + $store->name, + $status === null ? null : (ChangeStatus::tryFrom($status) ?? throw new InvalidIdentifier(sprintf('status: [%s] is not a change status.', $status))), + key: $key === null ? null : new Key($key), + ); + $requests = $this->query->handle($filter, $this->actors->of($request), $page->limit + 1, $page->cursor); + $next = count($requests) > $page->limit ? $requests[$page->limit - 1]->id : null; + + return ListResponse::make(array_map(static fn (ChangeRequest $change): array => $change->toArray(), array_slice($requests, 0, $page->limit)), $next); + } + + public function show(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $store = $this->targets->store($input->param('store')); + $found = $this->query->handle(new ChangeFilter($store->name, id: $input->param('id')), $this->actors->of($request), 1); + + return $this->render($found[0] ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $store->name, $input->param('id')))); + } + + public function store(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $owner = $input->array('owner'); + $address = $this->addresses->of(new AddressInput( + $input->param('store'), + (string) $input->text('key'), + is_string($owner['alias'] ?? null) ? $owner['alias'] : null, + is_string($owner['id'] ?? null) ? $owner['id'] : null, + $input->text('locale') ?? '', + )); + $operation = ChangeOperation::tryFrom($input->text('operation') ?? 'set') ?? ChangeOperation::Set; + $change = $this->propose->handle(new ChangeProposal($this->targets->target($address, $input->text('reason')), $operation, $input->value('value')), $this->actors->of($request, $input->text('reason'))); + + return $this->render($change, 202); + } + + public function approve(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + + return $this->render($this->approve->handle($this->decision($input->param('store'), $input->param('id'), $input->text('reason')), $this->actors->of($request))); + } + + public function reject(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + + return $this->render($this->reject->handle($this->decision($input->param('store'), $input->param('id'), $input->text('reason')), $this->actors->of($request))); + } + + public function cancel(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + + return $this->render($this->cancel->handle($this->decision($input->param('store'), $input->param('id'), $input->text('reason')), $this->actors->of($request))); + } + + private function decision(string $store, string $id, ?string $reason): ChangeDecision + { + return new ChangeDecision($this->targets->store($store), $id, $reason); + } + + private function render(ChangeRequest $change, int $status = 200): JsonResponse + { + return new JsonResponse(['data' => new ChangeRequestResource($change)->resolve()], $status); + } +} diff --git a/src/Http/Controllers/ConfigurationController.php b/src/Http/Controllers/ConfigurationController.php new file mode 100644 index 0000000..0b0a1a4 --- /dev/null +++ b/src/Http/Controllers/ConfigurationController.php @@ -0,0 +1,74 @@ + ['kind' => $entry->kind, 'name' => $entry->name, 'config' => (object) $entry->config], $this->list->handle($this->actors->of($request)))); + } + + public function update(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $entry = new ConfigurationEntry(rtrim($input->param('kind'), 's'), $input->param('name'), $input->array('config')); + $this->save->handle($entry, $this->actors->of($request)); + + return new JsonResponse(['data' => ['kind' => $entry->kind, 'name' => $entry->name, 'config' => (object) $entry->config]]); + } + + public function destroy(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $this->delete->handle(new ConfigurationEntry(rtrim($input->param('kind'), 's'), $input->param('name')), $this->actors->of($request)); + + return new JsonResponse(null, 204); + } + + public function updateDefinition(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $definition = $this->saveDefinition->handle($this->targets->store($input->param('store')), $input->param('key'), $input->array('attributes'), $this->actors->of($request)); + + return new JsonResponse(['data' => DefinitionResource::fields($definition)]); + } + + public function destroyDefinition(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $this->deleteDefinition->handle($this->targets->store($input->param('store')), $input->param('key'), $this->actors->of($request)); + + return new JsonResponse(null, 204); + } +} diff --git a/src/Http/Controllers/HistoryController.php b/src/Http/Controllers/HistoryController.php new file mode 100644 index 0000000..c5f5c35 --- /dev/null +++ b/src/Http/Controllers/HistoryController.php @@ -0,0 +1,51 @@ +toData(); + $result = $this->history->handle($this->addresses->of($request->addressData()), $this->actors->of($request), $page->limit, $page->cursor); + + return ListResponse::make(array_map(static fn (HistoryEntry $entry): array => $entry->toArray(), $result->entries), $result->nextCursor); + } + + public function rollback(WriteSettingRequest $request): JsonResponse + { + $input = $request->toData(); + $actor = $this->actors->of($request, $input->reason); + $address = $this->addresses->of($input->address); + + $this->rollback->handle($this->targets->target($address, $input->reason), $input->toVersion ?? 0, $actor); + $view = $this->read->handle($address, $actor); + + return new JsonResponse(['data' => SettingResource::fields($view)], 200, ['ETag' => $view->etag()]); + } +} diff --git a/src/Http/Controllers/SettingsController.php b/src/Http/Controllers/SettingsController.php new file mode 100644 index 0000000..21d31c1 --- /dev/null +++ b/src/Http/Controllers/SettingsController.php @@ -0,0 +1,145 @@ +toData(); + $result = $this->readMany->handle($this->addresses->of($request->addressData()), $this->actors->of($request), $page->limit, $page->cursor); + + return ListResponse::make(array_map(SettingResource::fields(...), $result['items']), $result['next']); + } + + public function show(SettingRequest $request): JsonResponse + { + $view = $this->read->handle($this->addresses->of($request->toData()), $this->actors->of($request)); + + return new JsonResponse(['data' => SettingResource::fields($view)], 200, ['ETag' => $view->etag()]); + } + + public function explain(SettingRequest $request): JsonResponse + { + return new JsonResponse(['data' => ExplanationResource::fields($this->explain->handle($this->addresses->of($request->toData()), $this->actors->of($request)))]); + } + + public function update(WriteSettingRequest $request): JsonResponse + { + $input = $request->toData(); + $actor = $this->actors->of($request, $input->reason); + $address = $this->addresses->of($input->address); + $expected = $this->expectedVersion($address, $input->ifMatch); + $change = $this->set->handle(new SettingWrite($this->targets->target($address, $input->reason), $input->value, $expected), $actor); + + return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($address, $actor); + } + + public function destroy(WriteSettingRequest $request): JsonResponse + { + $input = $request->toData(); + $actor = $this->actors->of($request, $input->reason); + $address = $this->addresses->of($input->address); + $this->expectedVersion($address, $input->ifMatch); + $change = $this->forget->handle($this->targets->target($address, $input->reason), $actor); + + return $change instanceof ChangeRequest ? $this->accepted($change) : new JsonResponse(null, 204); + } + + public function lock(WriteSettingRequest $request): JsonResponse + { + $input = $request->toData(); + $actor = $this->actors->of($request, $input->reason); + $address = $this->addresses->of($input->address); + $change = $this->lock->handle($this->targets->target($address, $input->reason), $actor); + + return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($address, $actor); + } + + public function unlock(WriteSettingRequest $request): JsonResponse + { + $input = $request->toData(); + $actor = $this->actors->of($request, $input->reason); + $address = $this->addresses->of($input->address); + $change = $this->unlock->handle($this->targets->target($address, $input->reason), $actor); + + return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($address, $actor); + } + + /** + * `If-Match` against the address's current ETag: a mismatch is 412, a match makes the write + * conditional on that version (the version-checked update, §6). `*` matches any version. + * + * @throws ConcurrentModification + */ + private function expectedVersion(SettingAddress $address, ?string $ifMatch): ?int + { + if ($ifMatch === null || $ifMatch === '*') { + return null; + } + + $version = $this->targets->version($address); + + if (! in_array($address->etag($version), array_map(trim(...), explode(',', $ifMatch)), true)) { + throw new ConcurrentModification(sprintf('Setting [%s] in store [%s] changed since it was read: its ETag no longer matches If-Match.', $address->key, $address->store)); + } + + return $version; + } + + private function render(SettingAddress $address, Actor $actor): JsonResponse + { + $view = $this->read->handle($address, $actor); + + return new JsonResponse(['data' => SettingResource::fields($view)], 200, ['ETag' => $view->etag()]); + } + + private function accepted(ChangeRequest $change): JsonResponse + { + return new JsonResponse(['data' => new ChangeRequestResource($change)->resolve()], 202); + } +} diff --git a/src/Http/Controllers/StoresController.php b/src/Http/Controllers/StoresController.php new file mode 100644 index 0000000..646b5fc --- /dev/null +++ b/src/Http/Controllers/StoresController.php @@ -0,0 +1,38 @@ +stores->handle($this->actors->of($request)))); + } + + public function definitions(PageRequest $request): JsonResponse + { + $definitions = $this->definitions->handle($this->targets->store($request->addressData()->store), $this->actors->of($request)); + + return ListResponse::make(array_map(DefinitionResource::fields(...), $definitions)); + } +} diff --git a/src/Http/Controllers/TransferController.php b/src/Http/Controllers/TransferController.php new file mode 100644 index 0000000..871cccf --- /dev/null +++ b/src/Http/Controllers/TransferController.php @@ -0,0 +1,62 @@ +toData(); + $mode = ExportMode::tryFrom($input->text('mode') ?? 'redacted') ?? ExportMode::Redacted; + $document = $this->export->handle(new ExportRequest($this->targets->store($input->param('store')), $mode), $this->actors->of($request)); + + return new JsonResponse(['data' => $document->toArray()]); + } + + public function import(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $report = $this->import->handle(new ImportRequest( + $this->targets->store($input->param('store')), + ExportDocument::fromArray($input->array('document')), + apply: $input->boolean('apply'), + ), $this->actors->of($request)); + + return new JsonResponse(['data' => $report->toArray()]); + } + + public function diff(BodyRequest $request): JsonResponse + { + $input = $request->toData(); + $diff = $this->diff->handle($this->targets->store($input->param('store')), ExportDocument::fromArray($input->array('document')), $this->actors->of($request)); + + return new JsonResponse(['data' => $diff->toArray()]); + } +} diff --git a/src/Http/Middleware/FreshControllers.php b/src/Http/Middleware/FreshControllers.php new file mode 100644 index 0000000..f900478 --- /dev/null +++ b/src/Http/Middleware/FreshControllers.php @@ -0,0 +1,31 @@ +route(); + + if ($route instanceof Route) { + $route->flushController(); + } + + /** @var Response */ + return $next($request); + } +} diff --git a/src/Http/Middleware/IdempotentWrites.php b/src/Http/Middleware/IdempotentWrites.php new file mode 100644 index 0000000..6a414f3 --- /dev/null +++ b/src/Http/Middleware/IdempotentWrites.php @@ -0,0 +1,62 @@ +header('Idempotency-Key'); + + if (! is_string($key) || $key === '' || strlen($key) > 255) { + /** @var Response */ + return $next($request); + } + + $user = $request->user()?->getAuthIdentifier(); + $cacheKey = $this->prefix . ':idempotency:' . sha1(implode('|', [is_scalar($user) ? (string) $user : '', $request->method(), $request->path(), $key])); + $stored = $this->cache->get($cacheKey); + + if (is_array($stored) && is_int($stored['status'] ?? null) && is_string($stored['body'] ?? null)) { + $headers = is_array($stored['headers'] ?? null) ? $stored['headers'] : []; + + return new IlluminateResponse($stored['body'], $stored['status'], $headers + ['Idempotent-Replayed' => 'true']); + } + + /** @var Response $response */ + $response = $next($request); + + if ($response->getStatusCode() < 500) { + $this->cache->put($cacheKey, [ + 'status' => $response->getStatusCode(), + 'body' => (string) $response->getContent(), + 'headers' => array_filter([ + 'Content-Type' => $response->headers->get('Content-Type'), + 'ETag' => $response->headers->get('ETag'), + ], static fn (?string $value): bool => $value !== null), + ], $this->ttl); + } + + return $response; + } +} diff --git a/src/Http/OpenApi/OpenApiDocument.php b/src/Http/OpenApi/OpenApiDocument.php new file mode 100644 index 0000000..8517029 --- /dev/null +++ b/src/Http/OpenApi/OpenApiDocument.php @@ -0,0 +1,322 @@ + $routes the application's routes; only the API's are read + * + * @return array + */ + public static function build(iterable $routes, string $version = '0.1.0'): array + { + $paths = []; + + foreach ($routes as $route) { + $name = (string) $route->getName(); + + if (! str_starts_with($name, ApiRoutes::NAME_PREFIX)) { + continue; + } + + $capability = Capability::from(preg_replace('/^owners\./', '', substr($name, strlen(ApiRoutes::NAME_PREFIX))) ?? ''); + + foreach (array_diff($route->methods(), ['HEAD']) as $method) { + $paths['/' . $route->uri()][strtolower($method)] = self::operation($name, $capability, $route); + } + } + + ksort($paths); + + return [ + 'openapi' => '3.1.0', + 'info' => [ + 'title' => 'laranail/settings', + 'version' => $version, + 'description' => 'The settings REST API. Values the caller may not view are left out; errors are RFC 9457 problem details.', + ], + 'paths' => $paths, + 'components' => [ + 'schemas' => self::schemas(), + 'securitySchemes' => ['bearer' => ['type' => 'http', 'scheme' => 'bearer']], + ], + 'security' => [['bearer' => []]], + ]; + } + + /** + * The schema name a capability's success response holds, and whether it is a list. + * + * @return array{?string, bool, int} + */ + public static function response(Capability $capability): array + { + return match ($capability) { + Capability::StoresIndex => ['Store', true, 200], + Capability::DefinitionsIndex => ['Definition', true, 200], + Capability::SettingsIndex => ['Setting', true, 200], + Capability::SettingsShow, Capability::SettingsUpdate, Capability::SettingsLock, + Capability::SettingsUnlock, Capability::SettingsRollback => ['Setting', false, 200], + Capability::SettingsDestroy, Capability::CategoriesDestroy, Capability::ConfigurationDestroy, + Capability::DefinitionsDestroy => [null, false, 204], + Capability::SettingsExplain => ['Explanation', false, 200], + Capability::SettingsHistory => ['HistoryEntry', true, 200], + Capability::AuditIndex => ['AuditEntry', true, 200], + Capability::ChangesIndex => ['ChangeRequest', true, 200], + Capability::ChangesStore => ['ChangeRequest', false, 202], + Capability::ChangesShow, Capability::ChangesApprove, Capability::ChangesReject, Capability::ChangesCancel => ['ChangeRequest', false, 200], + Capability::CategoriesIndex => ['Category', true, 200], + Capability::CategoriesStore => ['Category', false, 201], + Capability::CategoriesUpdate => ['Category', false, 200], + Capability::ConfigurationIndex => ['ConfigurationEntry', true, 200], + Capability::ConfigurationUpdate => ['ConfigurationEntry', false, 200], + Capability::DefinitionsUpdate => ['Definition', false, 200], + Capability::TransferExport => ['ExportDocument', false, 200], + Capability::TransferImport => ['ImportReport', false, 200], + Capability::TransferDiff => ['StoreDiff', false, 200], + }; + } + + /** @return array */ + private static function operation(string $name, Capability $capability, Route $route): array + { + [$schema, $list, $status] = self::response($capability); + $parameters = []; + + foreach ($route->parameterNames() as $parameter) { + $parameters[] = ['name' => $parameter, 'in' => 'path', 'required' => true, 'schema' => ['type' => 'string']]; + } + + if (in_array($capability, [Capability::SettingsShow, Capability::SettingsIndex, Capability::SettingsExplain, Capability::SettingsHistory, Capability::SettingsUpdate], true)) { + $parameters[] = ['name' => 'locale', 'in' => 'query', 'required' => false, 'schema' => ['type' => 'string']]; + } + + if ($list) { + $parameters[] = ['name' => 'limit', 'in' => 'query', 'required' => false, 'schema' => ['type' => 'integer', 'minimum' => 1, 'maximum' => 200]]; + $parameters[] = ['name' => 'cursor', 'in' => 'query', 'required' => false, 'schema' => ['type' => 'string']]; + } + + $problem = ['description' => 'A problem (RFC 9457).', 'content' => ['application/problem+json' => ['schema' => ['$ref' => '#/components/schemas/Problem']]]]; + $responses = [(string) $status => $schema === null + ? ['description' => 'Done.'] + : ['description' => 'OK.', 'content' => ['application/json' => ['schema' => $list ? self::listOf($schema) : self::dataOf($schema)]]]]; + + if (in_array($capability, [Capability::SettingsUpdate, Capability::SettingsDestroy, Capability::SettingsLock, Capability::SettingsUnlock, Capability::SettingsRollback], true)) { + $responses['202'] = ['description' => 'The change needs approval: a change request was opened.', 'content' => ['application/json' => ['schema' => self::dataOf('ChangeRequest')]]]; + } + + foreach (['401', '403', '404', '409', '412', '422', '423', '428', '429'] as $code) { + $responses[$code] = $problem; + } + + return array_filter([ + 'operationId' => $name, + 'summary' => $capability->label(), + 'tags' => [$capability->group()], + 'parameters' => $parameters, + 'requestBody' => in_array('GET', $route->methods(), true) ? null : ['required' => false, 'content' => ['application/json' => ['schema' => ['type' => 'object']]]], + 'responses' => $responses, + ], static fn (mixed $value): bool => $value !== null); + } + + /** @return array */ + private static function dataOf(string $schema): array + { + return ['type' => 'object', 'required' => ['data'], 'properties' => ['data' => ['$ref' => '#/components/schemas/' . $schema]]]; + } + + /** @return array */ + private static function listOf(string $schema): array + { + return [ + 'type' => 'object', + 'required' => ['data', 'meta'], + 'properties' => [ + 'data' => ['type' => 'array', 'items' => ['$ref' => '#/components/schemas/' . $schema]], + 'meta' => ['type' => 'object', 'required' => ['next_cursor'], 'properties' => ['next_cursor' => ['type' => ['string', 'null']]]], + ], + ]; + } + + /** @return array */ + private static function schemas(): array + { + $string = ['type' => 'string']; + $nullableString = ['type' => ['string', 'null']]; + $nullableInteger = ['type' => ['integer', 'null']]; + $boolean = ['type' => 'boolean']; + $strings = ['type' => 'array', 'items' => $string]; + $object = static fn (array $properties, array $required): array => ['type' => 'object', 'required' => $required, 'properties' => $properties]; + + return [ + 'Problem' => $object([ + 'type' => $string, + 'title' => $string, + 'status' => ['type' => 'integer'], + 'detail' => $string, + 'instance' => $nullableString, + 'errors' => ['type' => 'object'], + ], ['type', 'title', 'status', 'detail']), + 'Setting' => $object([ + 'store' => $string, + 'scope' => $string, + 'key' => $string, + 'locale' => $string, + 'found' => $boolean, + 'layer' => $nullableString, + 'from' => $nullableString, + 'version' => ['type' => 'integer'], + 'redacted' => $boolean, + 'value' => [], + ], ['store', 'scope', 'key', 'locale', 'found', 'version', 'redacted']), + 'Store' => $object([ + 'name' => $string, + 'mode' => ['type' => 'string', 'enum' => ['polymorphic', 'dedicated']], + 'owners' => $strings, + 'layers' => $strings, + 'strict' => $boolean, + 'inherits' => $boolean, + 'fallback' => $nullableString, + 'approvals' => $strings, + ], ['name', 'mode', 'owners', 'layers', 'strict', 'inherits']), + 'Definition' => $object([ + 'store' => $string, + 'key' => $string, + 'group' => $string, + 'category' => $nullableString, + 'type' => $nullableString, + 'has_default' => $boolean, + 'default' => [], + 'rules' => $strings, + 'encrypted' => $boolean, + 'sensitive' => $boolean, + 'public' => $boolean, + 'locked' => $boolean, + 'localised' => $boolean, + 'inherits' => ['type' => ['boolean', 'null']], + 'overridable_by' => $strings, + 'precedence' => $string, + 'label' => $nullableString, + 'description' => $nullableString, + 'requires_verification' => $boolean, + 'requires_approval' => $boolean, + ], ['store', 'key', 'group', 'has_default', 'encrypted', 'sensitive']), + 'Explanation' => $object([ + 'found' => $boolean, + 'layer' => $nullableString, + 'from' => $nullableString, + 'redacted' => $boolean, + 'steps' => $strings, + 'value' => [], + ], ['found', 'redacted', 'steps']), + 'HistoryEntry' => $object([ + 'id' => $string, + 'store' => $string, + 'setting_ref' => $nullableString, + 'scope' => $string, + 'key' => $string, + 'locale' => $string, + 'operation' => $string, + 'old_value' => $nullableString, + 'new_value' => $nullableString, + 'old_type' => $nullableString, + 'new_type' => $nullableString, + 'old_encrypted' => $boolean, + 'new_encrypted' => $boolean, + 'version' => ['type' => 'integer'], + 'causer_type' => $string, + 'causer_alias' => $nullableString, + 'causer_id' => $nullableString, + 'reason' => $nullableString, + 'created_at' => $string, + ], ['id', 'store', 'scope', 'key', 'operation', 'version', 'created_at']), + 'AuditEntry' => $object([ + 'id' => $string, + 'occurred_at' => $string, + 'action' => $string, + 'outcome' => ['type' => 'string', 'enum' => ['allowed', 'denied', 'pending', 'failed']], + 'store' => $nullableString, + 'scope' => $nullableString, + 'key' => $nullableString, + 'locale' => $nullableString, + 'version_from' => $nullableInteger, + 'version_to' => $nullableInteger, + 'actor_type' => $string, + 'actor_alias' => $nullableString, + 'actor_id' => $nullableString, + 'channel' => $string, + ], ['id', 'occurred_at', 'action', 'outcome', 'actor_type', 'channel']), + 'ChangeRequest' => $object([ + 'id' => $string, + 'store' => $string, + 'scope' => $string, + 'key' => $string, + 'locale' => $string, + 'operation' => ['type' => 'string', 'enum' => ['set', 'forget', 'lock', 'unlock']], + 'encrypted' => $boolean, + 'base_version' => ['type' => 'integer'], + 'status' => ['type' => 'string', 'enum' => ['pending', 'approved', 'applied', 'rejected', 'cancelled', 'stale', 'expired']], + 'requested_by' => ['type' => 'object'], + 'approvals' => $strings, + 'decided_by' => ['type' => ['object', 'null']], + 'decided_at' => $nullableString, + 'reason' => $nullableString, + 'decision_reason' => $nullableString, + 'expires_at' => $nullableString, + 'created_at' => $nullableString, + ], ['id', 'store', 'scope', 'key', 'operation', 'status', 'base_version']), + 'Category' => $object([ + 'slug' => $string, + 'store' => $string, + 'title' => $string, + 'titles' => ['type' => 'object'], + 'parent' => $nullableString, + 'description' => $nullableString, + 'icon' => $nullableString, + 'sort_order' => ['type' => 'integer'], + 'system' => $boolean, + ], ['slug', 'store', 'title', 'sort_order', 'system']), + 'ConfigurationEntry' => $object([ + 'kind' => ['type' => 'string', 'enum' => ['store', 'layer']], + 'name' => $string, + 'config' => ['type' => 'object'], + ], ['kind', 'name', 'config']), + 'ExportDocument' => $object([ + 'format' => ['type' => 'string', 'const' => 'laranail/settings'], + 'version' => ['type' => 'integer'], + 'store' => $string, + 'mode' => ['type' => 'string', 'enum' => ['redacted', 'ciphertext', 'plaintext']], + 'categories' => ['type' => 'array', 'items' => ['type' => 'object']], + 'settings' => ['type' => 'array', 'items' => ['type' => 'object']], + ], ['format', 'version', 'store', 'mode', 'categories', 'settings']), + 'ImportReport' => $object([ + 'applied' => $boolean, + 'created' => $strings, + 'updated' => $strings, + 'unchanged' => $strings, + 'skipped' => ['type' => ['object', 'array']], + 'categories' => $strings, + 'proposed' => $strings, + ], ['applied', 'created', 'updated', 'unchanged', 'skipped']), + 'StoreDiff' => $object([ + 'added' => $strings, + 'removed' => $strings, + 'changed' => $strings, + 'unchanged' => $strings, + 'unknown' => $strings, + ], ['added', 'removed', 'changed', 'unchanged', 'unknown']), + ]; + } +} diff --git a/src/Http/Requests/BodyRequest.php b/src/Http/Requests/BodyRequest.php new file mode 100644 index 0000000..33e7ee7 --- /dev/null +++ b/src/Http/Requests/BodyRequest.php @@ -0,0 +1,79 @@ +> */ + public function rules(): array + { + $name = (string) $this->route()?->getName(); + + return match (true) { + str_ends_with($name, 'changes.store') => [ + 'store' => ['nullable', 'string', 'max:64'], + 'key' => ['required', 'string', 'max:191'], + 'value' => ['nullable'], + 'owner' => ['nullable', 'array'], + 'owner.alias' => ['required_with:owner', 'string', 'max:64'], + 'owner.id' => ['required_with:owner', 'string', 'max:36'], + 'locale' => ['nullable', 'string', 'max:16'], + 'operation' => ['nullable', 'string', 'in:set,forget,lock,unlock'], + 'reason' => ['nullable', 'string', 'max:255'], + ], + str_ends_with($name, 'categories.store') => [ + 'slug' => ['required', 'string', 'max:128'], + 'title' => ['required', 'string', 'max:255'], + 'parent' => ['nullable', 'string', 'max:128'], + 'description' => ['nullable', 'string'], + 'icon' => ['nullable', 'string', 'max:255'], + 'sort_order' => ['nullable', 'integer', 'min:0'], + 'titles' => ['nullable', 'array'], + ], + str_ends_with($name, 'categories.update') => [ + 'title' => ['nullable', 'string', 'max:255'], + 'parent' => ['nullable', 'string', 'max:128'], + ], + str_ends_with($name, 'configuration.update') => ['config' => ['required', 'array']], + str_ends_with($name, 'definitions.update') => ['attributes' => ['present', 'array']], + str_ends_with($name, 'transfer.export') => ['mode' => ['nullable', 'string', 'in:redacted,ciphertext,plaintext']], + str_ends_with($name, 'transfer.import'), + str_ends_with($name, 'transfer.diff') => ['document' => ['required', 'array'], 'apply' => ['nullable', 'boolean']], + default => ['reason' => ['nullable', 'string', 'max:255']], + }; + } + + public function toData(): BodyInput + { + $params = []; + + foreach (['store', 'id', 'slug', 'kind', 'name', 'key'] as $parameter) { + $value = $this->route($parameter); + + if (is_string($value)) { + $params[$parameter] = $value; + } + } + + /** @var array $body */ + $body = $this->validated(); + + return new BodyInput($params, $body, $this->has('parent')); + } +} diff --git a/src/Http/Requests/Concerns/ReadsAddress.php b/src/Http/Requests/Concerns/ReadsAddress.php new file mode 100644 index 0000000..619319a --- /dev/null +++ b/src/Http/Requests/Concerns/ReadsAddress.php @@ -0,0 +1,31 @@ +> */ + protected function addressRules(): array + { + return ['locale' => ['nullable', 'string', 'max:16']]; + } + + protected function address(): AddressInput + { + $text = fn (string $name): ?string => is_string($this->route($name)) ? $this->route($name) : null; + $locale = $this->query('locale'); + + return new AddressInput( + $text('store') ?? '', + $text('key') ?? '', + $text('alias'), + $text('id'), + is_string($locale) ? $locale : '', + ); + } +} diff --git a/src/Http/Requests/PageRequest.php b/src/Http/Requests/PageRequest.php new file mode 100644 index 0000000..6fcec2e --- /dev/null +++ b/src/Http/Requests/PageRequest.php @@ -0,0 +1,60 @@ +> */ + public function rules(): array + { + return [ + 'limit' => ['nullable', 'integer', 'min:1', 'max:200'], + 'cursor' => ['nullable', 'string', 'max:255'], + 'since' => ['nullable', 'date'], + 'until' => ['nullable', 'date'], + ] + array_fill_keys(array_diff(self::FILTERS, ['since', 'until']), ['nullable', 'string', 'max:191']); + } + + public function toData(int $defaultLimit = 50): PageInput + { + $limit = $this->query('limit'); + $cursor = $this->query('cursor'); + $filters = []; + + foreach (self::FILTERS as $name) { + $value = $this->query($name); + + if (is_string($value) && $value !== '') { + $filters[$name] = $value; + } + } + + return new PageInput(is_numeric($limit) ? (int) $limit : $defaultLimit, is_string($cursor) && $cursor !== '' ? $cursor : null, $filters); + } + + public function addressData(): AddressInput + { + return $this->address(); + } +} diff --git a/src/Http/Requests/SettingRequest.php b/src/Http/Requests/SettingRequest.php new file mode 100644 index 0000000..8a79317 --- /dev/null +++ b/src/Http/Requests/SettingRequest.php @@ -0,0 +1,31 @@ +> */ + public function rules(): array + { + return $this->addressRules(); + } + + public function toData(): AddressInput + { + return $this->address(); + } +} diff --git a/src/Http/Requests/WriteSettingRequest.php b/src/Http/Requests/WriteSettingRequest.php new file mode 100644 index 0000000..c0b72ae --- /dev/null +++ b/src/Http/Requests/WriteSettingRequest.php @@ -0,0 +1,54 @@ +> */ + public function rules(): array + { + $rules = $this->addressRules() + ['reason' => ['nullable', 'string', 'max:255']]; + + if ($this->isMethod('PUT')) { + $rules['value'] = ['present']; + } + + if (str_ends_with($this->path(), '/rollback')) { + $rules['version'] = ['required', 'integer', 'min:1']; + } + + return $rules; + } + + public function toData(): WriteInput + { + $reason = $this->input('reason'); + $version = $this->input('version'); + $ifMatch = $this->header('If-Match'); + + return new WriteInput( + $this->address(), + $this->input('value'), + is_string($reason) ? $reason : null, + is_string($ifMatch) && $ifMatch !== '' ? $ifMatch : null, + is_numeric($version) ? (int) $version : null, + ); + } +} diff --git a/src/Http/Resources/CategoryResource.php b/src/Http/Resources/CategoryResource.php new file mode 100644 index 0000000..1639dd6 --- /dev/null +++ b/src/Http/Resources/CategoryResource.php @@ -0,0 +1,27 @@ + */ + public static function fields(Category $category): array + { + return [ + 'slug' => $category->slug->value, + 'store' => $category->store->value, + 'title' => $category->title, + 'titles' => (object) $category->titles, + 'parent' => $category->parent?->value, + 'description' => $category->description, + 'icon' => $category->icon, + 'sort_order' => $category->sortOrder, + 'system' => $category->system, + ]; + } +} diff --git a/src/Http/Resources/ChangeRequestResource.php b/src/Http/Resources/ChangeRequestResource.php new file mode 100644 index 0000000..76b0986 --- /dev/null +++ b/src/Http/Resources/ChangeRequestResource.php @@ -0,0 +1,30 @@ + */ + #[Override] + public function toArray(Request $request): array + { + return $this->resource->toArray(); + } +} diff --git a/src/Http/Resources/DefinitionResource.php b/src/Http/Resources/DefinitionResource.php new file mode 100644 index 0000000..5a39392 --- /dev/null +++ b/src/Http/Resources/DefinitionResource.php @@ -0,0 +1,43 @@ + */ + public static function fields(Definition $definition): array + { + $fields = [ + 'store' => $definition->store->value, + 'key' => $definition->key->value, + 'group' => $definition->group(), + 'category' => $definition->category, + 'type' => $definition->type, + 'has_default' => $definition->hasDefault && ! $definition->encrypted, + 'rules' => $definition->rules, + 'encrypted' => $definition->encrypted, + 'sensitive' => $definition->isSensitive(), + 'public' => $definition->public, + 'locked' => $definition->locked, + 'localised' => $definition->localised, + 'inherits' => $definition->inherits, + 'overridable_by' => $definition->overridableBy, + 'precedence' => $definition->precedence->value, + 'label' => $definition->label, + 'description' => $definition->description, + 'requires_verification' => $definition->requiresVerification, + 'requires_approval' => $definition->requiresApproval, + ]; + + if ($definition->hasDefault && ! $definition->encrypted) { + $fields['default'] = $definition->default; + } + + return $fields; + } +} diff --git a/src/Http/Resources/ExplanationResource.php b/src/Http/Resources/ExplanationResource.php new file mode 100644 index 0000000..9114626 --- /dev/null +++ b/src/Http/Resources/ExplanationResource.php @@ -0,0 +1,30 @@ + */ + public static function fields(Explanation $explanation): array + { + $lookup = $explanation->lookup; + $fields = [ + 'found' => $lookup->isFound(), + 'layer' => $lookup->layer(), + 'from' => $lookup->scope()?->value, + 'redacted' => $lookup->isRedacted(), + 'steps' => $explanation->steps, + ]; + + if ($lookup->isFound() && ! $lookup->isRedacted()) { + $fields['value'] = $lookup->value(); + } + + return $fields; + } +} diff --git a/src/Http/Resources/SettingResource.php b/src/Http/Resources/SettingResource.php new file mode 100644 index 0000000..2035318 --- /dev/null +++ b/src/Http/Resources/SettingResource.php @@ -0,0 +1,55 @@ + */ + public static function fields(SettingView $view): array + { + $fields = [ + 'store' => $view->address->store, + 'scope' => Scope::of($view->address->ownerRef())->value, + 'key' => $view->address->key, + 'locale' => new Locale($view->address->locale)->value, + 'found' => $view->found, + 'layer' => $view->layer, + 'from' => $view->from, + 'version' => $view->version, + 'redacted' => $view->redacted, + ]; + + if (! $view->redacted) { + $fields['value'] = $view->value; + } + + return $fields; + } + + /** @return array */ + #[Override] + public function toArray(Request $request): array + { + return self::fields($this->resource); + } +} diff --git a/src/Http/Resources/StoreResource.php b/src/Http/Resources/StoreResource.php new file mode 100644 index 0000000..7eed0ff --- /dev/null +++ b/src/Http/Resources/StoreResource.php @@ -0,0 +1,27 @@ + */ + public static function fields(Store $store): array + { + return [ + 'name' => $store->name->value, + 'mode' => $store->mode->value, + 'owners' => $store->owners, + 'layers' => array_map(static fn (Layer $layer): string => $layer->name, $store->layers), + 'strict' => $store->strict, + 'inherits' => $store->inherits, + 'fallback' => $store->fallback?->value, + 'approvals' => $store->approvalKeys, + ]; + } +} diff --git a/src/Http/Support/Addresses.php b/src/Http/Support/Addresses.php new file mode 100644 index 0000000..c4e9359 --- /dev/null +++ b/src/Http/Support/Addresses.php @@ -0,0 +1,26 @@ +alias !== null && $input->id !== null ? $this->owners->resolve($input->alias, $input->id) : null; + + return new SettingAddress($input->store, $input->key, $owner, $input->locale); + } +} diff --git a/src/Http/Support/ApiActor.php b/src/Http/Support/ApiActor.php new file mode 100644 index 0000000..1e7bf28 --- /dev/null +++ b/src/Http/Support/ApiActor.php @@ -0,0 +1,32 @@ +access->resolveActor($request) ?? throw new ActorRequired('The settings API needs an authenticated actor.'); + $actor = $actor->withChannel(Channel::Rest); + + return $reason === null || $reason === '' ? $actor : $actor->withReason($reason); + } +} diff --git a/src/Http/Support/ListResponse.php b/src/Http/Support/ListResponse.php new file mode 100644 index 0000000..2064ccc --- /dev/null +++ b/src/Http/Support/ListResponse.php @@ -0,0 +1,17 @@ +> $items */ + public static function make(array $items, ?string $nextCursor = null): JsonResponse + { + return new JsonResponse(['data' => $items, 'meta' => ['next_cursor' => $nextCursor]]); + } +} diff --git a/src/Http/Support/Problems.php b/src/Http/Support/Problems.php new file mode 100644 index 0000000..427afd8 --- /dev/null +++ b/src/Http/Support/Problems.php @@ -0,0 +1,121 @@ +, array{int, string}> */ + private const array MAP = [ + AccessDenied::class => [403, 'access-denied'], + ActorRequired::class => [401, 'actor-required'], + VerificationRequired::class => [428, 'verification-required'], + UnknownStore::class => [404, 'unknown-store'], + UnknownSetting::class => [404, 'unknown-setting'], + UnknownOwner::class => [404, 'unknown-owner'], + UnknownCategory::class => [404, 'unknown-category'], + UnknownChangeRequest::class => [404, 'unknown-change-request'], + InvalidSettingValue::class => [422, 'invalid-value'], + InvalidIdentifier::class => [422, 'invalid-identifier'], + InvalidImport::class => [422, 'invalid-import'], + InvalidDefinition::class => [422, 'invalid-definition'], + InvalidConfiguration::class => [422, 'invalid-configuration'], + TypeMismatch::class => [422, 'type-mismatch'], + CategoryCycle::class => [422, 'category-cycle'], + CategoryStoreMismatch::class => [422, 'category-store-mismatch'], + LockedSetting::class => [423, 'locked'], + ConcurrentModification::class => [412, 'precondition-failed'], + ApprovalUnavailable::class => [409, 'approval-unavailable'], + ChangeRequestClosed::class => [409, 'change-request-closed'], + OwnerNotAllowed::class => [409, 'owner-not-allowed'], + StoreNotWritable::class => [409, 'store-not-writable'], + HistoryUnavailable::class => [409, 'history-unavailable'], + DriverUnavailable::class => [503, 'unavailable'], + ]; + + /** The problem response for an exception raised by an API route, or null to leave it alone. */ + public static function render(Throwable $exception, Request $request): ?JsonResponse + { + $route = $request->route(); + + if (! is_object($route) || ! method_exists($route, 'getName') || ! str_starts_with((string) $route->getName(), 'laranail-settings.api.')) { + return null; + } + + return match (true) { + $exception instanceof ValidationException => self::make(422, 'validation', 'The request is invalid.', $request, ['errors' => $exception->errors()]), + $exception instanceof AuthenticationException => self::make(401, 'unauthenticated', 'Authentication is required.', $request), + $exception instanceof ThrottleRequestsException => self::make(429, 'too-many-requests', 'Too many requests.', $request), + $exception instanceof SettingsException => self::forSettings($exception, $request), + $exception instanceof HttpExceptionInterface => self::make($exception->getStatusCode(), 'http-' . $exception->getStatusCode(), $exception->getMessage() !== '' ? $exception->getMessage() : 'The request failed.', $request), + default => null, + }; + } + + /** + * @param array $extra + */ + public static function make(int $status, string $type, string $detail, ?Request $request = null, array $extra = []): JsonResponse + { + return new JsonResponse([ + 'type' => self::TYPE_BASE . $type, + 'title' => ucfirst(str_replace('-', ' ', $type)), + 'status' => $status, + 'detail' => $detail, + 'instance' => $request?->getRequestUri(), + ] + $extra, $status, ['Content-Type' => 'application/problem+json']); + } + + private static function forSettings(SettingsException $exception, Request $request): JsonResponse + { + foreach (self::MAP as $class => [$status, $type]) { + if ($exception instanceof $class) { + return self::make($status, $type, $exception->getMessage(), $request); + } + } + + return self::make(500, 'settings-error', 'The settings operation failed.', $request); + } +} diff --git a/src/Importers/AkauntingSettingsImporter.php b/src/Importers/AkauntingSettingsImporter.php new file mode 100644 index 0000000..835630b --- /dev/null +++ b/src/Importers/AkauntingSettingsImporter.php @@ -0,0 +1,58 @@ +` or + * `:
` (default table `settings`). Rows its extra columns scope to a model or + * team are skipped, because that scoping is the application's own. + */ +final readonly class AkauntingSettingsImporter implements Importer +{ + public function __construct( + private ConnectionResolverInterface $db, + ) {} + + public function read(string $source, StoreName $store): ExportDocument + { + [$connection, $table] = array_pad(explode(':', $source, 2), 2, null); + $table = $table === null || $table === '' ? 'settings' : $table; + + try { + $rows = $this->db->connection($connection === '' ? null : $connection)->table($table)->get()->all(); + } catch (Exception $exception) { + throw new InvalidImport(sprintf('akaunting: table [%s] on connection [%s] cannot be read (%s).', $table, $connection ?: 'default', $exception->getMessage()), 0, $exception); + } + + $values = []; + + foreach ($rows as $row) { + $row = (array) $row; + + if (! array_key_exists('key', $row) || ! array_key_exists('value', $row)) { + throw new InvalidImport(sprintf('akaunting: table [%s] has no key and value columns.', $table)); + } + + // Extra columns (user_id, company_id, …) scope a row to something of the host's own. + if (array_filter(array_diff_key($row, array_flip(['id', 'key', 'value', 'created_at', 'updated_at'])), static fn (mixed $value): bool => $value !== null) !== []) { + continue; + } + + $values[ImportedKeys::key(is_string($row['key']) ? $row['key'] : '', 'akaunting')->value] = [$row['value'], false]; + } + + return ImportedKeys::document($store, $values, 'akaunting'); + } +} diff --git a/src/Importers/ImportedKeys.php b/src/Importers/ImportedKeys.php new file mode 100644 index 0000000..ab39260 --- /dev/null +++ b/src/Importers/ImportedKeys.php @@ -0,0 +1,49 @@ +getMessage()), 0, $exception); + } + } + + /** + * Global values as a document of the store. + * + * @param array $values key => [value, locked] + */ + public static function document(StoreName $store, array $values, string $source): ExportDocument + { + ksort($values); + $settings = []; + + foreach ($values as $key => [$value, $locked]) { + $settings[] = new ExportedSetting(Scope::global(), new Key($key), Locale::none(), $value, locked: $locked); + } + + return new ExportDocument($store->value, [], $settings, ExportMode::Plaintext, null, $source); + } +} diff --git a/src/Importers/SpatieSettingsImporter.php b/src/Importers/SpatieSettingsImporter.php new file mode 100644 index 0000000..131c229 --- /dev/null +++ b/src/Importers/SpatieSettingsImporter.php @@ -0,0 +1,53 @@ +.` with its JSON + * payload decoded, and `locked` kept (applied only by a trusted import). `$source` is + * `` or `:
` (default table `settings`; an empty connection is the + * default one). Values spatie stored encrypted arrive as the ciphertext spatie wrote: define those + * keys encrypted here and set them again. + */ +final readonly class SpatieSettingsImporter implements Importer +{ + public function __construct( + private ConnectionResolverInterface $db, + ) {} + + public function read(string $source, StoreName $store): ExportDocument + { + [$connection, $table] = array_pad(explode(':', $source, 2), 2, null); + $table = $table === null || $table === '' ? 'settings' : $table; + + try { + $rows = $this->db->connection($connection === '' ? null : $connection)->table($table)->get(['group', 'name', 'payload', 'locked'])->all(); + } catch (Exception $exception) { + throw new InvalidImport(sprintf('spatie: table [%s] on connection [%s] is not a spatie/laravel-settings table (%s).', $table, $connection ?: 'default', $exception->getMessage()), 0, $exception); + } + + $values = []; + + foreach ($rows as $row) { + $row = (array) $row; + $group = is_string($row['group'] ?? null) ? $row['group'] : ''; + $name = is_string($row['name'] ?? null) ? $row['name'] : ''; + $payload = is_string($row['payload'] ?? null) ? json_decode($row['payload'], true) : null; + $key = ImportedKeys::key($group . '.' . $name, 'spatie'); + + $values[$key->value] = [$payload, (bool) ($row['locked'] ?? false)]; + } + + return ImportedKeys::document($store, $values, 'spatie'); + } +} diff --git a/src/Importers/ToolkitJsonImporter.php b/src/Importers/ToolkitJsonImporter.php new file mode 100644 index 0000000..6f0cbe6 --- /dev/null +++ b/src/Importers/ToolkitJsonImporter.php @@ -0,0 +1,67 @@ +files->isFile($source)) { + throw new InvalidImport(sprintf('toolkit: [%s] is not a file.', $source)); + } + + $data = json_decode($this->files->get($source), true); + + if (! is_array($data)) { + throw new InvalidImport(sprintf('toolkit: [%s] is not a JSON object.', $source)); + } + + $values = []; + + foreach ($this->flatten($data) as $key => $value) { + $values[ImportedKeys::key($key, 'toolkit')->value] = [$value, false]; + } + + return ImportedKeys::document($store, $values, 'toolkit'); + } + + /** + * @param array $data + * + * @return array + */ + private function flatten(array $data, string $prefix = ''): array + { + $flat = []; + + foreach ($data as $key => $value) { + $path = $prefix === '' ? (string) $key : $prefix . '.' . $key; + + if (is_array($value) && $value !== [] && ! array_is_list($value)) { + $flat += $this->flatten($value, $path); + } else { + $flat[$path] = $value; + } + } + + return $flat; + } +} diff --git a/src/Listeners/SendSettingsAlert.php b/src/Listeners/SendSettingsAlert.php index 7b6c831..5868766 100644 --- a/src/Listeners/SendSettingsAlert.php +++ b/src/Listeners/SendSettingsAlert.php @@ -13,18 +13,22 @@ use Simtabi\Laranail\Settings\Data\AlertContext; use Illuminate\Notifications\AnonymousNotifiable; use Simtabi\Laranail\Settings\Events\AuditPruned; +use Simtabi\Laranail\Settings\Events\ChangeStale; use Simtabi\Laranail\Settings\Events\ScopeFlushed; use Simtabi\Laranail\Settings\Events\SettingSaved; use Illuminate\Contracts\Cache\Repository as Cache; use Simtabi\Laranail\Settings\Events\CategoryMoved; use Simtabi\Laranail\Settings\Events\CategorySaved; +use Simtabi\Laranail\Settings\Events\ChangeApplied; use Simtabi\Laranail\Settings\Events\HistoryPruned; use Simtabi\Laranail\Settings\Events\OrphansPruned; use Simtabi\Laranail\Settings\Events\SettingLocked; use Simtabi\Laranail\Settings\Events\StorePromoted; +use Simtabi\Laranail\Settings\Events\ChangeRejected; use Simtabi\Laranail\Settings\Events\AccessWasDenied; use Simtabi\Laranail\Settings\Events\CategoryDeleted; use Simtabi\Laranail\Settings\Events\CategoryRenamed; +use Simtabi\Laranail\Settings\Events\ChangeRequested; use Simtabi\Laranail\Settings\Events\SettingUnlocked; use Simtabi\Laranail\Settings\Events\SettingForgotten; use Simtabi\Laranail\Settings\Events\DefinitionsSynced; @@ -66,6 +70,10 @@ OrphansPruned::class, AccessWasDenied::class, VerificationWasRequired::class, + ChangeRequested::class, + ChangeApplied::class, + ChangeRejected::class, + ChangeStale::class, ]; /** diff --git a/src/Owners/MorphMapOwnerResolver.php b/src/Owners/MorphMapOwnerResolver.php new file mode 100644 index 0000000..1300e3e --- /dev/null +++ b/src/Owners/MorphMapOwnerResolver.php @@ -0,0 +1,56 @@ +morphed)($alias); + + if (! is_string($class) || ! class_exists($class)) { + throw new UnknownOwner(sprintf('Owner alias [%s] is not in the morph map.', $alias)); + } + + try { + $ref = new OwnerRef($alias, $id); + } catch (SettingsException $exception) { + throw new UnknownOwner($exception->getMessage(), 0, $exception); + } + + if (! is_subclass_of($class, Settable::class) || ! is_subclass_of($class, Model::class)) { + return $ref; + } + + $model = $class::query()->find($id); + + if (! $model instanceof Settable || ! $model instanceof Model) { + throw new UnknownOwner(sprintf('No [%s] owner with id [%s].', $alias, $id)); + } + + // Its parents count only when the alias is the model's own morph alias; otherwise the + // owner is addressed by alias and id alone, as the URL named it. + return $model->getMorphClass() === $alias ? $model : $ref; + } +} diff --git a/src/Providers/SettingsServiceProvider.php b/src/Providers/SettingsServiceProvider.php index 579efa9..b6a1c83 100644 --- a/src/Providers/SettingsServiceProvider.php +++ b/src/Providers/SettingsServiceProvider.php @@ -13,8 +13,12 @@ use Illuminate\Http\Request; use InvalidArgumentException; use Illuminate\Log\LogManager; +use Illuminate\Routing\Router; +use Illuminate\Http\JsonResponse; +use Illuminate\Database\Connection; use Illuminate\Filesystem\Filesystem; use Simtabi\Laranail\Settings\Data\Key; +use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Contracts\Session\Session; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Scope; @@ -22,15 +26,18 @@ use Illuminate\Queue\Events\JobProcessing; use Illuminate\Contracts\Config\Repository; use Illuminate\Contracts\Events\Dispatcher; +use Illuminate\Support\Facades\RateLimiter; use Simtabi\Laranail\Package\Tools\Package; use Simtabi\Laranail\Settings\Stores\Store; use Illuminate\Contracts\Validation\Factory; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\AlertRule; use Simtabi\Laranail\Settings\Data\StoreName; +use Simtabi\Laranail\Settings\Http\ApiRoutes; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\SettingsManager; use Illuminate\Database\Events\MigrationsEnded; +use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Contracts\Foundation\Application; use Simtabi\Laranail\Settings\Actions\MakeStore; use Simtabi\Laranail\Settings\Actions\WarmCache; @@ -40,6 +47,7 @@ use Simtabi\Laranail\Settings\Actions\FlushScope; use Simtabi\Laranail\Settings\Actions\PruneAudit; use Simtabi\Laranail\Settings\Actions\QueryAudit; +use Simtabi\Laranail\Settings\Actions\SetSetting; use Simtabi\Laranail\Settings\Actions\WriteGuard; use Simtabi\Laranail\Settings\Audit\LogAuditSink; use Simtabi\Laranail\Settings\Contracts\Settings; @@ -47,11 +55,15 @@ use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Actions\DiffHistory; use Simtabi\Laranail\Settings\Actions\FindOrphans; +use Simtabi\Laranail\Settings\Actions\LockSetting; use Simtabi\Laranail\Settings\Audit\AutoAuditSink; use Simtabi\Laranail\Settings\Audit\NullAuditSink; +use Simtabi\Laranail\Settings\Console\DiffCommand; use Simtabi\Laranail\Settings\Contracts\AuditSink; +use Simtabi\Laranail\Settings\Data\ApprovalPolicy; use Simtabi\Laranail\Settings\Events\LayerSkipped; use Simtabi\Laranail\Settings\Models\ModelContext; +use Simtabi\Laranail\Settings\Typed\TypedSettings; use Illuminate\Cache\Repository as CacheRepository; use Simtabi\Laranail\Settings\Actions\PromoteStore; use Simtabi\Laranail\Settings\Actions\PruneHistory; @@ -66,20 +78,33 @@ use Illuminate\Contracts\Encryption\StringEncrypter; use Illuminate\Database\ConnectionResolverInterface; use Illuminate\Database\Eloquent\Relations\Relation; +use Simtabi\Laranail\Settings\Actions\ForgetSetting; +use Simtabi\Laranail\Settings\Actions\UnlockSetting; use Simtabi\Laranail\Settings\Console\DoctorCommand; +use Simtabi\Laranail\Settings\Console\ExportCommand; +use Simtabi\Laranail\Settings\Console\ImportCommand; +use Simtabi\Laranail\Settings\Http\Support\Problems; use Illuminate\Contracts\Auth\Factory as AuthFactory; use Illuminate\Contracts\Filesystem\Factory as Disks; use Simtabi\Laranail\Settings\Actions\HistoryActions; use Simtabi\Laranail\Settings\Actions\SettingActions; use Simtabi\Laranail\Settings\Console\HistoryCommand; +use Simtabi\Laranail\Settings\Console\OpenApiCommand; use Simtabi\Laranail\Settings\Console\PromoteCommand; +use Simtabi\Laranail\Settings\Console\RescopeCommand; use Simtabi\Laranail\Settings\Drivers\ReadOnlyValues; +use Simtabi\Laranail\Settings\Typed\SettingsMigrator; +use Simtabi\Laranail\Settings\Actions\MigrateSettings; use Simtabi\Laranail\Settings\Actions\RollbackSetting; use Simtabi\Laranail\Settings\Actions\SyncDefinitions; use Simtabi\Laranail\Settings\Audit\DatabaseAuditSink; use Simtabi\Laranail\Settings\Contracts\ActorResolver; +use Simtabi\Laranail\Settings\Contracts\OwnerResolver; use Simtabi\Laranail\Settings\Services\Access\Auditor; +use Simtabi\Laranail\Settings\Typed\SettingsMigration; +use Simtabi\Laranail\Settings\Actions\DiagnoseSettings; use Simtabi\Laranail\Settings\Console\MakeStoreCommand; +use Simtabi\Laranail\Settings\Console\ReencryptCommand; use Simtabi\Laranail\Settings\Console\WarmCacheCommand; use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; @@ -90,16 +115,22 @@ use Simtabi\Laranail\Settings\Console\PruneAuditCommand; use Simtabi\Laranail\Settings\Logging\OperationalLogger; use Simtabi\Laranail\Settings\Verification\NullVerifier; +use Simtabi\Laranail\Settings\Actions\Transfer\DiffStore; use Simtabi\Laranail\Settings\Listeners\LogSettingsEvent; +use Simtabi\Laranail\Settings\Console\PruneChangesCommand; use Simtabi\Laranail\Settings\Console\PruneHistoryCommand; use Simtabi\Laranail\Settings\Console\PruneOrphansCommand; use Simtabi\Laranail\Settings\Contracts\BootstrapEvidence; use Simtabi\Laranail\Settings\Listeners\SendSettingsAlert; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Transfer\Importers; use Simtabi\Laranail\Settings\Stores\InstallationEvidence; use Simtabi\Laranail\Package\Tools\Commands\InstallCommand; +use Simtabi\Laranail\Settings\Actions\Transfer\ExportStore; +use Simtabi\Laranail\Settings\Actions\Transfer\ImportStore; use Simtabi\Laranail\Settings\Authorization\GateAuthorizer; use Simtabi\Laranail\Settings\Exceptions\SettingsException; +use Simtabi\Laranail\Settings\Owners\MorphMapOwnerResolver; use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; use Simtabi\Laranail\Settings\Services\Resolution\Resolver; use Simtabi\Laranail\Settings\Authorization\ChainAuthorizer; @@ -110,26 +141,48 @@ use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; use Simtabi\Laranail\Settings\Support\LaravelValueValidator; +use Simtabi\Laranail\Settings\Actions\Approvals\CancelChange; +use Simtabi\Laranail\Settings\Actions\Approvals\PruneChanges; +use Simtabi\Laranail\Settings\Actions\Approvals\QueryChanges; +use Simtabi\Laranail\Settings\Actions\Approvals\RejectChange; use Simtabi\Laranail\Settings\Console\SyncDefinitionsCommand; use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; +use Simtabi\Laranail\Settings\Actions\Approvals\ApproveChange; +use Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange; +use Simtabi\Laranail\Settings\Actions\Categories\MoveCategory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; +use Simtabi\Laranail\Settings\Actions\Transfer\TransferActions; +use Simtabi\Laranail\Settings\Http\Middleware\IdempotentWrites; +use Simtabi\Laranail\Settings\Services\Transfer\StoreSnapshots; +use Simtabi\Laranail\Settings\Actions\Approvals\ApprovalActions; +use Simtabi\Laranail\Settings\Actions\Categories\CreateCategory; +use Simtabi\Laranail\Settings\Actions\Categories\DeleteCategory; +use Simtabi\Laranail\Settings\Actions\Categories\RenameCategory; use Simtabi\Laranail\Settings\Authentication\GuardActorResolver; use Simtabi\Laranail\Settings\Actions\Categories\CategoryActions; +use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; use Simtabi\Laranail\Settings\Authentication\SanctumActorResolver; use Simtabi\Laranail\Settings\Authorization\PermissionsAuthorizer; use Simtabi\Laranail\Settings\Verification\ActorTimestampVerifier; +use Simtabi\Laranail\Settings\Actions\Configuration\SaveDefinition; use Simtabi\Laranail\Package\Tools\Providers\PackageServiceProvider; use Simtabi\Laranail\Settings\Services\Tenancy\TenantDiscriminators; +use Simtabi\Laranail\Settings\Actions\Configuration\DeleteDefinition; use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; use Simtabi\Laranail\Settings\Database\Seeders\DefaultCategoriesSeeder; use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; use Simtabi\Laranail\Settings\Verification\PasswordConfirmationVerifier; +use Simtabi\Laranail\Settings\Actions\Configuration\ConfigurationActions; use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Actions\Configuration\SaveConfigurationEntry; use Illuminate\Contracts\Notifications\Dispatcher as NotificationDispatcher; use Simtabi\Laranail\Package\Tools\Support\Definitions\AutoSeederDefinition; +use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; +use Simtabi\Laranail\Settings\Actions\Configuration\DeleteConfigurationEntry; +use Simtabi\Laranail\Settings\Actions\Configuration\ListConfigurationEntries; /** * Registers laranail/settings with the host application. @@ -159,7 +212,7 @@ public function configurePackage(Package $package): void ->hasPackageSeeders(AutoSeederDefinition::make('laranail/settings:defaults') ->seeders([DefaultCategoriesSeeder::class]) ->options(['disable_foreign_key_checks' => false, 'fire_events' => true])) - ->hasCommands([PromoteCommand::class, PruneOrphansCommand::class, PruneAuditCommand::class, PruneHistoryCommand::class, HistoryCommand::class, MakeStoreCommand::class, DoctorCommand::class, SyncDefinitionsCommand::class, WarmCacheCommand::class, ClearCacheCommand::class]) + ->hasCommands([PromoteCommand::class, PruneOrphansCommand::class, PruneAuditCommand::class, PruneHistoryCommand::class, HistoryCommand::class, MakeStoreCommand::class, DoctorCommand::class, SyncDefinitionsCommand::class, WarmCacheCommand::class, ClearCacheCommand::class, PruneChangesCommand::class, ExportCommand::class, ImportCommand::class, DiffCommand::class, ReencryptCommand::class, RescopeCommand::class, OpenApiCommand::class]) ->hasInstallCommand(static function (InstallCommand $command): void { $command ->startWith(static function (InstallCommand $command): void { @@ -198,6 +251,11 @@ public function packageBooted(): void // event fires. Reading configuration here touches neither the database nor the cache. $config = $app->make(Repository::class); + // The REST API (§16.10): nothing is registered unless it is switched on. + if (filter_var($config->get('laranail.settings.http.enabled', false), FILTER_VALIDATE_BOOL)) { + $this->bootHttp($app, $config); + } + if ($config->get('laranail.settings.listeners.log', false) === true) { $events->listen(LogSettingsEvent::EVENTS, LogSettingsEvent::class); } @@ -300,6 +358,8 @@ static function (string $change) use ($app): void { $app->make(Dispatcher::class)->dispatch(new LayerSkipped($store, $layer, $reason)); }, cache: self::cacheEnabled($app) ? $app->make(SettingsCache::class) : null, + persisted: $app->make(PersistedConfiguration::class), + sources: self::configurationSources($app), )); $this->app->singleton(ValuePipeline::class); @@ -329,9 +389,16 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { $this->registerCache(); $this->registerListeners(); + $this->registerPersistedConfiguration(); + $this->registerApprovals(); + $this->registerTransfer(); + $this->registerHttp(); + $this->registerTyped(); + $this->app->scoped(SettingActions::class, static fn (Application $app): SettingActions => SettingActions::using( $app->make(SettingWriter::class), $app->make(AccessGuard::class), + $app->make(ApprovalActions::class)->propose, )); $this->app->scoped(StoreActions::class, static function (Application $app): StoreActions { @@ -346,9 +413,7 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { $access, $events, $app->make(Caches::class), - static fn (Store $store, Key $key): ?Definition => $app->make(RuntimeConfiguration::class)->findDefinition($store->name, $key) - ?? $app->make(DefinitionRegistry::class)->find($store->name, $key) - ?? $app->make(DatabaseDefinitions::class)->find($store, $key), + self::definitionLookup($app), ), $flush, new WarmCache($access), @@ -439,9 +504,50 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { auditQuery: $app->make(QueryAudit::class), databaseDefinitions: $app->make(DatabaseDefinitions::class), historyActions: $app->make(HistoryActions::class), + approvalActions: $app->make(ApprovalActions::class), + transferActions: $app->make(TransferActions::class), + configurationActions: $app->make(ConfigurationActions::class), + )); + + $this->app->bind(DiagnoseSettings::class, static fn (Application $app): DiagnoseSettings => new DiagnoseSettings( + $app->make(StoreRegistry::class), + $app->make(SchemaShapeRepository::class), + $app->make(ValueEncrypter::class), + static fn (): array => $app->make(PersistedConfiguration::class)->problems(), )); } + /** + * The definition a key resolves to, as a handle resolves it: runtime definitions first, then + * code and config, then the definitions table (D-6). + * + * @return Closure(Store, Key): ?Definition + */ + private static function definitionLookup(Application $app): Closure + { + return static fn (Store $store, Key $key): ?Definition => $app->make(RuntimeConfiguration::class)->findDefinition($store->name, $key) + ?? $app->make(DefinitionRegistry::class)->find($store->name, $key) + ?? $app->make(DatabaseDefinitions::class)->find($store, $key); + } + + /** + * `configuration.sources`: the merge order of `config`, `database` and `runtime` stores and + * layers, later wins. + * + * @return list + */ + private static function configurationSources(Application $app): array + { + $sources = $app->make(Repository::class)->get('laranail.settings.configuration.sources', ['config', 'database', 'runtime']); + $names = is_array($sources) ? array_values(array_filter($sources, is_string(...))) : null; + + if ($names === null || count($names) !== count($sources) || array_diff($names, ['config', 'database', 'runtime']) !== [] || count(array_unique($names)) !== count($names)) { + throw new InvalidConfiguration('laranail.settings.configuration.sources: a list of config, database and runtime, each at most once.'); + } + + return $names; + } + /** `cache.enabled`: on unless set to a false value. */ private static function cacheEnabled(Application $app): bool { @@ -589,6 +695,264 @@ private static function config(Application $app): ConfigValues return new ConfigValues($app->make(Repository::class)); } + /** + * Persisted configuration (§16.11): read lazily from the settings_stores table on the default + * store's database connection (as the configuration file names it), validated by building the + * stores it would produce, and bound `scoped`. + */ + private function registerPersistedConfiguration(): void + { + $this->app->scoped(PersistedConfiguration::class, static function (Application $app): PersistedConfiguration { + $stores = self::array($app, 'laranail.settings.stores'); + $layers = self::array($app, 'laranail.settings.layers'); + $default = self::string($app, 'laranail.settings.default', 'settings'); + $persisted = $app->make(Repository::class)->get('laranail.settings.configuration.persisted', false); + + return new PersistedConfiguration( + filter_var($persisted, FILTER_VALIDATE_BOOL), + static function () use ($app, $stores, $layers, $default): Connection { + $connection = null; + + foreach ((array) (is_array($stores[$default] ?? null) ? ($stores[$default]['layers'] ?? []) : []) as $layer) { + $config = is_string($layer) ? ($layers[$layer] ?? null) : null; + + if (is_array($config) && ($config['driver'] ?? null) === 'database') { + $connection = is_string($config['connection'] ?? null) ? $config['connection'] : null; + + break; + } + } + + $resolved = $app->make(ConnectionResolverInterface::class)->connection($connection); + + return $resolved instanceof Connection ? $resolved : throw new InvalidConfiguration('laranail.settings.configuration: the default store\'s database connection is not a database connection.'); + }, + static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), + static function (array $persistedStores, array $persistedLayers) use ($app, $stores, $layers, $default): void { + new StoreRegistry($app->make(DriverFactory::class), $default, array_replace($stores, $persistedStores), array_replace($layers, $persistedLayers))->validate(); + }, + $stores, + static function (string $problem) use ($app): void { + $app->make(OperationalLogger::class)->warning($problem); + }, + ); + }); + + $this->app->scoped(ConfigurationActions::class, static function (Application $app): ConfigurationActions { + $access = $app->make(AccessGuard::class); + $stores = $app->make(StoreRegistry::class); + $persisted = $app->make(PersistedConfiguration::class); + + return new ConfigurationActions( + new SaveConfigurationEntry($stores, $persisted, $access), + new DeleteConfigurationEntry($stores, $persisted, $access), + new ListConfigurationEntries($stores, $persisted, $access), + new SaveDefinition($app->make(DefinitionRegistry::class), $app->make(DatabaseDefinitions::class), $app->make(ValueEncoder::class), $access), + new DeleteDefinition($app->make(DatabaseDefinitions::class), $app->make(ValueEncoder::class), $access), + ); + }); + } + + /** Export, import and store diff (G-42), and the importers (G-43). */ + private function registerTransfer(): void + { + $this->app->singleton(StoreSnapshots::class, static fn (Application $app): StoreSnapshots => new StoreSnapshots( + $app->make(ValueEncrypter::class), + $app->make(ValueEncoder::class), + )); + + $this->app->scoped(TransferActions::class, static function (Application $app): TransferActions { + $access = $app->make(AccessGuard::class); + $snapshots = $app->make(StoreSnapshots::class); + $actions = $app->make(SettingActions::class); + + return new TransferActions( + new ExportStore($access, $snapshots), + new ImportStore( + $access, + $snapshots, + $app->make(ValuePipeline::class), + $app->make(ValueEncoder::class), + $actions->set, + $actions->lock, + $app->make(StoreActions::class)->categories->create, + self::definitionLookup($app), + ), + new DiffStore($access, $snapshots), + ); + }); + + $this->app->singleton(Importers::class, static fn (Application $app): Importers => new Importers( + self::array($app, 'laranail.settings.importers'), + static function (string $class) use ($app): object { + $importer = $app->make($class); + + return is_object($importer) ? $importer : throw new InvalidConfiguration(sprintf('laranail.settings.importers: [%s] did not build an object.', $class)); + }, + )); + } + + /** + * The REST API: its rate limiter, its routes under `http.prefix`/v1 and problem details for + * the errors its routes raise. Reads configuration only; touches neither database nor cache. + */ + private function bootHttp(Application $app, Repository $config): void + { + $perMinute = self::integer($app, 'laranail.settings.http.rate_limit', 60); + + RateLimiter::for('laranail-settings', static function (Request $request) use ($perMinute): Limit { + $user = $request->user()?->getAuthIdentifier(); + + return $perMinute > 0 + ? Limit::perMinute($perMinute)->by(is_scalar($user) ? 'user:' . $user : 'ip:' . $request->ip()) + : Limit::none(); + }); + + $middleware = $config->get('laranail.settings.http.middleware'); + $middleware = is_array($middleware) + ? array_values(array_filter($middleware, is_string(...))) + : ['api', class_exists('Laravel\\Sanctum\\Sanctum') ? 'auth:sanctum' : 'auth']; + + ApiRoutes::register( + $app->make(Router::class), + self::string($app, 'laranail.settings.http.prefix', 'api/settings'), + $middleware, + self::array($app, 'laranail.settings.http.routes'), + ); + + $handler = $app->make(ExceptionHandler::class); + + if (method_exists($handler, 'renderable')) { + $handler->renderable(static fn (Throwable $exception, Request $request): ?JsonResponse => Problems::render($exception, $request)); + } + } + + /** + * Typed settings (Phase 5): a typed settings class resolved from the container is loaded + * through the request's settings handle; classes listed in `typed.classes` register their + * definitions when the definition registry is first built; settings migrations get their + * migrator. Nothing is read at boot. + */ + private function registerTyped(): void + { + $this->app->scoped(MigrateSettings::class, static fn (Application $app): MigrateSettings => new MigrateSettings( + $app->make(StoreRegistry::class), + $app->make(SettingWriter::class), + $app->make(ValuePipeline::class), + $app->make(AccessGuard::class), + self::definitionLookup($app), + )); + + $app = $this->app; + SettingsMigration::resolveMigratorUsing(static fn (): SettingsMigrator => new SettingsMigrator( + $app->make(MigrateSettings::class), + new StoreName(self::string($app, 'laranail.settings.default', 'settings')), + Actor::system('settings migration'), + )); + + $this->app->afterResolving(DefinitionRegistry::class, static function (DefinitionRegistry $registry) use ($app): void { + foreach (self::strings($app, 'laranail.settings.typed.classes') as $class) { + if (! is_subclass_of($class, TypedSettings::class)) { + throw new InvalidConfiguration(sprintf('laranail.settings.typed.classes: [%s] is not a typed settings class.', $class)); + } + + $class::register($registry); + } + }); + + $this->app->beforeResolving(static function (mixed $abstract, array $parameters, Application $app): void { + if (is_string($abstract) && is_subclass_of($abstract, TypedSettings::class) && ! $app->bound($abstract)) { + $app->bind($abstract, static fn (Application $app): TypedSettings => $abstract::load($app->make(Settings::class))); + } + }); + } + + /** What the REST API's controllers are built from (bound always; cheap, and used only by routes). */ + private function registerHttp(): void + { + $this->app->scoped(SettingTargets::class, static fn (Application $app): SettingTargets => new SettingTargets( + $app->make(StoreRegistry::class), + self::definitionLookup($app), + )); + + $this->app->scoped(OwnerResolver::class, static function (Application $app): OwnerResolver { + $owners = self::array($app, 'laranail.settings.http.owners'); + + return new MorphMapOwnerResolver(static fn (string $alias): ?string => is_string($owners[$alias] ?? null) ? $owners[$alias] : Relation::getMorphedModel($alias)); + }); + + $this->app->bind(IdempotentWrites::class, static function (Application $app): IdempotentWrites { + $store = $app->make(Repository::class)->get('laranail.settings.http.idempotency.cache'); + $cache = $app->make(Caches::class)->store(is_string($store) && $store !== '' ? $store : null); + + return new IdempotentWrites( + $cache instanceof CacheRepository ? $cache : throw new InvalidConfiguration('laranail.settings.http.idempotency.cache: not a cache repository.'), + self::integer($app, 'laranail.settings.http.idempotency.ttl', 86400), + self::string($app, 'laranail.settings.cache.prefix', 'laranail-settings'), + ); + }); + + // Each action a controller takes is the instance the PHP API uses (§16.2). + $this->app->scoped(SetSetting::class, static fn (Application $app): SetSetting => $app->make(SettingActions::class)->set); + $this->app->scoped(ForgetSetting::class, static fn (Application $app): ForgetSetting => $app->make(SettingActions::class)->forget); + $this->app->scoped(LockSetting::class, static fn (Application $app): LockSetting => $app->make(SettingActions::class)->lock); + $this->app->scoped(UnlockSetting::class, static fn (Application $app): UnlockSetting => $app->make(SettingActions::class)->unlock); + $this->app->scoped(RollbackSetting::class, static fn (Application $app): RollbackSetting => $app->make(HistoryActions::class)->rollback); + $this->app->scoped(ProposeChange::class, static fn (Application $app): ProposeChange => $app->make(ApprovalActions::class)->propose); + $this->app->scoped(ApproveChange::class, static fn (Application $app): ApproveChange => $app->make(ApprovalActions::class)->approve); + $this->app->scoped(RejectChange::class, static fn (Application $app): RejectChange => $app->make(ApprovalActions::class)->reject); + $this->app->scoped(CancelChange::class, static fn (Application $app): CancelChange => $app->make(ApprovalActions::class)->cancel); + $this->app->scoped(QueryChanges::class, static fn (Application $app): QueryChanges => $app->make(ApprovalActions::class)->query); + $this->app->scoped(CreateCategory::class, static fn (Application $app): CreateCategory => $app->make(StoreActions::class)->categories->create); + $this->app->scoped(RenameCategory::class, static fn (Application $app): RenameCategory => $app->make(StoreActions::class)->categories->rename); + $this->app->scoped(MoveCategory::class, static fn (Application $app): MoveCategory => $app->make(StoreActions::class)->categories->move); + $this->app->scoped(DeleteCategory::class, static fn (Application $app): DeleteCategory => $app->make(StoreActions::class)->categories->delete); + $this->app->scoped(SaveConfigurationEntry::class, static fn (Application $app): SaveConfigurationEntry => $app->make(ConfigurationActions::class)->save); + $this->app->scoped(DeleteConfigurationEntry::class, static fn (Application $app): DeleteConfigurationEntry => $app->make(ConfigurationActions::class)->delete); + $this->app->scoped(ListConfigurationEntries::class, static fn (Application $app): ListConfigurationEntries => $app->make(ConfigurationActions::class)->list); + $this->app->scoped(SaveDefinition::class, static fn (Application $app): SaveDefinition => $app->make(ConfigurationActions::class)->saveDefinition); + $this->app->scoped(DeleteDefinition::class, static fn (Application $app): DeleteDefinition => $app->make(ConfigurationActions::class)->deleteDefinition); + $this->app->scoped(ExportStore::class, static fn (Application $app): ExportStore => $app->make(TransferActions::class)->export); + $this->app->scoped(ImportStore::class, static fn (Application $app): ImportStore => $app->make(TransferActions::class)->import); + $this->app->scoped(DiffStore::class, static fn (Application $app): DiffStore => $app->make(TransferActions::class)->diff); + } + + /** Four-eyes approvals (§16.7): the policy from `approvals.*`, and the actions over it. */ + private function registerApprovals(): void + { + $this->app->scoped(ApprovalPolicy::class, static function (Application $app): ApprovalPolicy { + $config = $app->make(Repository::class); + $days = static function (string $key, ?int $default) use ($config): ?int { + $value = $config->get('laranail.settings.approvals.' . $key, $default); + + return $value === null ? null : (is_numeric($value) ? (int) $value : throw new InvalidConfiguration(sprintf('laranail.settings.approvals.%s: a number of days, or null.', $key))); + }; + + return new ApprovalPolicy( + self::integer($app, 'laranail.settings.approvals.min_approvals', 1), + $config->get('laranail.settings.approvals.allow_self', false) === true, + $days('expire_after', 7), + $days('keep_days', 90), + ); + }); + + $this->app->scoped(ApprovalActions::class, static function (Application $app): ApprovalActions { + $access = $app->make(AccessGuard::class); + $events = $app->make(Dispatcher::class); + $policy = $app->make(ApprovalPolicy::class); + $definitions = self::definitionLookup($app); + + return new ApprovalActions( + new ProposeChange($access, $app->make(ValuePipeline::class), $events, $policy), + new ApproveChange($access, $app->make(SettingWriter::class), $app->make(ValuePipeline::class), $events, $definitions, $policy), + new RejectChange($access, $events, $definitions), + new CancelChange($access, $events), + new QueryChanges($app->make(StoreRegistry::class), $access), + new PruneChanges($app->make(StoreRegistry::class), $access, $policy), + ); + }); + } + /** * The settings cache (§7.5), built on first use, never at boot: the configured cache store * (null for the application's default), keyed per tenant, reporting cache failures to the diff --git a/src/Services/Configuration/PersistedConfiguration.php b/src/Services/Configuration/PersistedConfiguration.php new file mode 100644 index 0000000..19ab662 --- /dev/null +++ b/src/Services/Configuration/PersistedConfiguration.php @@ -0,0 +1,259 @@ +>, layers: array>}|null */ + private ?array $loaded = null; + + /** @var list */ + private array $problems = []; + + private int $generation = 0; + + /** + * @param Closure(): Connection $connection the default store's database connection + * @param Closure(): SchemaShape $shape the recorded schema shape + * @param Closure(array, array): void $validate builds stores and layers, raising InvalidConfiguration + * @param array $configStores `laranail.settings.stores`, which a persisted entry may not re-layer + * @param (Closure(string): void)|null $log told about each skipped entry + */ + public function __construct( + private readonly bool $enabled, + private readonly Closure $connection, + private readonly Closure $shape, + private readonly Closure $validate, + private readonly array $configStores = [], + private readonly ?Closure $log = null, + ) {} + + public function isEnabled(): bool + { + return $this->enabled && ($this->shape)()->storesTable; + } + + /** Changes whenever an entry is saved or deleted, so registries rebuild. */ + public function generation(): int + { + return $this->generation; + } + + /** @return array> valid persisted stores, by name */ + public function stores(): array + { + return $this->load()['stores']; + } + + /** @return array> valid persisted layers, by name */ + public function layers(): array + { + return $this->load()['layers']; + } + + /** @return list why entries were skipped on the last read (doctor) */ + public function problems(): array + { + $this->load(); + + return $this->problems; + } + + /** + * Save a store entry, as the configuration file would hold it. + * + * @param array $config + * + * @throws InvalidConfiguration + */ + public function saveStore(string $name, array $config): void + { + $this->save('store', $name, $config); + } + + /** + * Save a layer entry. + * + * @param array $config + * + * @throws InvalidConfiguration + */ + public function saveLayer(string $name, array $config): void + { + $this->save('layer', $name, $config); + } + + /** Remove a persisted entry; returns whether there was one. */ + public function delete(string $kind, string $name): bool + { + $this->assertEnabled(); + $deleted = $this->table()->where('kind', $kind)->where('name', $name)->delete() > 0; + $this->changed(); + + return $deleted; + } + + /** @param array $config */ + private function save(string $kind, string $name, array $config): void + { + $this->assertEnabled(); + + try { + new StoreName($name); + } catch (InvalidIdentifier $exception) { + throw new InvalidConfiguration(sprintf('Persisted %s [%s]: %s', $kind, $name, $exception->getMessage()), 0, $exception); + } + + $loaded = $this->load(); + $stores = $loaded['stores']; + $layers = $loaded['layers']; + $kind === 'store' ? $stores[$name] = $config : $layers[$name] = $config; + + $this->check($kind, $name, $config, $stores, $layers); + + $now = CarbonImmutable::now(); + $json = Json::encode($config, 'A persisted ' . $kind); + + if ($this->table()->where('kind', $kind)->where('name', $name)->exists()) { + $this->table()->where('kind', $kind)->where('name', $name)->update(['config' => $json, 'updated_at' => $now]); + } else { + $this->table()->insert(['id' => (string) Str::ulid(), 'kind' => $kind, 'name' => $name, 'config' => $json, 'created_at' => $now, 'updated_at' => $now]); + } + + $this->changed(); + } + + /** + * @return array{stores: array>, layers: array>} + */ + private function load(): array + { + if ($this->loaded !== null) { + return $this->loaded; + } + + $this->problems = []; + $accepted = ['stores' => [], 'layers' => []]; + + if (! $this->isEnabled()) { + return $this->loaded = $accepted; + } + + try { + $rows = $this->table()->orderBy('kind')->orderBy('name')->get(['kind', 'name', 'config'])->all(); + } catch (Exception $exception) { + $this->skip(sprintf('the persisted configuration table could not be read (%s)', $exception->getMessage())); + + return $this->loaded = $accepted; + } + + // Layers first: a store entry may use a persisted layer. + usort($rows, static fn (object $a, object $b): int => ((array) $a)['kind'] === 'layer' ? -1 : (((array) $b)['kind'] === 'layer' ? 1 : 0)); + + foreach ($rows as $row) { + $row = (array) $row; + $kind = is_string($row['kind'] ?? null) ? $row['kind'] : ''; + $name = is_string($row['name'] ?? null) ? $row['name'] : ''; + $config = is_string($row['config'] ?? null) ? json_decode($row['config'], true) : null; + + if (! in_array($kind, ['store', 'layer'], true) || ! is_array($config)) { + $this->skip(sprintf('%s [%s] is not a configuration entry', $kind, $name)); + + continue; + } + + $stores = $accepted['stores']; + $layers = $accepted['layers']; + $kind === 'store' ? $stores[$name] = $config : $layers[$name] = $config; + + try { + $this->check($kind, $name, $config, $stores, $layers); + } catch (SettingsException $exception) { + $this->skip(sprintf('%s [%s]: %s', $kind, $name, $exception->getMessage())); + + continue; + } + + $accepted = ['stores' => $stores, 'layers' => $layers]; + } + + return $this->loaded = $accepted; + } + + /** + * @param array $config + * @param array> $stores + * @param array> $layers + * + * @throws InvalidConfiguration + */ + private function check(string $kind, string $name, array $config, array $stores, array $layers): void + { + $configured = $this->configStores[$name] ?? null; + + if ($kind === 'store' && is_array($configured) && ($configured['layers'] ?? null) !== ($config['layers'] ?? null)) { + throw new InvalidConfiguration(sprintf('Persisted store [%s] would change the layers the configuration file gives it; change them there and promote the data.', $name)); + } + + ($this->validate)($stores, $layers); + } + + private function skip(string $problem): void + { + $this->problems[] = $problem; + + if ($this->log instanceof Closure) { + ($this->log)('laranail/settings skipped a persisted configuration entry: ' . $problem); + } + } + + private function changed(): void + { + $this->loaded = null; + $this->generation++; + } + + private function assertEnabled(): void + { + if (! $this->isEnabled()) { + throw new InvalidConfiguration('laranail.settings.configuration.persisted: persisted configuration is off (or its table was never migrated); turn it on and run the migration first.'); + } + } + + private function table(): Builder + { + try { + $connection = ($this->connection)(); + } catch (Exception $exception) { + throw new DriverFailure('The persisted configuration connection is unavailable.', 0, $exception); + } + + return $connection->table(($this->shape)()->names->stores()); + } +} diff --git a/src/Services/Database/AuditRepository.php b/src/Services/Database/AuditRepository.php index ea7dcdf..0cd9c5b 100644 --- a/src/Services/Database/AuditRepository.php +++ b/src/Services/Database/AuditRepository.php @@ -106,7 +106,7 @@ public function insert(AuditEntry $entry): void 'locale' => $entry->locale, 'version_from' => $entry->versionFrom, 'version_to' => $entry->versionTo, - 'change_request' => null, + 'change_request' => is_string($entry->meta['change_request'] ?? null) ? $entry->meta['change_request'] : null, 'actor_type' => $entry->actorType->value, 'actor_alias' => $entry->actorAlias, 'actor_id' => $entry->actorId, diff --git a/src/Services/Database/ChangeRequestRepository.php b/src/Services/Database/ChangeRequestRepository.php new file mode 100644 index 0000000..294015f --- /dev/null +++ b/src/Services/Database/ChangeRequestRepository.php @@ -0,0 +1,312 @@ +database(); + + if (! $database instanceof DatabaseDriver || ! $database->shape()->changeRequestsTable) { + throw new ApprovalUnavailable(sprintf('Store [%s] cannot hold change requests: it needs an active database layer and the change requests table (approvals.table).', $store->name)); + } + + return new self($database); + } + + /** + * One row as a request; a malformed row raises DriverFailure rather than inventing a request. + * + * @param array $row + */ + public static function request(array $row): ChangeRequest + { + $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; + $time = static fn (string $column): ?CarbonImmutable => $text($column) === null ? null : CarbonImmutable::parse($text($column)); + $id = $text('id'); + $operation = ChangeOperation::tryFrom($text('operation') ?? ''); + $status = ChangeStatus::tryFrom($text('status') ?? ''); + $requester = ActorType::tryFrom($text('requested_by_type') ?? ''); + $base = $row['base_version'] ?? null; + $store = $text('store'); + $scope = $text('scope'); + $key = $text('key'); + + if ($id === null || $store === null || $scope === null || $key === null || ! $operation instanceof ChangeOperation || ! $status instanceof ChangeStatus || ! $requester instanceof ActorType || ! is_numeric($base)) { + throw new DriverFailure(sprintf('Change request row [%s] is malformed.', $id ?? '?')); + } + + $approvals = $text('approvals') === null ? [] : json_decode($text('approvals'), true); + + return new ChangeRequest( + id: $id, + store: $store, + scope: $scope, + key: $key, + locale: $text('locale') ?? '', + operation: $operation, + payload: $text('payload'), + type: $text('type'), + encrypted: DatabaseValues::boolean($row['is_encrypted'] ?? false), + baseVersion: (int) $base, + status: $status, + requestedByType: $requester, + requestedByAlias: $text('requested_by_alias'), + requestedById: $text('requested_by_id'), + approvals: is_array($approvals) ? array_values(array_filter($approvals, is_string(...))) : [], + decidedByType: ActorType::tryFrom($text('decided_by_type') ?? ''), + decidedByAlias: $text('decided_by_alias'), + decidedById: $text('decided_by_id'), + decidedAt: $time('decided_at'), + reason: $text('reason'), + decisionReason: $text('decision_reason'), + expiresAt: $time('expires_at'), + createdAt: $time('created_at'), + ); + } + + /** The current tenant's request with this id in the store, or UnknownChangeRequest. */ + public function get(StoreName $store, string $id): ChangeRequest + { + return $this->find($store, $id) ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $store, $id)); + } + + public function database(): DatabaseDriver + { + return $this->database; + } + + /** + * Open a request and return it. + * + * @param array{store: string, scope: string, key: string, locale: string, operation: ChangeOperation, payload: ?string, type: ?string, encrypted: bool, base_version: int, reason: ?string, expires_at: ?CarbonImmutable} $request + */ + public function create(array $request, Actor $requester, CarbonImmutable $now): ChangeRequest + { + $id = (string) Str::ulid(); + $store = new StoreName($request['store']); + + $this->database->attempt($store, fn (): bool => $this->table()->insert([ + 'id' => $id, + 'store' => $request['store'], + 'scope' => $request['scope'], + 'key' => $request['key'], + 'locale' => $request['locale'], + 'operation' => $request['operation']->value, + 'payload' => $request['payload'], + 'type' => $request['type'], + 'is_encrypted' => $request['encrypted'], + 'base_version' => $request['base_version'], + 'status' => ChangeStatus::Pending->value, + 'requested_by_type' => $requester->type->value, + 'requested_by_alias' => $requester->alias, + 'requested_by_id' => $requester->id, + 'approvals' => null, + 'reason' => $request['reason'], + 'expires_at' => $request['expires_at'], + 'created_at' => $now, + 'updated_at' => $now, + ] + $this->database->tenantColumns())); + + return $this->find($store, $id) ?? throw new DriverFailure(sprintf('Change request [%s] was not stored.', $id)); + } + + /** The current tenant's request with this id, or null. */ + public function find(StoreName $store, string $id): ?ChangeRequest + { + $row = $this->database->attempt($store, fn (): ?object => $this->database->scoped($this->table())->where('id', $id)->first()); + + return $row === null ? null : self::request((array) $row); + } + + /** + * The current tenant's requests of a filter, newest first. + * + * @return list + */ + public function list(ChangeFilter $filter, int $limit = 100, ?string $after = null): array + { + return $this->database->attempt($filter->store, function () use ($filter, $limit, $after): array { + $query = $this->query($filter); + + if ($after !== null) { + $query->where('id', '<', $after); + } + + return array_values(array_map(static fn (object $row): ChangeRequest => self::request((array) $row), $query->limit($limit)->get()->all())); + }); + } + + /** + * Move a request from one of `$from` to a new status, recording who decided it; returns + * false when it was no longer in any of `$from` (somebody else decided it first). + * + * @param list $from + * @param list|null $approvals the approvals so far, when they change + */ + public function transition(ChangeRequest $request, array $from, ChangeStatus $to, ?Actor $decidedBy, ?string $reason, CarbonImmutable $now, ?array $approvals = null): bool + { + $columns = ['status' => $to->value, 'updated_at' => $now]; + + if ($approvals !== null) { + $columns['approvals'] = Json::encode($approvals, 'A change request\'s approvals'); + } + + if ($decidedBy instanceof Actor) { + $columns += [ + 'decided_by_type' => $decidedBy->type->value, + 'decided_by_alias' => $decidedBy->alias, + 'decided_by_id' => $decidedBy->id, + 'decided_at' => $now, + 'decision_reason' => $reason, + ]; + } + + $updated = $this->database->attempt(new StoreName($request->store), fn (): int => $this->database->scoped($this->table()) + ->where('id', $request->id) + ->whereIn('status', array_map(static fn (ChangeStatus $status): string => $status->value, $from)) + ->update($columns)); + + return $updated > 0; + } + + /** + * Rewrite every tenant's encrypted proposed payloads (re-encryption). `$rewrite` returns null + * when it cannot read a payload (counted as failed, left as it was). Returns [rewritten, failed]. + * + * @param Closure(string): ?string $rewrite + * + * @return array{int, int} + */ + public function rewriteEncrypted(StoreName $store, Closure $rewrite): array + { + return $this->database->attempt($store, function () use ($rewrite): array { + $rewritten = 0; + $failed = 0; + + $this->table()->where('is_encrypted', true)->whereNotNull('payload')->select(['id', 'payload'])->chunkById(500, function ($rows) use ($rewrite, &$rewritten, &$failed): void { + foreach ($rows as $row) { + $row = (array) $row; + $new = is_string($row['payload'] ?? null) ? $rewrite($row['payload']) : null; + + if ($new === null) { + $failed++; + + continue; + } + + $rewritten += $this->table()->where('id', $row['id'])->update(['payload' => $new]); + } + }); + + return [$rewritten, $failed]; + }); + } + + /** Rename an owner alias in every tenant's open and decided requests (rescope, G-30). */ + public function rescope(StoreName $store, string $from, string $to): int + { + return $this->database->attempt($store, function () use ($from, $to): int { + $changed = 0; + + foreach ($this->table()->where('scope', '>=', $from . ':')->where('scope', '<', $from . ';')->get(['id', 'scope']) as $row) { + $row = (array) $row; + $scope = is_string($row['scope'] ?? null) ? $row['scope'] : ''; + $changed += $this->table()->where('id', $row['id'])->update(['scope' => $to . substr($scope, strlen($from))]); + } + + return $changed; + }); + } + + /** + * Mark every tenant's open requests past their expiry as expired, and delete decided requests + * last touched before `$cutoff`. Returns [expired, deleted]. + * + * @return array{int, int} + */ + public function sweep(CarbonImmutable $now, ?CarbonImmutable $cutoff, StoreName $store): array + { + return $this->database->attempt($store, function () use ($now, $cutoff): array { + $expired = $this->table() + ->whereIn('status', [ChangeStatus::Pending->value, ChangeStatus::Approved->value]) + ->whereNotNull('expires_at') + ->where('expires_at', '<=', $now) + ->update(['status' => ChangeStatus::Expired->value, 'updated_at' => $now]); + + $deleted = $cutoff instanceof CarbonImmutable + ? $this->table() + ->whereNotIn('status', [ChangeStatus::Pending->value, ChangeStatus::Approved->value]) + ->where('updated_at', '<', $cutoff) + ->delete() + : 0; + + return [$expired, $deleted]; + }); + } + + /** How many of the current tenant's requests are open but past their expiry (doctor). */ + public function overdue(CarbonImmutable $now, StoreName $store): int + { + return $this->database->attempt($store, fn (): int => $this->database->scoped($this->table()) + ->whereIn('status', [ChangeStatus::Pending->value, ChangeStatus::Approved->value]) + ->whereNotNull('expires_at') + ->where('expires_at', '<=', $now) + ->count()); + } + + private function query(ChangeFilter $filter): Builder + { + $query = $this->database->scoped($this->table())->where('store', $filter->store->value); + + foreach (['id' => $filter->id, 'status' => $filter->status?->value, 'scope' => $filter->scope?->value, 'key' => $filter->key?->value] as $column => $value) { + if ($value !== null) { + $query->where($column, $value); + } + } + + return $query->orderByDesc('id'); + } + + private function table(): Builder + { + return $this->database->connection()->table($this->database->names()->changeRequests()); + } +} diff --git a/src/Services/Database/DefinitionsRepository.php b/src/Services/Database/DefinitionsRepository.php index e1ce6a2..c6ee1e6 100644 --- a/src/Services/Database/DefinitionsRepository.php +++ b/src/Services/Database/DefinitionsRepository.php @@ -5,6 +5,7 @@ namespace Simtabi\Laranail\Settings\Services\Database; use Carbon\CarbonImmutable; +use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Support\Json; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\Definition; @@ -12,6 +13,7 @@ use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Support\DatabaseValues; +use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; /** * The definitions table on one connection (D-6, §4.4): syncing code and config definitions in as @@ -94,6 +96,54 @@ public function sync(StoreName $store, array $definitions): array return ['synced' => $synced, 'removed' => $removed, 'conflicts' => $conflicts]; } + /** + * Save a definition edited through the API (§16.11) as a runtime row. A system row (synced + * from code or config) for the key refuses it: code is the source of truth for those. + * + * @throws InvalidDefinition + */ + public function save(StoreName $store, Definition $definition): void + { + $database = $this->database; + $table = static fn () => $database->connection()->table($database->names()->definitions())->where('store', $store->value); + $now = CarbonImmutable::now(); + + $database->attempt($store, function () use ($table, $store, $definition, $now): void { + $row = $table()->where('key', $definition->key->value)->first(['is_system']); + + if ($row !== null && DatabaseValues::boolean($row->is_system ?? false)) { + throw new InvalidDefinition(sprintf('Setting [%s] in store [%s] is defined in code or configuration; change it there.', $definition->key, $store)); + } + + $columns = $this->columns($store, $definition, new Translations($this->database->shape()->translations)) + ['updated_at' => $now]; + + if ($row === null) { + $table()->insert($columns + DatabaseDriver::newId($this->database->shape()->ids) + [ + 'store' => $store->value, + 'key' => $definition->key->value, + 'is_system' => false, + 'created_at' => $now, + ]); + + return; + } + + $table()->where('key', $definition->key->value)->update($columns); + }); + } + + /** Delete a runtime definition row; returns whether one was there. System rows are kept. */ + public function delete(StoreName $store, Key $key): bool + { + $database = $this->database; + + return $database->attempt($store, static fn (): int => $database->connection()->table($database->names()->definitions()) + ->where('store', $store->value) + ->where('key', $key->value) + ->where('is_system', false) + ->delete()) > 0; + } + /** @return array */ private function columns(StoreName $store, Definition $definition, Translations $translations): array { diff --git a/src/Services/Database/HistoryRepository.php b/src/Services/Database/HistoryRepository.php index a623f9a..ce1c760 100644 --- a/src/Services/Database/HistoryRepository.php +++ b/src/Services/Database/HistoryRepository.php @@ -4,6 +4,7 @@ namespace Simtabi\Laranail\Settings\Services\Database; +use Closure; use Carbon\CarbonImmutable; use Illuminate\Support\Str; use Illuminate\Database\Query\Builder; @@ -232,6 +233,74 @@ public function prune(?CarbonImmutable $cutoff, ?int $keepVersions, StoreName $s }); } + /** + * Rewrite every encrypted payload in the history, every tenant's (re-encryption): the old and + * the new value of each entry. `$rewrite` returns null when it cannot read a payload (counted + * as failed, left as it was). Returns [rewritten, failed]. + * + * @param Closure(string): ?string $rewrite + * + * @return array{int, int} + */ + public function rewriteEncrypted(StoreName $store, Closure $rewrite): array + { + return $this->database->attempt($store, function () use ($rewrite): array { + $rewritten = 0; + $failed = 0; + + $this->table() + ->where(static fn (Builder $query): Builder => $query->where('old_encrypted', true)->orWhere('new_encrypted', true)) + ->select(['id', 'old_value', 'new_value', 'old_encrypted', 'new_encrypted']) + ->chunkById(500, function ($rows) use ($rewrite, &$rewritten, &$failed): void { + foreach ($rows as $row) { + $row = (array) $row; + $columns = []; + + foreach (['old', 'new'] as $side) { + $payload = $row[$side . '_value'] ?? null; + + if (! DatabaseValues::boolean($row[$side . '_encrypted'] ?? false) || ! is_string($payload)) { + continue; + } + + $new = $rewrite($payload); + $new === null ? $failed++ : $columns[$side . '_value'] = $new; + } + + if ($columns !== []) { + $this->table()->where('id', $row['id'])->update($columns); + $rewritten++; + } + } + }); + + return [$rewritten, $failed]; + }); + } + + /** Rename an owner alias in every tenant's history (rescope, G-30); returns how many entries changed. */ + public function rescope(StoreName $store, string $from, string $to): int + { + return $this->database->attempt($store, function () use ($store, $from, $to): int { + $changed = 0; + + $this->table() + ->where('store', $store->value) + ->where('scope', '>=', $from . ':') + ->where('scope', '<', $from . ';') + ->select(['id', 'scope']) + ->chunkById(500, function ($rows) use ($from, $to, &$changed): void { + foreach ($rows as $row) { + $row = (array) $row; + $scope = is_string($row['scope'] ?? null) ? $row['scope'] : ''; + $changed += $this->table()->where('id', $row['id'])->update(['scope' => $to . substr($scope, strlen($from))]); + } + }); + + return $changed; + }); + } + private function identity(StoreName $store, Scope $scope, Key $key, Locale $locale): Builder { return $this->database->scoped($this->table()) diff --git a/src/Services/Definitions/DatabaseDefinitions.php b/src/Services/Definitions/DatabaseDefinitions.php index 5539feb..f63f18a 100644 --- a/src/Services/Definitions/DatabaseDefinitions.php +++ b/src/Services/Definitions/DatabaseDefinitions.php @@ -54,6 +54,24 @@ public static function localised(?string $stored, bool $json): ?string return new Translations($json ? TranslationsMode::Json : TranslationsMode::Lang)->nullableText($stored); } + /** Forget the store's loaded rows, so the next read sees a definition just saved or deleted. */ + public function forget(Store $store): void + { + unset($this->loaded[$store->name->value]); + } + + /** @return array every runtime definition of the store, by key */ + public function all(Store $store): array + { + $database = $store->database(); + + if (! $this->enabled || ! $database instanceof DatabaseDriver || ! $database->shape()->definitionsTable) { + return []; + } + + return $this->loaded[$store->name->value] ??= $this->load($store, $database); + } + public function find(Store $store, Key $key): ?Definition { if (! $this->enabled) { diff --git a/src/Services/Definitions/DefinitionRegistry.php b/src/Services/Definitions/DefinitionRegistry.php index 0c606e7..da95246 100644 --- a/src/Services/Definitions/DefinitionRegistry.php +++ b/src/Services/Definitions/DefinitionRegistry.php @@ -33,6 +33,12 @@ public function __construct( private readonly array $configured = [], ) {} + /** The store a definition without `inStore()` belongs to. */ + public function defaultStore(): StoreName + { + return $this->defaultStore; + } + public function define(string $key): DefinitionBuilder { return new DefinitionBuilder($this, new Key($key)); @@ -69,6 +75,26 @@ public function all(): array return array_values($this->definitions); } + /** + * Build, without registering, a definition from configuration-style attributes (`type`, + * `default`, `rules`, `encrypted`, …, as in `definitions.`): how a definition saved + * through the API (§16.11) is validated before it is stored. + * + * @param array $attributes + * + * @throws InvalidDefinition + */ + public function fromAttributes(string $key, array $attributes, StoreName $store): Definition + { + $definition = $this->fromConfig($key, ['store' => $store->value] + $attributes)->build($this->defaultStore); + + if ($definition->type !== null && ! $this->casters->has($definition->type)) { + throw new InvalidDefinition(sprintf('Setting [%s] uses unknown type [%s]; register a caster for it.', $definition->key, $definition->type)); + } + + return $definition; + } + private function loadConfigured(): void { if ($this->configLoaded) { diff --git a/src/Services/Resolution/SettingTargets.php b/src/Services/Resolution/SettingTargets.php new file mode 100644 index 0000000..1aca29a --- /dev/null +++ b/src/Services/Resolution/SettingTargets.php @@ -0,0 +1,72 @@ +stores->get(new StoreName($name)); + } + + /** @throws OwnerNotAllowed when the store does not accept the owner */ + public function target(SettingAddress $address, ?string $reason = null): SettingTarget + { + $store = $this->store($address->store); + $owner = $address->ownerRef(); + $key = new Key($address->key); + + if ($owner instanceof OwnerRef && ! $store->accepts($owner->alias)) { + throw new OwnerNotAllowed(sprintf('Store [%s] does not accept owner alias [%s].', $store->name, $owner->alias)); + } + + return new SettingTarget($store, $key, new Locale($address->locale), $owner, ($this->definitions)($store, $key), $reason); + } + + /** The settings handle reading this address's store, owner and locale as the actor. */ + public function handle(Settings $settings, SettingAddress $address, ?Actor $actor): Settings + { + $handle = $settings->store($address->store); + $handle = $address->owner === null ? $handle : $handle->for($address->owner); + $handle = $address->locale === '' ? $handle : $handle->locale($address->locale); + + return $actor instanceof Actor ? $handle->as($actor) : $handle; + } + + /** The version of the address's own row in the store's writable layer (0 when it has none). */ + public function version(SettingAddress $address): int + { + $store = $this->store($address->store); + $scope = Scope::of($address->ownerRef()); + + return $store->writableLayer()->driver->load($store->name, [$scope])->find($scope, new Key($address->key), new Locale($address->locale))->version ?? 0; + } +} diff --git a/src/Services/Stores/StoreRegistry.php b/src/Services/Stores/StoreRegistry.php index 81cadbe..59f3cb4 100644 --- a/src/Services/Stores/StoreRegistry.php +++ b/src/Services/Stores/StoreRegistry.php @@ -28,6 +28,7 @@ use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; +use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; /** * Builds and validates every store from configuration on first use. Configuration errors are @@ -38,13 +39,14 @@ final class StoreRegistry /** @var array|null */ private ?array $stores = null; - /** The runtime configuration generation the built stores reflect. */ - private int $builtGeneration = 0; + /** The runtime and persisted configuration generations the built stores reflect. */ + private string $builtGeneration = ''; /** * @param array $storeConfig `laranail.settings.stores` * @param array $layerConfig `laranail.settings.layers` * @param (Closure(string, string, string): void)|null $onLayerSkipped told (store, layer, reason) when bootstrap mode skips a layer + * @param list $sources `configuration.sources`: the merge order of config, database (persisted) and runtime entries, later wins */ public function __construct( private readonly DriverFactory $drivers, @@ -56,12 +58,14 @@ public function __construct( private readonly ?BootstrapEvidence $evidence = null, private readonly ?Closure $onLayerSkipped = null, private readonly ?SettingsCache $cache = null, + private readonly ?PersistedConfiguration $persisted = null, + private readonly array $sources = ['config', 'database', 'runtime'], ) {} /** A copy whose every layer is replaced by one driver (used by the fake). */ public function withEveryLayer(Driver $driver): self { - return new self($this->drivers, $this->default, $this->storeConfig, $this->layerConfig, $driver, $this->runtime, $this->evidence, $this->onLayerSkipped, $this->cache); + return new self($this->drivers, $this->default, $this->storeConfig, $this->layerConfig, $driver, $this->runtime, $this->evidence, $this->onLayerSkipped, $this->cache, $this->persisted, $this->sources); } /** @@ -108,7 +112,7 @@ public function forOwner(string $alias): Store /** @return array */ public function all(): array { - $generation = $this->runtime?->generation() ?? 0; + $generation = ($this->runtime?->generation() ?? 0) . ':' . ($this->persisted?->generation() ?? 0); if ($this->stores === null || $this->builtGeneration !== $generation) { $this->stores = $this->build(); @@ -177,6 +181,7 @@ private function build(): array table: $table, mode: $schema->mode, fallback: $schema->fallback, + approvalKeys: $this->approvalKeys($config['approvals'] ?? [], $path . '.approvals'), ); } @@ -248,16 +253,39 @@ private function layer(string $name, string $storePath, array $extra = []): Laye return new Layer($name, $this->override ?? $this->driverFactory()->make($layer), $this->override instanceof Driver ? DriverType::Array : DriverType::tryFrom($driver)); } - /** @return array config stores, with runtime additions over them */ + /** @return array config, persisted and runtime stores, merged in `configuration.sources` order */ private function storeConfigs(): array { - return array_replace($this->storeConfig, $this->runtime?->stores() ?? []); + return $this->merged($this->storeConfig, fn (): array => $this->persisted?->stores() ?? [], $this->runtime?->stores() ?? []); } - /** @return array config layers, with runtime additions over them */ + /** @return array config, persisted and runtime layers, merged in `configuration.sources` order */ private function layerConfigs(): array { - return array_replace($this->layerConfig, $this->runtime?->layers() ?? []); + return $this->merged($this->layerConfig, fn (): array => $this->persisted?->layers() ?? [], $this->runtime?->layers() ?? []); + } + + /** + * @param array $config + * @param Closure(): array $persisted read only when `database` is a source + * @param array $runtime + * + * @return array + */ + private function merged(array $config, Closure $persisted, array $runtime): array + { + $merged = []; + + foreach ($this->sources as $source) { + $merged = array_replace($merged, match ($source) { + 'config' => $config, + 'database' => $persisted(), + 'runtime' => $runtime, + default => throw new InvalidConfiguration(sprintf('laranail.settings.configuration.sources: [%s] is not config, database or runtime.', $source)), + }); + } + + return $merged; } private function driverFactory(): DriverFactory @@ -274,6 +302,24 @@ private function locksOverridable(mixed $locks, string $path): bool return ($locks['overridable'] ?? false) === true; } + /** @return list */ + private function approvalKeys(mixed $approvals, string $path): array + { + if (! is_array($approvals)) { + throw new InvalidConfiguration($path . ': an array is required.'); + } + + $globs = $this->strings($approvals['keys'] ?? [], $path . '.keys'); + + foreach ($globs as $glob) { + if (preg_match('/^[a-z0-9_.*?\[\]]+$/', $glob) !== 1) { + throw new InvalidConfiguration(sprintf('%s.keys: [%s] is not a key glob (a-z, 0-9, _, ., *, ?).', $path, $glob)); + } + } + + return $globs; + } + /** @return list */ private function strings(mixed $value, string $path): array { diff --git a/src/Services/Transfer/Importers.php b/src/Services/Transfer/Importers.php new file mode 100644 index 0000000..494a97a --- /dev/null +++ b/src/Services/Transfer/Importers.php @@ -0,0 +1,45 @@ +` can use (`importers`, name => class), built on first use. + * A name that is not configured, or a class that is not an {@see Importer}, raises + * InvalidConfiguration naming the config path. + */ +final readonly class Importers +{ + /** + * @param array $classes `laranail.settings.importers` + * @param Closure(class-string): object $make builds a class with its dependencies + */ + public function __construct( + private array $classes, + private Closure $make, + ) {} + + /** @return list */ + public function names(): array + { + return array_values(array_map(strval(...), array_keys($this->classes))); + } + + public function get(string $name): Importer + { + $class = $this->classes[$name] ?? null; + + if (! is_string($class) || ! class_exists($class) || ! is_subclass_of($class, Importer::class)) { + throw new InvalidConfiguration(sprintf('laranail.settings.importers.%s: [%s] is not a class implementing %s (known importers: %s).', $name, is_string($class) ? $class : 'missing', Importer::class, implode(', ', $this->names()))); + } + + $importer = ($this->make)($class); + + return $importer instanceof Importer ? $importer : throw new InvalidConfiguration(sprintf('laranail.settings.importers.%s: [%s] did not build an importer.', $name, $class)); + } +} diff --git a/src/Services/Transfer/StoreSnapshots.php b/src/Services/Transfer/StoreSnapshots.php new file mode 100644 index 0000000..9c8665f --- /dev/null +++ b/src/Services/Transfer/StoreSnapshots.php @@ -0,0 +1,128 @@ +ciphertext !== null || $b->ciphertext !== null) { + return $a->ciphertext === $b->ciphertext && $a->locked === $b->locked; + } + + return $a->hasValue === $b->hasValue + && json_encode($a->value, JSON_PRESERVE_ZERO_FRACTION) === json_encode($b->value, JSON_PRESERVE_ZERO_FRACTION) + && $a->locked === $b->locked; + } + + /** @throws StoreNotWritable when the store has no active database layer */ + public function export(Store $store, ExportMode $mode): ExportDocument + { + $database = $store->requireDatabase('; exports read the database layer.'); + $records = $database->load($store->name, array_values(array_filter(array_map(Scope::fromString(...), $database->scopes($store->name))))); + + $settings = []; + + foreach ($records->all() as $record) { + $settings[] = $this->setting($record, $mode); + } + + usort($settings, static fn (ExportedSetting $a, ExportedSetting $b): int => strcmp($a->identity(), $b->identity())); + + return new ExportDocument( + $store->name->value, + array_map(ExportedCategory::of(...), CategoryRepository::of($store)->all()), + $settings, + $mode, + CarbonImmutable::now()->toIso8601String(), + ); + } + + /** + * Compare the store with a document. Encrypted values are compared by ciphertext only when + * both sides hold one (it changes with every encryption, so "changed" may be a re-encryption); + * a redacted side cannot be compared. + */ + public function diff(Store $store, ExportDocument $document): StoreDiff + { + $current = $this->export($store, $document->mode === ExportMode::Plaintext ? ExportMode::Plaintext : ExportMode::Ciphertext)->settingsByIdentity(); + $incoming = $document->settingsByIdentity(); + $diff = ['added' => [], 'removed' => [], 'changed' => [], 'unchanged' => [], 'unknown' => []]; + + foreach ($incoming as $identity => $setting) { + $existing = $current[$identity] ?? null; + + $bucket = match (true) { + ! $existing instanceof ExportedSetting => 'added', + $setting->redacted => 'unknown', + default => self::same($existing, $setting) ? 'unchanged' : 'changed', + }; + $diff[$bucket][] = $identity; + } + + foreach (array_keys($current) as $identity) { + if (! isset($incoming[$identity])) { + $diff['removed'][] = $identity; + } + } + + return new StoreDiff(...$diff); + } + + private function setting(Record $record, ExportMode $mode): ExportedSetting + { + $make = static fn (mixed $value = null, ?string $ciphertext = null, bool $redacted = false, bool $hasValue = true): ExportedSetting => new ExportedSetting( + $record->scope, + $record->key, + $record->locale, + $value, + $ciphertext, + $redacted, + $record->type, + $record->encrypted, + $record->locked, + $hasValue, + ); + + if ($record->payload === null) { + return $make(hasValue: false); + } + + if (! $record->encrypted) { + return $make($this->encoder->decode($record->key, $record->payload)); + } + + return match ($mode) { + ExportMode::Redacted => $make(redacted: true), + ExportMode::Ciphertext => $make(ciphertext: $record->payload), + ExportMode::Plaintext => $make($this->encoder->decode($record->key, $this->encrypter->decrypt($record->payload))), + }; + } +} diff --git a/src/SettingsManager.php b/src/SettingsManager.php index bc16c53..647e169 100644 --- a/src/SettingsManager.php +++ b/src/SettingsManager.php @@ -20,6 +20,7 @@ use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Audit\AuditQuery; use Simtabi\Laranail\Settings\Data\HistoryDiff; +use Simtabi\Laranail\Settings\Enums\ExportMode; use Simtabi\Laranail\Settings\Actions\WarmCache; use Simtabi\Laranail\Settings\Data\HistoryEntry; use Simtabi\Laranail\Settings\Data\SettingWrite; @@ -27,26 +28,39 @@ use Simtabi\Laranail\Settings\Actions\QueryAudit; use Simtabi\Laranail\Settings\Contracts\Settable; use Simtabi\Laranail\Settings\Contracts\Settings; +use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Data\HistoryFilter; use Simtabi\Laranail\Settings\Data\SettingTarget; +use Simtabi\Laranail\Settings\Approvals\Approvals; +use Simtabi\Laranail\Settings\Data\ChangeProposal; use Simtabi\Laranail\Settings\Actions\StoreActions; use Simtabi\Laranail\Settings\Data\PromotionReport; use Simtabi\Laranail\Settings\History\HistoryQuery; use Simtabi\Laranail\Settings\Data\PromotionRequest; +use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Actions\HistoryActions; use Simtabi\Laranail\Settings\Actions\SettingActions; use Simtabi\Laranail\Settings\Resolution\Explanation; +use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff; use Simtabi\Laranail\Settings\Exceptions\TypeMismatch; use Simtabi\Laranail\Settings\Exceptions\ActorRequired; use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; use Simtabi\Laranail\Settings\Categories\CategoryManager; +use Simtabi\Laranail\Settings\Data\Transfer\ImportReport; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; +use Simtabi\Laranail\Settings\Data\Transfer\ExportRequest; +use Simtabi\Laranail\Settings\Data\Transfer\ImportRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Services\Resolution\Resolver; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Actions\Transfer\TransferActions; +use Simtabi\Laranail\Settings\Actions\Approvals\ApprovalActions; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; +use Simtabi\Laranail\Settings\Actions\Configuration\ConfigurationActions; +use Simtabi\Laranail\Settings\Configuration\PersistedConfigurationEditor; use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** @@ -84,6 +98,9 @@ public function __construct( private ?QueryAudit $auditQuery = null, private ?DatabaseDefinitions $databaseDefinitions = null, private ?HistoryActions $historyActions = null, + private ?ApprovalActions $approvalActions = null, + private ?TransferActions $transferActions = null, + private ?ConfigurationActions $configurationActions = null, ) { $this->access = $access ?? AccessGuard::closed(); $this->actions = $actions ?? SettingActions::using($writer, $this->access); @@ -363,6 +380,55 @@ public function historyDiff(string $key, int $from, int $to): HistoryDiff return $this->historyActions()->diff->handle($this->writeTarget($key), $from, $to, $this->actingAs); } + public function propose(string $key, mixed $value): ChangeRequest + { + return $this->approvalActions()->propose->handle(new ChangeProposal($this->writeTarget($key), ChangeOperation::Set, $value), $this->actingAs); + } + + public function approvals(): Approvals + { + return new Approvals($this->approvalActions(), $this->targetStore(), $this->actingAs); + } + + public function export(ExportMode $mode = ExportMode::Redacted): ExportDocument + { + return $this->transferActions()->export->handle(new ExportRequest($this->targetStore(), $mode), $this->actingAs); + } + + public function import(ExportDocument $document): ImportReport + { + return $this->transferActions()->import->handle(new ImportRequest($this->targetStore(), $document, apply: true, reason: $this->reason ?? $this->actingAs?->context->reason), $this->actingAs); + } + + public function previewImport(ExportDocument $document): ImportReport + { + return $this->transferActions()->import->handle(new ImportRequest($this->targetStore(), $document), $this->actingAs); + } + + public function compare(ExportDocument $document): StoreDiff + { + return $this->transferActions()->diff->handle($this->targetStore(), $document, $this->actingAs); + } + + public function persistedConfiguration(): PersistedConfigurationEditor + { + return new PersistedConfigurationEditor( + $this->configurationActions ?? throw new LogicException('This settings handle was built without the configuration actions; resolve Settings from the container.'), + $this->targetStore(), + $this->actingAs, + ); + } + + private function transferActions(): TransferActions + { + return $this->transferActions ?? throw new LogicException('This settings handle was built without the transfer actions; resolve Settings from the container.'); + } + + private function approvalActions(): ApprovalActions + { + return $this->approvalActions ?? throw new LogicException('This settings handle was built without the approval actions; resolve Settings from the container.'); + } + private function historyActions(): HistoryActions { return $this->historyActions ?? throw new LogicException('This settings handle was built without the history actions; resolve Settings from the container.'); @@ -500,6 +566,9 @@ private function with( $this->auditQuery, $this->databaseDefinitions, $this->historyActions, + $this->approvalActions, + $this->transferActions, + $this->configurationActions, ); } } diff --git a/src/Stores/Store.php b/src/Stores/Store.php index 617b5de..9de059f 100644 --- a/src/Stores/Store.php +++ b/src/Stores/Store.php @@ -5,6 +5,7 @@ namespace Simtabi\Laranail\Settings\Stores; use Closure; +use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Data\StoreName; @@ -27,6 +28,7 @@ /** * @param list $layers * @param list $owners + * @param list $approvalKeys key globs whose writes become change requests (`approvals.keys`) */ public function __construct( public StoreName $name, @@ -39,8 +41,21 @@ public function __construct( public ?string $table = null, public StoreMode $mode = StoreMode::Polymorphic, public ?StoreName $fallback = null, + public array $approvalKeys = [], ) {} + /** Whether `approvals.keys` makes a write of this key a change request (§16.7). */ + public function requiresApproval(Key $key): bool + { + return array_any($this->approvalKeys, static fn (string $glob): bool => fnmatch($glob, $key->value, FNM_NOESCAPE)); + } + + /** Whether this store can hold change requests: its database layer is active and has the table. */ + public function acceptsChangeRequests(): bool + { + return $this->database()?->shape()->changeRequestsTable ?? false; + } + public function isDedicated(): bool { return $this->mode === StoreMode::Dedicated; diff --git a/src/Testing/SettingsFake.php b/src/Testing/SettingsFake.php index 4559706..9dc729a 100644 --- a/src/Testing/SettingsFake.php +++ b/src/Testing/SettingsFake.php @@ -14,15 +14,22 @@ use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Audit\AuditQuery; use Simtabi\Laranail\Settings\Data\HistoryDiff; +use Simtabi\Laranail\Settings\Enums\ExportMode; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Contracts\Settable; use Simtabi\Laranail\Settings\Contracts\Settings; +use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Approvals\Approvals; use Simtabi\Laranail\Settings\Data\PromotionReport; use Simtabi\Laranail\Settings\History\HistoryQuery; use Simtabi\Laranail\Settings\Data\PromotionRequest; use Simtabi\Laranail\Settings\Resolution\Explanation; +use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff; use Simtabi\Laranail\Settings\Categories\CategoryManager; +use Simtabi\Laranail\Settings\Data\Transfer\ImportReport; +use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; +use Simtabi\Laranail\Settings\Configuration\PersistedConfigurationEditor; use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** @@ -209,6 +216,41 @@ public function historyDiff(string $key, int $from, int $to): HistoryDiff return $this->inner->historyDiff($key, $from, $to); } + public function propose(string $key, mixed $value): ChangeRequest + { + return $this->inner->propose($key, $value); + } + + public function approvals(): Approvals + { + return $this->inner->approvals(); + } + + public function export(ExportMode $mode = ExportMode::Redacted): ExportDocument + { + return $this->inner->export($mode); + } + + public function import(ExportDocument $document): ImportReport + { + return $this->inner->import($document); + } + + public function previewImport(ExportDocument $document): ImportReport + { + return $this->inner->previewImport($document); + } + + public function compare(ExportDocument $document): StoreDiff + { + return $this->inner->compare($document); + } + + public function persistedConfiguration(): PersistedConfigurationEditor + { + return $this->inner->persistedConfiguration(); + } + public function assertSaved(string $key, mixed ...$value): void { $checksValue = $value !== []; diff --git a/src/Typed/Attributes/Encrypted.php b/src/Typed/Attributes/Encrypted.php new file mode 100644 index 0000000..8f9edad --- /dev/null +++ b/src/Typed/Attributes/Encrypted.php @@ -0,0 +1,13 @@ +settings()->rename('mail.from', 'mail.from_address'); + * } + * + * public function down(): void + * { + * $this->settings()->rename('mail.from_address', 'mail.from'); + * } + * }; + * + * A migration is built with `new`, so nothing can be injected: the service provider hands this + * class the migrator through {@see resolveMigratorUsing()}, as it hands the models their context. + */ +abstract class SettingsMigration extends Migration +{ + /** @var (Closure(): SettingsMigrator)|null */ + private static ?Closure $migrator = null; + + /** @param Closure(): SettingsMigrator $migrator */ + public static function resolveMigratorUsing(Closure $migrator): void + { + self::$migrator = $migrator; + } + + protected function settings(): SettingsMigrator + { + return (self::$migrator ?? throw new LogicException('Settings migrations need laranail/settings\' service provider to be registered.'))(); + } +} diff --git a/src/Typed/SettingsMigrator.php b/src/Typed/SettingsMigrator.php new file mode 100644 index 0000000..acd82a9 --- /dev/null +++ b/src/Typed/SettingsMigrator.php @@ -0,0 +1,55 @@ +store($store); + + return $this->migrate->handle(new SettingsMigrationStep(SettingsMigrationStep::RENAME, $name, new Key($from), $name, new Key($to)), $this->actor); + } + + /** Move a key from one store to another (optionally under a new key). */ + public function move(string $key, string $fromStore, string $toStore, ?string $toKey = null): int + { + return $this->migrate->handle(new SettingsMigrationStep(SettingsMigrationStep::RENAME, new StoreName($fromStore), new Key($key), new StoreName($toStore), new Key($toKey ?? $key)), $this->actor); + } + + /** Remove a key everywhere: every owner and locale. */ + public function delete(string $key, ?string $store = null): int + { + return $this->migrate->handle(new SettingsMigrationStep(SettingsMigrationStep::DELETE, $this->store($store), new Key($key)), $this->actor); + } + + /** Store a global value, unless the key already has one. */ + public function add(string $key, mixed $value, ?string $store = null): int + { + return $this->migrate->handle(new SettingsMigrationStep(SettingsMigrationStep::ADD, $this->store($store), new Key($key), value: $value), $this->actor); + } + + private function store(?string $store): StoreName + { + return $store === null ? $this->defaultStore : new StoreName($store); + } +} diff --git a/src/Typed/TypedProperty.php b/src/Typed/TypedProperty.php new file mode 100644 index 0000000..b8781ed --- /dev/null +++ b/src/Typed/TypedProperty.php @@ -0,0 +1,114 @@ +getType(); + + if (! $type instanceof ReflectionNamedType) { + throw new InvalidDefinition(sprintf('%s::$%s needs a single declared type (union types cannot be mapped to a setting).', $property->getDeclaringClass()->getName(), $property->getName())); + } + + $name = $type->getName(); + + if (! in_array($name, ['string', 'int', 'float', 'bool', 'array'], true) && ! is_subclass_of($name, BackedEnum::class) && ! in_array($name, [DateTimeImmutable::class, CarbonImmutable::class, DateTimeInterface::class], true)) { + throw new InvalidDefinition(sprintf('%s::$%s has type [%s]; use string, int, float, bool, array, a backed enum or DateTimeImmutable.', $property->getDeclaringClass()->getName(), $property->getName(), $name)); + } + + $key = ($property->getAttributes(Key::class)[0] ?? null)?->newInstance()->key + ?? ltrim(($group === null ? '' : $group . '.') . strtolower((string) preg_replace('/(?getName())), '.'); + + return new self( + $property, + $key, + $name, + $type->allowsNull(), + $property->getAttributes(Encrypted::class) !== [], + ($property->getAttributes(Type::class)[0] ?? null)?->newInstance()->alias, + ); + } + + /** The caster alias a definition of this property takes. */ + public function casterAlias(): ?string + { + return $this->alias ?? match ($this->type) { + 'string', 'int', 'float', 'bool', 'array' => $this->type, + DateTimeImmutable::class, CarbonImmutable::class, DateTimeInterface::class => null, + default => null, + }; + } + + /** A property value as it is stored: an enum's backing value, a date as ISO 8601. */ + public function toStored(mixed $value): mixed + { + return match (true) { + $value instanceof BackedEnum => $value->value, + $value instanceof DateTimeInterface => CarbonImmutable::instance($value)->toIso8601String(), + default => $value, + }; + } + + /** + * A stored value as the property holds it. + * + * @throws TypeMismatch when it cannot be one + */ + public function fromStored(mixed $value): mixed + { + if ($value === null) { + return $this->nullable ? null : throw $this->mismatch($value); + } + + $type = $this->type; + + return match (true) { + $type === 'string' => is_string($value) ? $value : throw $this->mismatch($value), + $type === 'int' => is_int($value) || (is_string($value) && preg_match('/^-?\d+$/', $value) === 1) ? (int) $value : throw $this->mismatch($value), + $type === 'float' => is_int($value) || is_float($value) || is_numeric($value) ? (float) $value : throw $this->mismatch($value), + $type === 'bool' => is_bool($value) ? $value : throw $this->mismatch($value), + $type === 'array' => is_array($value) ? $value : throw $this->mismatch($value), + is_subclass_of($type, BackedEnum::class) => (is_int($value) || is_string($value) ? $type::tryFrom($value) : null) ?? throw $this->mismatch($value), + $value instanceof DateTimeInterface => CarbonImmutable::instance($value), + is_string($value) => $type === DateTimeImmutable::class ? new DateTimeImmutable($value) : CarbonImmutable::parse($value), + default => throw $this->mismatch($value), + }; + } + + private function mismatch(mixed $value): TypeMismatch + { + return new TypeMismatch(sprintf('Setting [%s] holds %s, which %s::$%s (%s%s) cannot take.', $this->key, get_debug_type($value), $this->property->getDeclaringClass()->getShortName(), $this->property->getName(), $this->nullable ? '?' : '', $this->type)); + } +} diff --git a/src/Typed/TypedSettings.php b/src/Typed/TypedSettings.php new file mode 100644 index 0000000..611ad70 --- /dev/null +++ b/src/Typed/TypedSettings.php @@ -0,0 +1,187 @@ +as($user)); + * $mail->fromAddress = 'ops@example.com'; + * $mail->save(); + * + * A property keeps its declared default until a value is stored for its key. `save()` writes only + * the properties that changed since `load()`. `register()` turns the properties into definitions + * (type, default, encryption), so the key-value API reads them the same way. + */ +abstract class TypedSettings +{ + private ?Settings $handle = null; + + /** @var array stored form of each property as loaded */ + private array $loaded = []; + + final public function __construct() {} + + /** + * Read every property's key through the handle (scoped to the class's store, when it names + * one); a key with no value keeps the property's default. + * + * @throws TypeMismatch when a stored value cannot be the property's type + */ + public static function load(Settings $settings): static + { + $instance = new static; + $handle = self::scoped($settings); + $instance->handle = $handle; + + foreach (static::properties() as $name => $property) { + $lookup = $handle->lookup($property->key); + + if ($lookup->isFound()) { + $property->property->setValue($instance, $property->fromStored($lookup->value())); + } + + if ($property->property->isInitialized($instance)) { + $instance->loaded[$name] = $property->toStored($property->property->getValue($instance)); + } + } + + return $instance; + } + + /** + * Register a definition for every property: its key, the caster alias its type implies (or + * `#[Type]`), its declared default and `#[Encrypted]`, in the class's store. A key already + * defined in code or configuration is left as it is. + * + * @return list + */ + public static function register(DefinitionRegistry $registry): array + { + $definitions = []; + $defaults = new ReflectionClass(static::class)->getDefaultProperties(); + $store = self::attribute(Store::class)?->name; + + foreach (static::properties() as $name => $property) { + if ($registry->find($store === null ? $registry->defaultStore() : new StoreName($store), new Key($property->key)) instanceof Definition) { + continue; + } + + $builder = $registry->define($property->key); + + if ($store !== null) { + $builder->inStore($store); + } + + if ($property->casterAlias() !== null) { + $builder->ofType((string) $property->casterAlias()); + } + + if (array_key_exists($name, $defaults) && $property->property->hasDefaultValue() && ($defaults[$name] !== null || $property->nullable)) { + $builder->withDefault($property->toStored($defaults[$name])); + } + + if ($property->encrypted) { + $builder->encrypted(); + } + + $definitions[] = $builder->register(); + } + + return $definitions; + } + + /** + * Every mapped property, by name: the public, non-static properties the class declares. + * + * @return array + * + * @throws InvalidDefinition + */ + public static function properties(): array + { + $group = self::attribute(Group::class)?->prefix; + $properties = []; + + foreach (new ReflectionClass(static::class)->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { + if (! $property->isStatic() && $property->getDeclaringClass()->getName() !== self::class) { + $properties[$property->getName()] = TypedProperty::of($property, $group); + } + } + + return $properties; + } + + /** + * Write every property that changed since `load()` through the handle it was loaded with; given + * a handle, write every property through that one instead (copying settings to an owner). + */ + public function save(?Settings $settings = null): void + { + $given = $settings instanceof Settings; + $handle = $given ? self::scoped($settings) : ($this->handle ?? throw new TypeMismatch(static::class . ' was not loaded; pass a settings handle to save().')); + + foreach (static::properties() as $name => $property) { + if (! $property->property->isInitialized($this)) { + continue; + } + + $stored = $property->toStored($property->property->getValue($this)); + + if (! $given && array_key_exists($name, $this->loaded) && $this->loaded[$name] === $stored) { + continue; + } + + $handle->set($property->key, $stored); + $this->loaded[$name] = $stored; + } + + $this->handle = $handle; + } + + /** The handle narrowed to the class's store, when it names one. */ + private static function scoped(Settings $settings): Settings + { + $store = self::attribute(Store::class)?->name; + + return $store === null ? $settings : $settings->store($store); + } + + /** + * @template T of object + * + * @param class-string $attribute + * + * @return ?T + */ + private static function attribute(string $attribute): ?object + { + $found = new ReflectionClass(static::class)->getAttributes($attribute)[0] ?? null; + + return $found?->newInstance(); + } +} diff --git a/tests/Arch/ArchitectureTest.php b/tests/Arch/ArchitectureTest.php index 5e8a27e..879b616 100644 --- a/tests/Arch/ArchitectureTest.php +++ b/tests/Arch/ArchitectureTest.php @@ -6,8 +6,10 @@ use Illuminate\Support\Facades\Blade; use Simtabi\Laranail\Settings\Actions\SetSetting; use Simtabi\Laranail\Settings\Actions\LockSetting; +use Simtabi\Laranail\Settings\Typed\TypedSettings; use Simtabi\Laranail\Settings\Actions\ForgetSetting; use Simtabi\Laranail\Settings\Actions\UnlockSetting; +use Simtabi\Laranail\Settings\Typed\SettingsMigration; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; use Simtabi\Laranail\Settings\Exceptions\SettingsException; @@ -26,6 +28,9 @@ // Bases callers catch; their subtypes are final. SettingsException::class, InvalidIdentifier::class, + // Bases applications extend: a typed settings class, a settings migration. + TypedSettings::class, + SettingsMigration::class, ]); arch('nothing outside Providers and Facades reaches into the container') @@ -74,7 +79,7 @@ } // A scan that inspects nothing has broken, not found a clean tree. - expect($inspected)->toBeGreaterThanOrEqual(240) + expect($inspected)->toBeGreaterThanOrEqual(360) ->and($offending)->toBe([]) ->and(is_dir($root . '/resources/views'))->toBeFalse(); }); diff --git a/tests/Arch/LayeringTest.php b/tests/Arch/LayeringTest.php index 677be7b..384197b 100644 --- a/tests/Arch/LayeringTest.php +++ b/tests/Arch/LayeringTest.php @@ -41,14 +41,17 @@ function classOf(string $path): string /** Actions with more than handle() public, and why. */ const ACTION_EXEMPTIONS = [ - 'Actions\\WriteGuard' => 'run(): the guard every write action runs through; not an intent of its own', - 'Actions\\Categories\\CategoryGuard' => 'run(): the guard every category action runs through', - 'Actions\\SettingActions' => 'a bundle of the write actions for entry points (using())', - 'Actions\\StoreActions' => 'a bundle of the store actions for entry points', - 'Actions\\HistoryActions' => 'a bundle of the history actions for entry points', - 'Actions\\Categories\\CategoryActions' => 'a bundle of the category actions for entry points (using())', - 'Actions\\QueryAudit' => 'get(), cursor(), paginate(): one authorized read in three result shapes, part of the public API', - 'Actions\\PruneOrphans' => 'find(): deprecated in 0.1, forwards to FindOrphans, removed in 1.0', + 'Actions\\WriteGuard' => 'run(): the guard every write action runs through; not an intent of its own', + 'Actions\\Categories\\CategoryGuard' => 'run(): the guard every category action runs through', + 'Actions\\SettingActions' => 'a bundle of the write actions for entry points (using())', + 'Actions\\StoreActions' => 'a bundle of the store actions for entry points', + 'Actions\\HistoryActions' => 'a bundle of the history actions for entry points', + 'Actions\\Approvals\\ApprovalActions' => 'a bundle of the approval actions for entry points', + 'Actions\\Transfer\\TransferActions' => 'a bundle of the export, import and diff actions for entry points', + 'Actions\\Configuration\\ConfigurationActions' => 'a bundle of the persisted configuration actions for entry points', + 'Actions\\Categories\\CategoryActions' => 'a bundle of the category actions for entry points (using())', + 'Actions\\QueryAudit' => 'get(), cursor(), paginate(): one authorized read in three result shapes, part of the public API', + 'Actions\\PruneOrphans' => 'find(): deprecated in 0.1, forwards to FindOrphans, removed in 1.0', ]; it('gives every action handle() as its only public method', function (): void { @@ -68,7 +71,7 @@ function classOf(string $path): string } } - expect(count($files))->toBeGreaterThanOrEqual(30) + expect(count($files))->toBeGreaterThanOrEqual(55) ->and(array_keys(array_diff_key($offenders, ACTION_EXEMPTIONS)))->toBe([]) // An exemption that no longer needs to be one is stale. ->and(array_keys(array_diff_key(ACTION_EXEMPTIONS, $offenders)))->toBe([]); @@ -78,12 +81,12 @@ function classOf(string $path): string $files = sourceFiles('Actions'); $offenders = array_keys(array_filter($files, static fn (string $code): bool => preg_match('/->connection\(\)|getSchemaBuilder\(|DB::/', $code) === 1)); - expect(count($files))->toBeGreaterThanOrEqual(30) + expect(count($files))->toBeGreaterThanOrEqual(55) ->and($offenders)->toBe([]); }); it('lets only entry points depend on actions', function (): void { - $entryPoints = ['SettingsManager.php', 'Providers/', 'Facades/', 'Console/', 'Categories/CategoryManager.php', 'Audit/AuditQuery.php', 'History/HistoryQuery.php']; + $entryPoints = ['SettingsManager.php', 'Providers/', 'Facades/', 'Console/', 'Categories/CategoryManager.php', 'Audit/AuditQuery.php', 'History/HistoryQuery.php', 'Approvals/Approvals.php', 'Configuration/PersistedConfigurationEditor.php', 'Http/', 'Enums/Capability.php', 'Typed/SettingsMigrator.php']; $files = sourceFiles(''); $offenders = []; @@ -97,7 +100,7 @@ function classOf(string $path): string } } - expect(count($files))->toBeGreaterThanOrEqual(240) + expect(count($files))->toBeGreaterThanOrEqual(360) ->and($offenders)->toBe([]); }); diff --git a/tests/Arch/RestApiTest.php b/tests/Arch/RestApiTest.php new file mode 100644 index 0000000..5ff33f7 --- /dev/null +++ b/tests/Arch/RestApiTest.php @@ -0,0 +1,89 @@ + "Controller::method" => method, for every public controller method */ +function controllerMethods(): array +{ + $methods = []; + + foreach (glob(dirname(__DIR__, 2) . '/src/Http/Controllers/*.php') ?: [] as $file) { + $class = new ReflectionClass('Simtabi\\Laranail\\Settings\\Http\\Controllers\\' . basename($file, '.php')); + + foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + if ($method->getName() !== '__construct' && $method->getDeclaringClass()->getName() === $class->getName()) { + $methods[$class->getShortName() . '::' . $method->getName()] = $method; + } + } + } + + return $methods; +} + +/** @return list the Actions\* classes a controller method calls through its constructor properties */ +function delegatedActions(ReflectionMethod $method): array +{ + $lines = file((string) $method->getFileName()) ?: []; + $body = implode('', array_slice($lines, (int) $method->getStartLine() - 1, (int) $method->getEndLine() - (int) $method->getStartLine() + 1)); + $actions = []; + + foreach ($method->getDeclaringClass()->getConstructor()?->getParameters() ?? [] as $parameter) { + $type = $parameter->getType(); + $class = $type instanceof ReflectionNamedType ? $type->getName() : ''; + + if (str_starts_with($class, 'Simtabi\\Laranail\\Settings\\Actions\\') && preg_match('/\$this->' . $parameter->getName() . '->(handle|paginate|get|cursor)\(/', $body) === 1) { + $actions[] = $class; + } + } + + return $actions; +} + +it('makes every controller method delegate to an action', function (): void { + $methods = controllerMethods(); + $idle = array_keys(array_filter($methods, static fn (ReflectionMethod $method): bool => delegatedActions($method) === [])); + + expect(count($methods))->toBeGreaterThanOrEqual(30) + ->and($idle)->toBe([]); +}); + +it('holds the routes, the capabilities and the controllers to each other', function (): void { + $routes = ApiRoutes::definitions(); + $methods = controllerMethods(); + $routed = array_values(array_unique(array_map(static fn (array $route): string => $route['capability']->value, $routes))); + $mismatched = []; + + foreach ($routes as $route) { + $method = $methods[new ReflectionClass($route['controller'])->getShortName() . '::' . $route['action']] ?? null; + + if (! $method instanceof ReflectionMethod || array_intersect($route['capability']->actions(), delegatedActions($method)) === []) { + $mismatched[] = $route['name']; + } + } + + sort($routed); + $cases = array_map(static fn (Capability $capability): string => $capability->value, Capability::cases()); + sort($cases); + + expect(count($routes))->toBeGreaterThanOrEqual(39) + ->and($routed)->toBe($cases) + ->and($mismatched)->toBe([]) + // Every controller method is routed: nothing reachable only by accident. + ->and(array_diff(array_keys($methods), array_map(static fn (array $route): string => new ReflectionClass($route['controller'])->getShortName() . '::' . $route['action'], $routes)))->toBe([]); +}); + +it('names every route with the vendor-scoped prefix and a capability', function (): void { + foreach (ApiRoutes::definitions() as $route) { + expect($route['name'])->toStartWith('laranail-settings.api.') + ->and(Capability::tryFrom((string) preg_replace('/^laranail-settings\.api\.(owners\.)?/', '', $route['name'])))->toBe($route['capability']); + } +}); diff --git a/tests/Arch/ServicesTest.php b/tests/Arch/ServicesTest.php index 93f1efa..e03c939 100644 --- a/tests/Arch/ServicesTest.php +++ b/tests/Arch/ServicesTest.php @@ -6,6 +6,7 @@ use Illuminate\Contracts\Filesystem\Factory; use Simtabi\Laranail\Settings\Contracts\Caster; use Simtabi\Laranail\Settings\Contracts\Driver; +use Simtabi\Laranail\Settings\Contracts\Importer; use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Contracts\AuditSink; use Simtabi\Laranail\Settings\Contracts\Authorizer; @@ -13,6 +14,7 @@ use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\ReadOnlyValues; use Simtabi\Laranail\Settings\Contracts\ActorResolver; +use Simtabi\Laranail\Settings\Contracts\OwnerResolver; use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; use Simtabi\Laranail\Settings\Contracts\ValueValidator; @@ -33,6 +35,7 @@ const PLUGIN_CONTRACTS = [ Driver::class, AuditSink::class, Authorizer::class, Caster::class, Verifier::class, ActorResolver::class, TenantDiscriminator::class, ReadinessProbe::class, ValueEncrypter::class, ValueValidator::class, BootstrapEvidence::class, + Importer::class, OwnerResolver::class, ]; /** The 19 classes moved into Services\ in 0.1: old name => new name. */ @@ -89,7 +92,7 @@ function servicesSources(): array } } - expect(count($services))->toBeGreaterThanOrEqual(20) + expect(count($services))->toBeGreaterThanOrEqual(25) ->and($offenders)->toBe([]); }); @@ -107,8 +110,8 @@ function servicesSources(): array )); // The positive control: the scan does find the repositories and registries that exist. - expect(count($files))->toBeGreaterThanOrEqual(240) - ->and(count($found))->toBeGreaterThanOrEqual(8) + expect(count($files))->toBeGreaterThanOrEqual(360) + ->and(count($found))->toBeGreaterThanOrEqual(9) ->and($offenders)->toBe([]); }); diff --git a/tests/Feature/Database/ApprovalsTest.php b/tests/Feature/Database/ApprovalsTest.php new file mode 100644 index 0000000..5aaa28a --- /dev/null +++ b/tests/Feature/Database/ApprovalsTest.php @@ -0,0 +1,253 @@ + ['user']]); + allowGates(Ability::Update, Ability::Forget, Ability::Lock, Ability::Unlock, Ability::Approve, Ability::View); +}); + +function needsApproval(string $key = 'mail.host'): void +{ + app(DefinitionRegistry::class)->define($key)->requiresApproval()->register(); +} + +it('turns a write to a setting that needs approval into a pending change request', function (): void { + Event::fake([ChangeRequested::class]); + needsApproval(); + $audit = auditInMemory(); + + settings()->as(user(1))->because('INC-1')->set('mail.host', 'smtp.acme.test'); + + $requests = settings()->approvals()->pending()->get(); + + expect(settings()->get('mail.host'))->toBeNull() + ->and($requests)->toHaveCount(1) + ->and($requests[0]->operation)->toBe(ChangeOperation::Set) + ->and($requests[0]->status)->toBe(ChangeStatus::Pending) + ->and($requests[0]->reason)->toBe('INC-1') + ->and($requests[0]->requestedById)->toBe('1') + ->and($requests[0]->baseVersion)->toBe(0) + ->and($requests[0]->expiresAt?->diffInDays(now()->toImmutable(), true))->toBeGreaterThan(6.9) + ->and($requests[0]->toArray())->not->toHaveKey('payload') + ->and(collect($audit->entries())->contains(fn ($entry): bool => $entry->action === AuditAction::Propose && $entry->outcome === AuditOutcome::Pending && $entry->meta['change_request'] === $requests[0]->id))->toBeTrue() + ->and(DB::table('settings_audit')->where('change_request', $requests[0]->id)->count())->toBe(1); + + Event::assertDispatched(ChangeRequested::class, fn (ChangeRequested $event): bool => $event->key === 'mail.host'); +}); + +it('matches store approval globs as well as definitions', function (): void { + useDatabase(['stores.settings.approvals' => ['keys' => ['billing.*']]]); + + settings()->set('billing.plan', 'pro'); + settings()->set('site.name', 'Acme'); + + expect(settings()->get('billing.plan'))->toBeNull() + ->and(settings()->get('site.name'))->toBe('Acme') + ->and(settings()->approvals()->get())->toHaveCount(1); +}); + +it('applies an approved request through the write pipeline and records who approved it', function (): void { + Event::fake([ChangeApproved::class, ChangeApplied::class]); + needsApproval(); + settings()->as(user(1))->set('mail.host', 'smtp.acme.test'); + $request = settings()->approvals()->get()[0]; + + $approved = settings()->as(user(2))->approvals()->approve($request->id, 'looks right'); + + expect($approved->status)->toBe(ChangeStatus::Applied) + ->and($approved->approvals)->toBe(['user:' . user(2)->getMorphClass() . ':2']) + ->and($approved->decidedById)->toBe('2') + ->and($approved->decisionReason)->toBe('looks right') + ->and(settings()->get('mail.host'))->toBe('smtp.acme.test') + ->and(settings()->history()->key('mail.host')->get()[0]->causerId)->toBe('2'); + + Event::assertDispatched(ChangeApplied::class, fn (ChangeApplied $event): bool => $event->version === 1); + expect(fn (): ChangeRequest => settings()->approvals()->approve($request->id))->toThrow(ChangeRequestClosed::class, 'applied'); +}); + +it('refuses self-approval unless allowed', function (): void { + needsApproval(); + settings()->as(user(1))->set('mail.host', 'smtp.acme.test'); + $id = settings()->approvals()->get()[0]->id; + + expect(fn (): ChangeRequest => settings()->as(user(1))->approvals()->approve($id))->toThrow(AccessDenied::class, 'own change request') + ->and(DB::table('settings_audit')->where('outcome', 'denied')->where('change_request', $id)->count())->toBe(1); + + config()->set('laranail.settings.approvals.allow_self', true); + app()->forgetScopedInstances(); + + expect(settings()->as(user(1))->approvals()->approve($id)->status)->toBe(ChangeStatus::Applied); +}); + +it('waits for the minimum number of distinct approvals', function (): void { + config()->set('laranail.settings.approvals.min_approvals', 2); + app()->forgetScopedInstances(); + needsApproval(); + settings()->as(user(1))->set('mail.host', 'smtp.acme.test'); + $id = settings()->approvals()->get()[0]->id; + + $first = settings()->as(user(2))->approvals()->approve($id); + $again = settings()->as(user(2))->approvals()->approve($id); + + expect($first->status)->toBe(ChangeStatus::Approved) + ->and($again->approvals)->toHaveCount(1) + ->and(settings()->get('mail.host'))->toBeNull() + ->and(settings()->as(user(3))->approvals()->approve($id)->status)->toBe(ChangeStatus::Applied) + ->and(settings()->get('mail.host'))->toBe('smtp.acme.test'); +}); + +it('marks a request stale when its setting changed after it was opened, and never overwrites', function (): void { + Event::fake([ChangeStale::class]); + useDatabase(['stores.settings.approvals' => ['keys' => ['mail.*']]]); + settings()->propose('mail.host', 'first.test'); + $id = settings()->approvals()->get()[0]->id; + // Somebody writes the key directly (a key the globs no longer cover). + config()->set('laranail.settings.stores.settings.approvals.keys', []); + app()->forgetScopedInstances(); + settings()->set('mail.host', 'direct.test'); + + $result = settings()->approvals()->approve($id); + + expect($result->status)->toBe(ChangeStatus::Stale) + ->and(settings()->get('mail.host'))->toBe('direct.test'); + Event::assertDispatched(ChangeStale::class); +}); + +it('rejects and cancels without writing', function (): void { + Event::fake([ChangeRejected::class, ChangeCancelled::class]); + needsApproval(); + settings()->as(user(1))->set('mail.host', 'a.test'); + settings()->as(user(1))->set('mail.host', 'b.test'); + [$second, $first] = settings()->approvals()->get(); + + $rejected = settings()->as(user(2))->approvals()->reject($first->id, 'no'); + + expect(fn (): ChangeRequest => settings()->as(user(2))->approvals()->cancel($second->id))->toThrow(AccessDenied::class, 'only the requester'); + + $cancelled = settings()->as(user(1))->approvals()->cancel($second->id); + + expect($rejected->status)->toBe(ChangeStatus::Rejected) + ->and($rejected->decisionReason)->toBe('no') + ->and($cancelled->status)->toBe(ChangeStatus::Cancelled) + ->and(settings()->get('mail.host'))->toBeNull() + ->and(fn (): ChangeRequest => settings()->approvals()->reject($first->id))->toThrow(ChangeRequestClosed::class); + Event::assertDispatched(ChangeRejected::class); + Event::assertDispatched(ChangeCancelled::class); +}); + +it('proposes forget, lock and unlock as well as values', function (): void { + settings()->for(new OwnerRef('user', 5))->set('mail.host', 'a.test'); + needsApproval(); + $owner = settings()->as(user(1))->for(new OwnerRef('user', 5)); + + $owner->lock('mail.host'); + $lock = settings()->approvals()->for(new OwnerRef('user', 5))->get()[0]; + settings()->as(user(2))->approvals()->approve($lock->id); + + $owner->forget('mail.host'); + $forget = settings()->approvals()->key('mail.host')->pending()->get()[0]; + + expect($lock->operation)->toBe(ChangeOperation::Lock) + ->and($lock->baseVersion)->toBe(1) + ->and(DB::table('settings')->where('scope', 'user:5')->value('is_locked'))->toBeTruthy() + ->and($forget->operation)->toBe(ChangeOperation::Forget); +}); + +it('keeps the proposed value of an encrypted setting encrypted at rest', function (): void { + $secret = TestCredentials::secret(); + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->requiresApproval()->register(); + + settings()->as(user(1))->set('mail.password', $secret); + $row = DB::table('settings_change_requests')->first(); + + expect($row->payload)->not->toContain($secret) + ->and((bool) $row->is_encrypted)->toBeTrue(); + + settings()->as(user(2))->approvals()->approve($row->id); + + expect(settings()->get('mail.password'))->toBe($secret); +}); + +it('lets an actor without approve see only their own requests', function (): void { + needsApproval(); + settings()->as(user(1))->set('mail.host', 'a.test'); + settings()->as(user(2))->set('mail.host', 'b.test'); + Gate::define(Ability::Approve->gateName(), static fn ($user): bool => $user->getAuthIdentifier() === 3); + + $mine = settings()->as(user(1))->approvals()->get(); + + expect($mine)->toHaveCount(1) + ->and($mine[0]->requestedById)->toBe('1') + ->and(settings()->as(user(3))->approvals()->get())->toHaveCount(2) + ->and(settings()->as(user(1))->approvals()->find($mine[0]->id)->id)->toBe($mine[0]->id) + ->and(fn (): ChangeRequest => settings()->approvals()->find('01ARZ3NDEKTSV4RRFFQ69G5FAV'))->toThrow(UnknownChangeRequest::class); +}); + +it('expires overdue requests and prunes decided ones', function (): void { + needsApproval(); + settings()->as(user(1))->set('mail.host', 'a.test'); + settings()->as(user(1))->set('mail.host', 'b.test'); + [$late, $early] = settings()->approvals()->get(); + settings()->as(user(2))->approvals()->reject($late->id); + + $this->travel(8)->days(); + + expect(fn (): ChangeRequest => settings()->as(user(2))->approvals()->approve($early->id))->toThrow(ChangeRequestClosed::class, 'expired'); + + $this->travel(100)->days(); + $exit = Artisan::call('laranail::settings.prune-changes'); + + expect($exit)->toBe(0) + ->and(Artisan::output())->toContain('deleted 2') + ->and(DB::table('settings_change_requests')->count())->toBe(0); +}); + +it('refuses approval where a store cannot hold change requests', function (): void { + useDatabase(['approvals.table' => false]); + needsApproval(); + + expect(Schema::hasTable('settings_change_requests'))->toBeFalse() + ->and(fn () => settings()->set('mail.host', 'a.test'))->toThrow(ApprovalUnavailable::class, 'cannot hold change requests') + ->and(fn (): ChangeRequest => settings()->propose('mail.host', 'a.test'))->toThrow(ApprovalUnavailable::class); +}); + +it('never lists a payload, so a change request is safe to render', function (): void { + needsApproval(); + settings()->set('mail.host', 'a.test'); + $request = settings()->approvals()->get()[0]; + + expect($request)->toBeInstanceOf(ChangeRequest::class) + ->and(json_encode($request->toArray()))->not->toContain('a.test'); +}); diff --git a/tests/Feature/Database/MaintenanceTest.php b/tests/Feature/Database/MaintenanceTest.php new file mode 100644 index 0000000..d73c8e2 --- /dev/null +++ b/tests/Feature/Database/MaintenanceTest.php @@ -0,0 +1,133 @@ + ['user', 'member']]); + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); +}); + +/** Switch APP_KEY, keeping the old one readable only when asked. */ +function rotateKey(bool $keepPrevious): void +{ + $old = config('app.key'); + config()->set('app.key', 'base64:' . base64_encode(random_bytes(32))); + config()->set('app.previous_keys', $keepPrevious ? [$old] : []); + + foreach (['encrypter', ValueEncrypter::class, ValuePipeline::class] as $abstract) { + app()->forgetInstance($abstract); + } + + app()->forgetScopedInstances(); +} + +it('re-encrypts values, history and change requests under the new key', function (): void { + $secret = TestCredentials::secret(); + settings()->set('mail.password', $secret); + settings()->set('mail.password', $secret . 'x'); + app(DefinitionRegistry::class)->define('mail.token')->encrypted()->requiresApproval()->register(); + settings()->set('mail.token', $secret); + $before = DB::table('settings')->where('key', 'mail.password')->value('value'); + + rotateKey(keepPrevious: true); + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + + $exit = Artisan::call('laranail::settings.reencrypt'); + + expect($exit)->toBe(0) + ->and(Artisan::output())->toContain('Re-encrypted 1 value(s), 2 history entries and 1 change request(s)') + ->and(DB::table('settings')->where('key', 'mail.password')->value('value'))->not->toBe($before) + ->and(DB::table('settings_audit')->where('action', AuditAction::Reencrypt->value)->value('outcome'))->toBe('allowed'); + + // The old key can go now: everything reads under the new one alone. + config()->set('app.previous_keys', []); + app()->forgetInstance('encrypter'); + app()->forgetInstance(ValueEncrypter::class); + app()->forgetInstance(ValuePipeline::class); + app()->forgetScopedInstances(); + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + + expect(settings()->get('mail.password'))->toBe($secret . 'x') + ->and(settings()->historyDiff('mail.password', 1, 2)->from)->toBe($secret); +}); + +it('leaves a value no key can read as it was, and says so', function (): void { + settings()->set('mail.password', TestCredentials::secret()); + $before = DB::table('settings')->where('key', 'mail.password')->value('value'); + + rotateKey(keepPrevious: false); + + expect(Artisan::call('laranail::settings.reencrypt'))->toBe(1) + ->and(Artisan::output())->toContain('could not be decrypted') + ->and(DB::table('settings')->where('key', 'mail.password')->value('value'))->toBe($before) + ->and(Artisan::call('laranail::settings.doctor', ['--json' => true]))->toBe(1) + ->and(Artisan::output())->toContain('cannot be decrypted'); +}); + +it('needs manage_stores to re-encrypt or rescope', function (): void { + expect(fn () => app(ReencryptSettings::class)->handle(Actor::user(user())))->toThrow(AccessDenied::class, 'manage_stores') + ->and(fn () => app(RescopeOwners::class)->handle('user', 'member', Actor::user(user())))->toThrow(AccessDenied::class, 'manage_stores'); +}); + +it('renames an owner alias in values, history and change requests, and doctor stops flagging it', function (): void { + useDatabase(['stores.settings.owners' => ['user', 'member'], 'identity.mode' => 'slug_per_row']); + settings()->for(new OwnerRef('user', 4))->set('theme', 'dark'); + settings()->for(new OwnerRef('user', 4))->propose('theme', 'light'); + DB::table('settings')->insert(['scope' => 'App\\Models\\Legacy:9', 'settable_type' => 'App\\Models\\Legacy', 'settable_id' => '9', 'key' => 'theme', 'group' => 'theme', 'locale' => '', 'value' => '"blue"', 'slug' => sha1('legacy'), 'created_at' => now(), 'updated_at' => now()]); + + expect(Artisan::call('laranail::settings.rescope', ['from' => 'user', 'to' => 'member']))->toBe(0) + ->and(Artisan::output())->toContain('in 1 value(s), 1 history entry and 1 change request(s)') + ->and(settings()->for(new OwnerRef('member', 4))->get('theme'))->toBe('dark') + ->and(DB::table('settings')->where('scope', 'member:4')->value('settable_type'))->toBe('member') + ->and(DB::table('settings')->where('scope', 'member:4')->value('slug'))->toBe(sha1('member:4|theme|')) + ->and(DB::table('settings_history')->where('scope', 'member:4')->count())->toBe(1) + ->and(DB::table('settings_change_requests')->where('scope', 'member:4')->count())->toBe(1); + + // A class name from before the alias allow-list (G-6) is renamed the same way. + app(RescopeOwners::class)->handle('App\\Models\\Legacy', 'member'); + Artisan::call('laranail::settings.doctor', ['--json' => true]); + + expect(settings()->for(new OwnerRef('member', 9))->get('theme'))->toBe('blue') + ->and(Artisan::output())->toContain('Every scope uses a listed alias.') + ->and(fn () => app(RescopeOwners::class)->handle('member', 'member'))->toThrow(InvalidIdentifier::class, 'already') + ->and(fn () => app(RescopeOwners::class)->handle('a:b', 'member'))->toThrow(InvalidIdentifier::class) + ->and(Artisan::call('laranail::settings.rescope', ['from' => 'user', 'to' => 'Bad Alias']))->toBe(1); +}); + +it('reports overdue change requests and schema drift on the governance tables', function (): void { + app(DefinitionRegistry::class)->define('mail.host')->requiresApproval()->register(); + settings()->set('mail.host', 'a.test'); + $this->travel(8)->days(); + + Artisan::call('laranail::settings.doctor', ['--json' => true]); + $report = Artisan::output(); + + DB::connection()->getSchemaBuilder()->table('settings_change_requests', static function ($table): void { + $table->dropColumn('decision_reason'); + }); + Artisan::call('laranail::settings.doctor', ['--json' => true]); + + expect($report)->toContain('past their expiry') + ->and($report)->toContain('No schema drift.') + ->and(Artisan::output())->toContain('settings_change_requests.decision_reason'); +}); diff --git a/tests/Feature/Database/PersistedConfigurationTest.php b/tests/Feature/Database/PersistedConfigurationTest.php new file mode 100644 index 0000000..b6e43cc --- /dev/null +++ b/tests/Feature/Database/PersistedConfigurationTest.php @@ -0,0 +1,124 @@ + true, 'definitions.table' => true]); +}); + +it('creates the persisted configuration table only when the switch is on', function (): void { + expect(Schema::hasTable('settings_stores'))->toBeTrue(); + + useDatabase(['configuration.persisted' => false]); + + expect(Schema::hasTable('settings_stores'))->toBeFalse() + ->and(fn () => settings()->persistedConfiguration()->saveStore('extra', ['layers' => ['runtime']]))->toThrow(InvalidConfiguration::class, 'persisted configuration is off'); +}); + +it('saves a store and a layer that settings then use, and audits it', function (): void { + $editor = settings()->persistedConfiguration(); + $editor->saveLayer('scratch', ['driver' => 'array']); + $editor->saveStore('extra', ['layers' => ['scratch'], 'owners' => ['team']]); + + settings()->store('extra')->set('feature.on', true); + + expect(settings()->store('extra')->get('feature.on'))->toBeTrue() + ->and(array_map(static fn (ConfigurationEntry $entry): string => $entry->kind . ':' . $entry->name, $editor->entries()))->toBe(['layer:scratch', 'store:extra']) + ->and(DB::table('settings_audit')->where('action', AuditAction::ManageStores->value)->count())->toBe(2) + ->and($editor->deleteStore('extra'))->toBeTrue() + ->and($editor->deleteStore('extra'))->toBeFalse() + ->and(fn (): mixed => settings()->store('extra')->get('feature.on'))->toThrow(UnknownStore::class); +}); + +it('validates an entry before saving it, and refuses re-layering a configured store', function (): void { + $editor = settings()->persistedConfiguration(); + + expect(fn () => $editor->saveStore('extra', ['layers' => ['nope']]))->toThrow(InvalidConfiguration::class, 'layer [nope] is not defined') + ->and(fn () => $editor->saveStore('settings', ['layers' => ['runtime']]))->toThrow(InvalidConfiguration::class, 'change them there') + ->and(fn () => $editor->saveStore('Bad Name', ['layers' => ['runtime']]))->toThrow(InvalidConfiguration::class) + ->and(DB::table('settings_stores')->count())->toBe(0); +}); + +it('skips and reports an invalid row instead of failing', function (): void { + DB::table('settings_stores')->insert([ + ['id' => '01J00000000000000000000001', 'kind' => 'store', 'name' => 'broken', 'config' => '{"layers":["missing"]}', 'created_at' => now(), 'updated_at' => now()], + ['id' => '01J00000000000000000000002', 'kind' => 'store', 'name' => 'fine', 'config' => '{"layers":["runtime"]}', 'created_at' => now(), 'updated_at' => now()], + ]); + app()->forgetScopedInstances(); + + settings()->store('fine')->set('a', 1); + Artisan::call('laranail::settings.doctor', ['--json' => true]); + + expect(settings()->store('fine')->get('a'))->toBe(1) + ->and(fn (): mixed => settings()->store('broken')->get('a'))->toThrow(UnknownStore::class) + ->and(Artisan::output())->toContain('Persisted entries skipped as invalid: store [broken]'); +}); + +it('merges persisted entries in configuration.sources order', function (): void { + config()->set('laranail.settings.stores.extra', ['layers' => ['runtime'], 'strict' => true]); + app()->forgetScopedInstances(); + settings()->persistedConfiguration()->saveStore('extra', ['layers' => ['runtime'], 'strict' => false]); + + expect(settings()->store('extra')->get('anything'))->toBeNull(); + + config()->set('laranail.settings.configuration.sources', ['database', 'config']); + app()->forgetScopedInstances(); + + expect(fn (): mixed => settings()->store('extra')->get('anything'))->toThrow(UnknownSetting::class, 'strict'); + + config()->set('laranail.settings.configuration.sources', ['config', 'nowhere']); + app()->forgetScopedInstances(); + + expect(fn (): mixed => settings()->get('x'))->toThrow(InvalidConfiguration::class, 'configuration.sources'); +}); + +it('saves and deletes definitions in the definitions table, never over code', function (): void { + $editor = settings()->persistedConfiguration(); + $definition = $editor->saveDefinition('site.theme', ['type' => 'string', 'default' => 'light', 'rules' => ['in:light,dark'], 'label' => 'Theme']); + + expect($definition->label)->toBe('Theme') + ->and(settings()->get('site.theme'))->toBe('light') + ->and(fn () => settings()->set('site.theme', 'blue'))->toThrow(InvalidSettingValue::class); + + app(DefinitionRegistry::class)->define('site.name')->register(); + + expect(fn (): Definition => $editor->saveDefinition('site.name', []))->toThrow(InvalidDefinition::class, 'code or configuration') + ->and(fn (): Definition => $editor->saveDefinition('site.x', ['type' => 'nope']))->toThrow(InvalidDefinition::class, 'unknown type') + ->and($editor->deleteDefinition('site.theme'))->toBeTrue() + ->and(settings()->get('site.theme'))->toBeNull(); +}); + +it('needs manage_stores and manage_definitions from an actor', function (): void { + $editor = settings()->as(user())->persistedConfiguration(); + + expect(fn () => $editor->saveStore('extra', ['layers' => ['runtime']]))->toThrow(AccessDenied::class, 'manage_stores') + ->and(fn (): array => $editor->entries())->toThrow(AccessDenied::class) + ->and(fn (): Definition => $editor->saveDefinition('a.b', []))->toThrow(AccessDenied::class, 'manage_definitions'); + + allowGates(Ability::ManageDefinitions); + config()->set('laranail.settings.verification.driver', 'none'); + app()->forgetScopedInstances(); + + expect(settings()->as(user())->persistedConfiguration()->saveDefinition('a.b', [])->key->value)->toBe('a.b'); +}); diff --git a/tests/Feature/Database/RestApiTest.php b/tests/Feature/Database/RestApiTest.php new file mode 100644 index 0000000..d752c45 --- /dev/null +++ b/tests/Feature/Database/RestApiTest.php @@ -0,0 +1,241 @@ +rebootWith([ + 'laranail.settings.http.enabled' => true, + 'laranail.settings.http.middleware' => ['api', 'auth'], + ]); + useDatabase(['stores.settings.owners' => ['user'], 'definitions.table' => true, 'configuration.persisted' => true, 'verification.driver' => 'none']); + Relation::morphMap(['user' => TestUser::class]); + allowGates(...Ability::cases()); + $this->actingAs(user(1)); +}); + +/** Call the API and check the response against the OpenAPI document. */ +function api(string $method, string $uri, array $data = [], array $headers = []): TestResponse +{ + $response = test()->json($method, '/api/settings/v1/' . $uri, $data, $headers); + $route = $response->baseRequest->route(); + + if (is_object($route) && $response->status() !== 204) { + $document = OpenApiDocument::build(app(Router::class)->getRoutes()->getRoutes()); + $operation = $document['paths']['/' . $route->uri()][strtolower($method)] ?? null; + $schema = $operation['responses'][(string) $response->status()]['content'] ?? null; + + expect($schema)->not->toBeNull(sprintf('%s %s answered %d, which the document does not describe', $method, $uri, $response->status())); + + $errors = new JsonSchema($document)->errors(json_decode((string) $response->getContent(), true), array_values($schema)[0]['schema']); + expect($errors)->toBe([], sprintf('%s %s does not match its schema', $method, $uri)); + } + + return $response; +} + +it('registers no route unless the API is enabled', function (): void { + $this->rebootWith([]); + + expect(collect(app(Router::class)->getRoutes()->getRoutes())->filter(fn ($route): bool => str_starts_with((string) $route->getName(), 'laranail-settings.api.')))->toHaveCount(0) + ->and(Artisan::call('laranail::settings.openapi'))->toBe(1); +}); + +it('reads and writes a setting with ETags and If-Match', function (): void { + $put = api('PUT', 'stores/settings/settings/site.name', ['value' => 'Acme'])->assertOk()->assertJsonPath('data.value', 'Acme')->assertJsonPath('data.version', 1); + $etag = $put->headers->get('ETag'); + + api('GET', 'stores/settings/settings/site.name')->assertOk()->assertHeader('ETag', $etag)->assertJsonPath('data.layer', 'database'); + api('PUT', 'stores/settings/settings/site.name', ['value' => 'Acme Ltd'], ['If-Match' => $etag])->assertOk()->assertJsonPath('data.version', 2); + api('PUT', 'stores/settings/settings/site.name', ['value' => 'Stale'], ['If-Match' => $etag]) + ->assertStatus(412) + ->assertHeader('Content-Type', 'application/problem+json') + ->assertJsonPath('type', 'https://opensource.simtabi.com/documentation/laranail/settings/problems/precondition-failed'); + + expect(settings()->get('site.name'))->toBe('Acme Ltd') + ->and(DB::table('settings_audit')->where('channel', 'rest')->where('action', 'update')->count())->toBe(2); +}); + +it('lists, explains, locks, unlocks and forgets, for the global value and an owner', function (): void { + settings()->set('site.name', 'Acme'); + settings()->set('theme', 'light'); + + api('GET', 'stores/settings/settings')->assertOk()->assertJsonCount(2, 'data'); + api('GET', 'stores/settings/settings?limit=1')->assertOk()->assertJsonPath('meta.next_cursor', 'site.name'); + api('PUT', 'stores/settings/owners/user/1/settings/theme', ['value' => 'dark'])->assertOk()->assertJsonPath('data.scope', 'user:1'); + api('GET', 'stores/settings/settings/theme/explain')->assertOk()->assertJsonPath('data.found', true); + api('POST', 'stores/settings/owners/user/1/settings/theme/lock')->assertOk(); + api('PUT', 'stores/settings/owners/user/1/settings/theme', ['value' => 'blue'])->assertStatus(423); + api('DELETE', 'stores/settings/owners/user/1/settings/theme/lock')->assertOk(); + api('DELETE', 'stores/settings/owners/user/1/settings/theme')->assertNoContent(); + api('GET', 'stores/settings/owners/user/9/settings/theme')->assertOk()->assertJsonPath('data.found', false)->assertJsonPath('data.version', 0); + api('GET', 'stores/settings/owners/nope/1/settings/theme')->assertNotFound(); + + expect(settings()->for(new OwnerRef('user', 1))->has('theme'))->toBeFalse(); +}); + +it('omits what the actor may not view, and refuses what they may not do', function (): void { + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + settings()->set('mail.password', TestCredentials::secret()); + settings()->set('site.name', 'Acme'); + Gate::define(Ability::ViewSensitive->gateName(), static fn (): bool => false); + Gate::define(Ability::Update->gateName(), static fn (): bool => false); + + $list = api('GET', 'stores/settings/settings')->assertOk(); + + expect(collect($list->json('data'))->pluck('key')->all())->toBe(['site.name']); + api('GET', 'stores/settings/settings/mail.password')->assertOk()->assertJsonPath('data.redacted', true)->assertJsonMissingPath('data.value'); + api('PUT', 'stores/settings/settings/site.name', ['value' => 'x'])->assertForbidden()->assertJsonPath('status', 403); + api('PUT', 'stores/settings/settings/site.name', [])->assertUnprocessable()->assertJsonStructure(['errors' => ['value']]); + api('GET', 'stores/nope/settings/site.name')->assertNotFound(); +}); + +it('answers 202 with a change request, and approves it through the API', function (): void { + app(DefinitionRegistry::class)->define('mail.host')->requiresApproval()->register(); + + $id = api('PUT', 'stores/settings/settings/mail.host', ['value' => 'smtp.test'])->assertStatus(202)->json('data.id'); + + api('GET', 'stores/settings/changes')->assertOk()->assertJsonPath('data.0.id', $id); + api('GET', 'stores/settings/changes/' . $id)->assertOk()->assertJsonPath('data.status', 'pending'); + api('POST', 'stores/settings/changes/' . $id . '/approve')->assertForbidden(); + + $this->actingAs(user(2)); + api('POST', 'stores/settings/changes/' . $id . '/approve', ['reason' => 'ok'])->assertOk()->assertJsonPath('data.status', 'applied'); + + $proposed = api('POST', 'stores/settings/changes', ['key' => 'mail.host', 'value' => 'other.test'])->assertStatus(202)->json('data.id'); + api('POST', 'stores/settings/changes/' . $proposed . '/cancel')->assertOk()->assertJsonPath('data.status', 'cancelled'); + $again = api('POST', 'stores/settings/changes', ['key' => 'mail.host', 'value' => 'x.test', 'owner' => ['alias' => 'user', 'id' => '1']])->json('data.id'); + $this->actingAs(user(1)); + api('POST', 'stores/settings/changes/' . $again . '/reject', ['reason' => 'no'])->assertOk()->assertJsonPath('data.status', 'rejected'); + api('POST', 'stores/settings/changes/' . $again . '/reject')->assertStatus(409); + api('GET', 'stores/settings/changes/01ARZ3NDEKTSV4RRFFQ69G5FAV')->assertNotFound(); + + expect(settings()->get('mail.host'))->toBe('smtp.test'); +}); + +it('pages history and rolls back', function (): void { + settings()->set('site.name', 'One'); + settings()->set('site.name', 'Two'); + + api('GET', 'stores/settings/settings/site.name/history?limit=1')->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.version', 2); + api('POST', 'stores/settings/settings/site.name/rollback', ['version' => 1])->assertOk()->assertJsonPath('data.value', 'One')->assertJsonPath('data.version', 3); + api('POST', 'stores/settings/settings/site.name/rollback', ['version' => 9])->assertStatus(409); + api('GET', 'audit?action=rollback')->assertOk()->assertJsonPath('data.0.action', 'rollback'); +}); + +it('manages categories, persisted configuration and definitions', function (): void { + api('POST', 'stores/settings/categories', ['slug' => 'mail', 'title' => 'Mail'])->assertCreated()->assertJsonPath('data.slug', 'mail'); + api('POST', 'stores/settings/categories', ['slug' => 'smtp', 'title' => 'SMTP'])->assertCreated(); + api('PATCH', 'stores/settings/categories/smtp', ['title' => 'Outgoing', 'parent' => 'mail'])->assertOk()->assertJsonPath('data.parent', 'mail')->assertJsonPath('data.title', 'Outgoing'); + api('GET', 'stores/settings/categories')->assertOk()->assertJsonCount(2, 'data'); + api('DELETE', 'stores/settings/categories/smtp')->assertNoContent(); + + api('PUT', 'configuration/stores/extra', ['config' => ['layers' => ['runtime']]])->assertOk()->assertJsonPath('data.kind', 'store'); + api('PUT', 'configuration/layers/scratch', ['config' => ['driver' => 'array']])->assertOk(); + api('GET', 'configuration')->assertOk()->assertJsonCount(2, 'data'); + api('GET', 'stores')->assertOk()->assertJsonCount(2, 'data'); + api('PUT', 'configuration/stores/broken', ['config' => ['layers' => ['missing']]])->assertUnprocessable(); + api('DELETE', 'configuration/stores/extra')->assertNoContent(); + + api('PUT', 'stores/settings/definitions/site.theme', ['attributes' => ['type' => 'string', 'default' => 'light']])->assertOk()->assertJsonPath('data.default', 'light'); + api('GET', 'stores/settings/definitions')->assertOk()->assertJsonPath('data.0.key', 'site.theme'); + api('GET', 'stores/settings/settings/site.theme')->assertOk()->assertJsonPath('data.value', 'light')->assertJsonPath('data.layer', 'default'); + api('DELETE', 'stores/settings/definitions/site.theme')->assertNoContent(); +}); + +it('exports, compares and imports', function (): void { + settings()->categories()->create(new NewCategory('mail', 'Mail')); + settings()->set('site.name', 'Acme'); + + $document = api('POST', 'stores/settings/export')->assertOk()->json('data'); + settings()->set('site.name', 'Changed'); + + api('POST', 'stores/settings/diff', ['document' => $document])->assertOk()->assertJsonPath('data.changed', ['global|site.name|']); + api('POST', 'stores/settings/import', ['document' => $document])->assertOk()->assertJsonPath('data.applied', false); + expect(settings()->get('site.name'))->toBe('Changed'); + api('POST', 'stores/settings/import', ['document' => $document, 'apply' => true])->assertOk()->assertJsonPath('data.updated', ['global|site.name|']); + api('POST', 'stores/settings/import', ['document' => ['format' => 'other']])->assertUnprocessable()->assertJsonPath('type', 'https://opensource.simtabi.com/documentation/laranail/settings/problems/invalid-import'); + + expect(settings()->get('site.name'))->toBe('Acme'); +}); + +it('answers a retried write from the idempotency cache instead of applying it twice', function (): void { + $first = api('PUT', 'stores/settings/settings/site.name', ['value' => 'Acme'], ['Idempotency-Key' => 'abc'])->assertOk(); + settings()->set('site.name', 'Moved on'); + $retry = api('PUT', 'stores/settings/settings/site.name', ['value' => 'Acme'], ['Idempotency-Key' => 'abc'])->assertOk(); + + expect($retry->headers->get('Idempotent-Replayed'))->toBe('true') + ->and($retry->getContent())->toBe($first->getContent()) + ->and(settings()->get('site.name'))->toBe('Moved on'); +}); + +it('needs an authenticated user and switches route groups off', function (): void { + auth()->logout(); + test()->json('GET', '/api/settings/v1/stores')->assertUnauthorized()->assertJsonPath('status', 401); + + $this->rebootWith(['laranail.settings.http.enabled' => true, 'laranail.settings.http.middleware' => ['api'], 'laranail.settings.http.routes' => ['approvals' => false]]); + + expect(app(Router::class)->getRoutes()->getByName('laranail-settings.api.changes.index'))->toBeNull() + ->and(app(Router::class)->getRoutes()->getByName('laranail-settings.api.settings.show'))->not->toBeNull(); + + test()->json('GET', '/api/settings/v1/stores')->assertUnauthorized()->assertJsonPath('type', 'https://opensource.simtabi.com/documentation/laranail/settings/problems/actor-required'); +}); + +it('generates an OpenAPI 3.1 document of every registered route', function (): void { + $path = sys_get_temp_dir() . '/laranail-settings-openapi-' . bin2hex(random_bytes(4)) . '.json'; + + expect(Artisan::call('laranail::settings.openapi', ['--output' => $path]))->toBe(0); + + $document = json_decode((string) file_get_contents($path), true); + $operations = collect($document['paths'])->flatMap(static fn (array $methods): array => array_column($methods, 'operationId')); + + expect($document['openapi'])->toBe('3.1.0') + ->and($operations)->toHaveCount(39) + ->and($operations->unique())->toHaveCount(39) + ->and(Artisan::call('laranail::settings.openapi'))->toBe(0) + ->and(Artisan::output())->toContain('"openapi": "3.1.0"'); +}); + +it('loads a Settable owner, so its parents take part in reads, and refuses one that does not exist', function (): void { + useDatabase(['stores.settings.owners' => ['owner', 'team'], 'stores.settings.inherits' => true, 'verification.driver' => 'none']); + Schema::create('owners', static function (Blueprint $table): void { + $table->id(); + $table->unsignedBigInteger('team_id')->nullable(); + }); + DB::table('owners')->insert(['id' => 5, 'team_id' => 3]); + Relation::morphMap(['owner' => SettingsOwner::class]); + settings()->for(new OwnerRef('team', 3))->set('theme', 'teal'); + + api('GET', 'stores/settings/owners/owner/5/settings/theme')->assertOk()->assertJsonPath('data.value', 'teal')->assertJsonPath('data.from', 'team:3'); + api('GET', 'stores/settings/owners/owner/6/settings/theme')->assertNotFound()->assertJsonPath('type', 'https://opensource.simtabi.com/documentation/laranail/settings/problems/unknown-owner'); + api('GET', 'stores/settings/owners/owner/bad%20id/settings/theme')->assertNotFound(); + + // Mapped only for URLs: addressed by alias and id, so no parents. + config()->set('laranail.settings.http.owners', ['member' => SettingsOwner::class]); + config()->set('laranail.settings.stores.settings.owners', ['owner', 'team', 'member']); + app()->forgetScopedInstances(); + api('GET', 'stores/settings/owners/member/5/settings/theme')->assertOk()->assertJsonPath('data.found', false); +}); diff --git a/tests/Feature/Database/SchemaMatrixTest.php b/tests/Feature/Database/SchemaMatrixTest.php index b607c58..7885c20 100644 --- a/tests/Feature/Database/SchemaMatrixTest.php +++ b/tests/Feature/Database/SchemaMatrixTest.php @@ -38,6 +38,7 @@ function switchFactors(): array 'categories_soft_deletes' => [false, true], 'tenancy' => ['none', 'column'], 'history' => [true, false], + 'approvals' => [true, false], ]; } @@ -66,10 +67,11 @@ function switchShapes(): array } // 141 pairs among the eight Phase 2b switches, plus tenancy's 2 values × the other 18 - // values = 177, plus history's 2 values × the other 20 values = 217 (Phase 4); the full - // product doubles from 1,152 to 2,304, and the pairwise set grows from 10 shapes to 11. - expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 2304 : 11) - ->and(count($all))->toBe(217) + // values = 177, plus history's 2 values × the other 20 values = 217 (Phase 4), plus the + // change requests table's 2 values × the other 22 values = 261 (Phase 4b); the full product + // doubles again from 2,304 to 4,608, and the pairwise set stays at 11 shapes. + expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 4608 : 11) + ->and(count($all))->toBe(261) ->and(array_diff_key($all, $covered))->toBe([]); })->group('matrix', 'mutation-excluded'); @@ -86,6 +88,7 @@ function switchShapes(): array 'categories.soft_deletes' => $shape['categories_soft_deletes'], 'tenancy.mode' => $shape['tenancy'], 'history.enabled' => $shape['history'], + 'approvals.table' => $shape['approvals'], 'stores.settings.owners' => $dedicated ? [] : ['user'], 'stores.settings.soft_deletes' => $shape['soft_deletes'], 'stores.settings.inherits' => true, @@ -142,6 +145,8 @@ function switchShapes(): array ->and(DB::table($ownerStore)->where('scope', 'user:1')->count())->toBe(1) ->and((int) DB::table($ownerStore)->where('scope', 'user:1')->value('version'))->toBe($shape['soft_deletes'] || $shape['history'] ? 4 : 3) ->and(Schema::hasTable('settings_history'))->toBe($shape['history']) + ->and(Schema::hasTable('settings_change_requests'))->toBe($shape['approvals']) + ->and($shape['approvals'] ? settings()->for($user)->propose('theme', 'dark')->scope : 'user:1')->toBe('user:1') ->and(array_map(static fn (HistoryEntry $entry): string => $entry->operation->value . ':' . $entry->version, $trail)) ->toBe($shape['history'] ? ['unlock:4', 'lock:3', 'set:2', 'forget:1', 'set:1'] : []) ->and($shape['history'] && $shape['tenancy'] === 'column' ? DB::table('settings_history')->distinct()->pluck('tenant')->all() : ['acme'])->toBe(['acme']) diff --git a/tests/Feature/Database/TransferTest.php b/tests/Feature/Database/TransferTest.php new file mode 100644 index 0000000..eb33fe1 --- /dev/null +++ b/tests/Feature/Database/TransferTest.php @@ -0,0 +1,224 @@ + ['user']]); + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); +}); + +function seedStore(): string +{ + $secret = TestCredentials::secret(); + settings()->categories()->create(new NewCategory('mail', 'Mail')); + settings()->categories()->create(new NewCategory('smtp', 'SMTP', parent: 'mail')); + settings()->set('site.name', 'Acme'); + settings()->set('mail.port', 587); + settings()->set('mail.password', $secret); + settings()->for(new OwnerRef('user', 7))->set('theme', 'dark'); + settings()->for(new OwnerRef('user', 7))->lock('theme'); + + return $secret; +} + +it('exports categories by slug and settings by identity, redacting secrets by default', function (): void { + $secret = seedStore(); + + $document = settings()->export(); + $json = $document->toJson(); + $settings = $document->settingsByIdentity(); + + expect($document->store)->toBe('settings') + ->and(array_map(static fn (ExportedCategory $category): ?string => $category->parent?->value, $document->categories))->toBe([null, 'mail']) + ->and(array_keys($settings))->toBe(['global|mail.password|', 'global|mail.port|', 'global|site.name|', 'user:7|theme|']) + ->and($settings['global|mail.port|']->value)->toBe(587) + ->and($settings['global|mail.password|']->redacted)->toBeTrue() + ->and($settings['user:7|theme|']->locked)->toBeTrue() + ->and($json)->not->toContain($secret) + ->and($json)->not->toContain('"id"') + ->and(DB::table('settings_audit')->where('action', AuditAction::Export->value)->count())->toBe(1); +}); + +it('exports secrets as ciphertext or plaintext only when asked, and plaintext needs view_sensitive', function (): void { + $secret = seedStore(); + allowGates(Ability::Export); + + expect(settings()->export(ExportMode::Ciphertext)->settingsByIdentity()['global|mail.password|']->ciphertext)->not->toBeNull()->not->toContain($secret) + ->and(settings()->export(ExportMode::Plaintext)->settingsByIdentity()['global|mail.password|']->value)->toBe($secret) + ->and(fn (): ExportDocument => settings()->as(user())->export(ExportMode::Plaintext))->toThrow(AccessDenied::class, 'view_sensitive'); +}); + +it('round-trips a store into an empty one through a dry run, then an apply', function (): void { + seedStore(); + $document = ExportDocument::fromJson(settings()->export(ExportMode::Ciphertext)->toJson()); + + useDatabase(['stores.settings.owners' => ['user']]); + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + + $preview = settings()->previewImport($document); + + expect($preview->applied)->toBeFalse() + ->and($preview->created)->toHaveCount(4) + ->and($preview->categories)->toBe(['mail', 'smtp']) + ->and(DB::table('settings')->count())->toBe(0); + + $report = settings()->import($document); + + expect($report->applied)->toBeTrue() + ->and(settings()->get('mail.port'))->toBe(587) + ->and(settings()->for(new OwnerRef('user', 7))->get('theme'))->toBe('dark') + // Untrusted: the lock in the file is not applied (G-10). + ->and((bool) DB::table('settings')->where('scope', 'user:7')->value('is_locked'))->toBeFalse() + ->and(settings()->categories()->get('smtp')->parent?->value)->toBe('mail') + ->and(settings()->compare($document)->isEmpty())->toBeFalse() + ->and(settings()->compare($document)->changed)->toBe(['global|mail.password|', 'user:7|theme|']) + ->and(settings()->previewImport($document)->unchanged)->toContain('global|site.name|') + ->and(DB::table('settings_audit')->where('action', AuditAction::Import->value)->count())->toBe(1) + ->and(DB::table('settings_audit')->where('action', AuditAction::Update->value)->count())->toBe(4); +}); + +it('skips redacted values and owners the store does not accept, and reports why', function (): void { + $document = ExportDocument::fromArray([ + 'format' => 'laranail/settings', + 'version' => 1, + 'store' => 'settings', + 'settings' => [ + ['scope' => 'global', 'key' => 'mail.password', 'redacted' => true, 'encrypted' => true], + ['scope' => 'team:3', 'key' => 'theme', 'value' => 'dark'], + ['scope' => 'global', 'key' => 'site.name', 'value' => 'Acme'], + ], + ]); + + $report = settings()->import($document); + + expect($report->created)->toBe(['global|site.name|']) + ->and(array_keys($report->skipped))->toBe(['global|mail.password|', 'team:3|theme|']) + ->and($report->skipped['team:3|theme|'])->toContain('does not accept owner alias [team]'); +}); + +it('applies locks and system categories only from a trusted import, through the command', function (): void { + seedStore(); + $path = sys_get_temp_dir() . '/laranail-settings-export-' . bin2hex(random_bytes(4)) . '.json'; + + expect(Artisan::call('laranail::settings.export', ['path' => $path, '--with-secrets' => true]))->toBe(0); + + useDatabase(['stores.settings.owners' => ['user']]); + + expect(Artisan::call('laranail::settings.import', ['source' => $path]))->toBe(0) + ->and(Artisan::output())->toContain('Dry run') + ->and(DB::table('settings')->count())->toBe(0) + ->and(Artisan::call('laranail::settings.import', ['source' => $path, '--apply' => true, '--trusted' => true]))->toBe(0) + ->and((bool) DB::table('settings')->where('scope', 'user:7')->value('is_locked'))->toBeTrue() + ->and(Artisan::call('laranail::settings.diff', ['path' => $path]))->toBe(1) + ->and(Artisan::output())->toContain('~ global|mail.password|')->not->toContain('user:7|theme|'); +}); + +it('asks for the store name before writing decrypted secrets', function (): void { + seedStore(); + $path = sys_get_temp_dir() . '/laranail-settings-export-' . bin2hex(random_bytes(4)) . '.json'; + + $this->artisan('laranail::settings.export', ['path' => $path, '--decrypt' => true]) + ->expectsQuestion('This writes decrypted secrets. Type the store name [settings] to continue', 'nope') + ->assertExitCode(1); + + expect(is_file($path))->toBeFalse() + ->and(Artisan::call('laranail::settings.export', ['path' => $path, '--decrypt' => true, '--confirm' => 'settings']))->toBe(0) + ->and(Artisan::call('laranail::settings.export'))->toBe(0) + ->and(Artisan::output())->toContain('"format": "laranail/settings"'); +}); + +it('refuses a file that is not an export', function (): void { + expect(fn (): ExportDocument => ExportDocument::fromJson('[1]'))->toThrow(InvalidImport::class, 'format: missing') + ->and(fn (): ExportDocument => ExportDocument::fromJson('{"format":"other"}'))->toThrow(InvalidImport::class, 'not a laranail/settings export') + ->and(fn (): ExportDocument => ExportDocument::fromJson('{"format":"laranail/settings","version":9}'))->toThrow(InvalidImport::class, 'version') + ->and(fn (): ExportDocument => ExportDocument::fromArray(['format' => 'laranail/settings', 'version' => 1, 'settings' => [['scope' => 'global', 'key' => 'Bad Key!']]]))->toThrow(InvalidImport::class, 'settings.0') + ->and(Artisan::call('laranail::settings.import', ['source' => '/nonexistent.json']))->toBe(1); +}); + +it('imports spatie/laravel-settings rows, keeping their locks for a trusted import', function (): void { + Schema::create('spatie_settings', static function (Blueprint $table): void { + $table->id(); + $table->string('group'); + $table->string('name'); + $table->boolean('locked')->default(false); + $table->json('payload'); + }); + DB::table('spatie_settings')->insert([ + ['group' => 'general', 'name' => 'site_name', 'locked' => false, 'payload' => json_encode('Acme')], + ['group' => 'general', 'name' => 'Site-Active', 'locked' => true, 'payload' => json_encode(true)], + ]); + + expect(Artisan::call('laranail::settings.import', ['source' => ':spatie_settings', '--from' => 'spatie', '--apply' => true, '--trusted' => true]))->toBe(0) + ->and(settings()->get('general.site_name'))->toBe('Acme') + ->and(settings()->get('general.site_active'))->toBeTrue() + ->and((bool) DB::table('settings')->where('key', 'general.site_active')->value('is_locked'))->toBeTrue() + ->and(Artisan::call('laranail::settings.import', ['source' => ':missing_table', '--from' => 'spatie']))->toBe(1); +}); + +it('imports toolkit\'s JSON store, flattening nested keys and keeping lists as values', function (): void { + $path = sys_get_temp_dir() . '/laranail-toolkit-' . bin2hex(random_bytes(4)) . '.json'; + file_put_contents($path, json_encode(['mail' => ['host' => 'smtp.test', 'cc' => ['a@x.test', 'b@x.test']], 'debug' => false])); + + $document = app(Importers::class)->get('toolkit')->read($path, new StoreName('settings')); + settings()->import($document); + + expect($document->source)->toBe('toolkit') + ->and(settings()->get('mail.host'))->toBe('smtp.test') + ->and(settings()->get('mail.cc'))->toBe(['a@x.test', 'b@x.test']) + ->and(settings()->get('debug'))->toBeFalse() + ->and(fn () => app(Importers::class)->get('toolkit')->read('/nonexistent', new StoreName('settings')))->toThrow(InvalidImport::class, 'not a file'); +}); + +it('imports akaunting/laravel-setting rows and skips rows scoped by the host', function (): void { + Schema::create('akaunting_settings', static function (Blueprint $table): void { + $table->id(); + $table->string('key'); + $table->text('value')->nullable(); + $table->unsignedBigInteger('company_id')->nullable(); + }); + DB::table('akaunting_settings')->insert([ + ['key' => 'invoice.prefix', 'value' => 'INV-', 'company_id' => null], + ['key' => 'invoice.prefix', 'value' => 'ACME-', 'company_id' => 3], + ]); + + settings()->import(app(Importers::class)->get('akaunting')->read(':akaunting_settings', new StoreName('settings'))); + + expect(settings()->get('invoice.prefix'))->toBe('INV-') + ->and(fn () => app(Importers::class)->get('nope'))->toThrow(InvalidConfiguration::class, 'laranail.settings.importers.nope'); +}); + +it('needs import to import and export to compare', function (): void { + $document = new ExportDocument('settings'); + + expect(fn (): ImportReport => settings()->as(user())->import($document))->toThrow(AccessDenied::class, 'import') + ->and(fn (): StoreDiff => settings()->as(user())->compare($document))->toThrow(AccessDenied::class, 'export') + ->and(settings()->as(Actor::system())->compare($document)->isEmpty())->toBeTrue(); +}); diff --git a/tests/Feature/Database/TypedSettingsTest.php b/tests/Feature/Database/TypedSettingsTest.php new file mode 100644 index 0000000..99f3fb6 --- /dev/null +++ b/tests/Feature/Database/TypedSettingsTest.php @@ -0,0 +1,182 @@ + ['user'], 'typed.classes' => [MailSettings::class]]); +}); + +it('maps properties to keys and loads defaults until values are stored', function (): void { + $mail = MailSettings::load(settings()); + + expect(array_map(static fn (TypedProperty $property): string => $property->key, MailSettings::properties()))->toBe([ + 'fromAddress' => 'mail.from_address', + 'port' => 'mail.port', + 'timeout' => 'mail.timeout', + 'secure' => 'mail.secure', + 'cc' => 'mail.cc', + 'plan' => 'mail.plan', + 'launchedAt' => 'mail.launched_at', + 'password' => 'mail.password', + 'siteName' => 'site.name', + ]) + ->and($mail->fromAddress)->toBe('hello@example.test') + ->and($mail->plan)->toBe(Plan::Free) + // typed.classes registered the defaults as definitions: the key-value API sees them too. + ->and(settings()->get('mail.port'))->toBe(25); +}); + +it('writes through the key-value engine, so both APIs hold the same rows (parity)', function (): void { + $secret = TestCredentials::secret(); + $mail = MailSettings::load(settings()); + $mail->fromAddress = 'ops@acme.test'; + $mail->port = 587; + $mail->timeout = 2.5; + $mail->secure = true; + $mail->cc = ['a@acme.test']; + $mail->plan = Plan::Pro; + $mail->launchedAt = new DateTimeImmutable('2026-01-02T03:04:05+00:00'); + $mail->password = $secret; + $mail->save(); + $typedRows = DB::table('settings')->orderBy('key')->pluck('value', 'key')->all(); + + expect(settings()->get('mail.from_address'))->toBe('ops@acme.test') + ->and(settings()->get('mail.plan'))->toBe('pro') + ->and(settings()->get('mail.password'))->toBe($secret) + ->and($typedRows['mail.password'])->not->toContain($secret) + ->and(array_keys($typedRows))->not->toContain('site.name'); + + // The same values through the key-value API, into an empty database, store the same payloads. + useDatabase(['stores.settings.owners' => ['user'], 'typed.classes' => [MailSettings::class]]); + foreach (['mail.from_address' => 'ops@acme.test', 'mail.port' => 587, 'mail.timeout' => 2.5, 'mail.secure' => true, 'mail.cc' => ['a@acme.test'], 'mail.plan' => 'pro', 'mail.launched_at' => '2026-01-02T03:04:05+00:00', 'mail.password' => $secret] as $key => $value) { + settings()->set($key, $value); + } + $kvRows = DB::table('settings')->orderBy('key')->pluck('value', 'key')->all(); + unset($typedRows['mail.password'], $kvRows['mail.password']); + + $loaded = MailSettings::load(settings()); + + expect($kvRows)->toBe($typedRows) + ->and($loaded->plan)->toBe(Plan::Pro) + ->and($loaded->launchedAt?->format('Y-m-d H:i:s'))->toBe('2026-01-02 03:04:05') + ->and($loaded->cc)->toBe(['a@acme.test']) + ->and($loaded->password)->toBe($secret) + ->and($loaded->timeout)->toBe(2.5); +}); + +it('saves only what changed, as the handle\'s actor, for an owner', function (): void { + allowGates(Ability::View, Ability::ViewSensitive, Ability::Update); + $owner = settings()->as(user(3))->for(new OwnerRef('user', 3)); + $mail = MailSettings::load($owner); + $mail->port = 2525; + $mail->save(); + + expect(DB::table('settings')->where('scope', 'user:3')->pluck('key')->all())->toBe(['mail.port']) + ->and(DB::table('settings_audit')->where('action', 'update')->where('actor_id', '3')->count())->toBe(1) + ->and(app(MailSettings::class)->port)->toBe(25) + ->and(MailSettings::load(settings()->for(new OwnerRef('user', 3)))->port)->toBe(2525); + + Gate::define(Ability::Update->gateName(), static fn (): bool => false); + $mail->port = 1; + + expect(fn () => $mail->save())->toThrow(AccessDenied::class); +}); + +it('refuses a stored value its property cannot hold, and a type it cannot map', function (): void { + useDatabase(['stores.settings.owners' => ['user'], 'typed.classes' => []]); + app()->forgetInstance(DefinitionRegistry::class); + settings()->set('mail.port', 'not a number'); + + expect(fn (): MailSettings => MailSettings::load(settings()))->toThrow(TypeMismatch::class, 'mail.port') + ->and(fn (): array => BrokenSettings::properties())->toThrow(InvalidDefinition::class, 'stdClass') + ->and(fn () => new MailSettings()->save())->toThrow(TypeMismatch::class, 'was not loaded'); +}); + +it('copies every property to another handle when one is given', function (): void { + $mail = MailSettings::load(settings()); + $mail->save(settings()->for(new OwnerRef('user', 8))); + + expect(DB::table('settings')->where('scope', 'user:8')->count())->toBe(9); +}); + +it('renames, moves, adds and deletes keys in a settings migration', function (): void { + useDatabase(['stores.settings.owners' => ['user'], 'stores.archive' => ['layers' => ['database'], 'owners' => ['team']]], stores: ['archive']); + settings()->set('mail.from', 'a@acme.test'); + settings()->for(new OwnerRef('user', 1))->set('mail.from', 'b@acme.test'); + settings()->for(new OwnerRef('user', 1))->lock('mail.from'); + settings()->set('legacy.flag', true); + + $migration = new class extends SettingsMigration + { + public function up(): void + { + $this->settings()->rename('mail.from', 'mail.from_address'); + $this->settings()->move('legacy.flag', 'settings', 'archive'); + $this->settings()->add('site.name', 'Acme'); + $this->settings()->add('mail.from_address', 'ignored'); + $this->settings()->delete('nothing.here'); + } + }; + $migration->up(); + + expect(settings()->get('mail.from_address'))->toBe('a@acme.test') + ->and(settings()->for(new OwnerRef('user', 1))->get('mail.from_address'))->toBe('b@acme.test') + ->and((bool) DB::table('settings')->where('scope', 'user:1')->where('key', 'mail.from_address')->value('is_locked'))->toBeTrue() + ->and(DB::table('settings')->where('key', 'mail.from')->count())->toBe(0) + ->and(settings()->store('archive')->get('legacy.flag'))->toBeTrue() + ->and(settings()->get('legacy.flag'))->toBeNull() + ->and(settings()->get('site.name'))->toBe('Acme') + ->and(DB::table('settings_audit')->where('action', 'migrate')->count())->toBe(5) + ->and(settings()->history()->global()->key('mail.from_address')->get())->toHaveCount(1); +}); + +it('resolves a typed settings class from the container, loaded', function (): void { + settings()->set('mail.port', 465); + + expect(app(MailSettings::class)->port)->toBe(465) + ->and(app(MailSettings::class))->toBeInstanceOf(TypedSettings::class); +}); + +it('refuses a typed.classes entry that is not a typed settings class', function (): void { + config()->set('laranail.settings.typed.classes', [stdClass::class]); + app()->forgetInstance(DefinitionRegistry::class); + + expect(fn () => app(DefinitionRegistry::class))->toThrow(InvalidConfiguration::class, 'typed.classes'); +}); + +it('registers definitions with the caster alias a #[Type] names', function (): void { + $class = new class extends TypedSettings + { + #[Type('string')] + public string $region = 'eu'; + }; + $definitions = $class::register(app(DefinitionRegistry::class)); + + expect($definitions[0]->type)->toBe('string') + ->and($definitions[0]->default)->toBe('eu') + ->and($class::register(app(DefinitionRegistry::class)))->toBe([]); +}); diff --git a/tests/Fixtures/Typed/BrokenSettings.php b/tests/Fixtures/Typed/BrokenSettings.php new file mode 100644 index 0000000..91898b7 --- /dev/null +++ b/tests/Fixtures/Typed/BrokenSettings.php @@ -0,0 +1,13 @@ + */ + public array $cc = []; + + public Plan $plan = Plan::Free; + + public ?DateTimeImmutable $launchedAt = null; + + #[Encrypted] + public ?string $password = null; + + #[Key('site.name')] + public string $siteName = 'Acme'; +} diff --git a/tests/Fixtures/Typed/Plan.php b/tests/Fixtures/Typed/Plan.php new file mode 100644 index 0000000..c67a470 --- /dev/null +++ b/tests/Fixtures/Typed/Plan.php @@ -0,0 +1,11 @@ + $document the OpenAPI document */ + public function __construct(private array $document) {} + + /** + * Every way `$value` breaks `$schema`, as `path: problem`; empty when it conforms. + * + * @param array $schema + * + * @return list + */ + public function errors(mixed $value, array $schema, string $path = '$'): array + { + if (isset($schema['$ref']) && is_string($schema['$ref'])) { + return $this->errors($value, $this->resolve($schema['$ref']), $path); + } + + $errors = []; + + if (isset($schema['type'])) { + $types = (array) $schema['type']; + + if (! array_any($types, fn (mixed $type): bool => is_string($type) && $this->is($value, $type))) { + return [sprintf('%s: expected %s, got %s', $path, implode('|', $types), get_debug_type($value))]; + } + } + + if (isset($schema['enum']) && is_array($schema['enum']) && ! in_array($value, $schema['enum'], true)) { + $errors[] = sprintf('%s: %s is not one of %s', $path, json_encode($value), json_encode($schema['enum'])); + } + + if (array_key_exists('const', $schema) && $value !== $schema['const']) { + $errors[] = sprintf('%s: expected %s', $path, json_encode($schema['const'])); + } + + if (is_int($value) || is_float($value)) { + if (isset($schema['minimum']) && $value < $schema['minimum']) { + $errors[] = sprintf('%s: below %s', $path, json_encode($schema['minimum'])); + } + + if (isset($schema['maximum']) && $value > $schema['maximum']) { + $errors[] = sprintf('%s: above %s', $path, json_encode($schema['maximum'])); + } + } + + if (is_array($value) && ! array_is_list($value) || $value instanceof stdClass) { + $object = (array) $value; + + foreach ((array) ($schema['required'] ?? []) as $required) { + if (! array_key_exists((string) $required, $object)) { + $errors[] = sprintf('%s: missing %s', $path, $required); + } + } + + foreach ((array) ($schema['properties'] ?? []) as $name => $property) { + if (array_key_exists((string) $name, $object) && is_array($property)) { + $errors = [...$errors, ...$this->errors($object[$name], $property, $path . '.' . $name)]; + } + } + } + + if (is_array($value) && array_is_list($value) && isset($schema['items']) && is_array($schema['items'])) { + foreach ($value as $index => $item) { + $errors = [...$errors, ...$this->errors($item, $schema['items'], $path . '[' . $index . ']')]; + } + } + + return $errors; + } + + /** @return array */ + private function resolve(string $ref): array + { + $name = substr($ref, strlen('#/components/schemas/')); + $schemas = $this->document['components']['schemas'] ?? []; + + return is_array($schemas) && is_array($schemas[$name] ?? null) ? $schemas[$name] : throw new LogicException('Unknown schema reference ' . $ref); + } + + private function is(mixed $value, string $type): bool + { + return match ($type) { + 'null' => $value === null, + 'string' => is_string($value), + 'integer' => is_int($value), + 'number' => is_int($value) || is_float($value), + 'boolean' => is_bool($value), + // JSON decoded as arrays: an empty array is an empty object or an empty list. + 'array' => is_array($value) && array_is_list($value), + 'object' => $value instanceof stdClass || (is_array($value) && ($value === [] || ! array_is_list($value))), + default => false, + }; + } +} diff --git a/tests/Unit/AccessValuesTest.php b/tests/Unit/AccessValuesTest.php index de89229..8db2997 100644 --- a/tests/Unit/AccessValuesTest.php +++ b/tests/Unit/AccessValuesTest.php @@ -42,7 +42,7 @@ function subjectFor(string $key = 'site.name'): Subject expect(AuditAction::fromAbility($ability)->value)->toBe($ability->value); } - expect(AuditAction::cases())->toHaveCount(19) + expect(AuditAction::cases())->toHaveCount(25) ->and(AuditAction::Configure->value)->toBe('configure'); }); diff --git a/tests/Unit/DocsConformanceTest.php b/tests/Unit/DocsConformanceTest.php index 5b0ab27..886cb9e 100644 --- a/tests/Unit/DocsConformanceTest.php +++ b/tests/Unit/DocsConformanceTest.php @@ -6,10 +6,10 @@ uses(AssertsDocsConformance::class); -// Floor = the 26 pages shipped today (5 guides, 15 reference, 6 recipes). Raise it as pages +// Floor = the 41 pages shipped today (5 guides, 25 reference, 11 recipes; counted 2026-11-10). Raise it as pages // are added; a glob that suddenly matches fewer has broken rather than found a clean tree. it('conforms to the org docs standard', function (): void { - $this->assertDocsConformToStandard(dirname(__DIR__, 2), 26); + $this->assertDocsConformToStandard(dirname(__DIR__, 2), 41); expect(true)->toBeTrue(); }); From 98f430c0f0d839d31c4a3f001f1279f0080f57f3 Mon Sep 17 00:00:00 2001 From: Imani Manyara Date: Tue, 10 Nov 2026 08:22:32 -0500 Subject: [PATCH 4/4] Treat a no-op change request update as held on MySQL --- .../Database/ChangeRequestRepository.php | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/Services/Database/ChangeRequestRepository.php b/src/Services/Database/ChangeRequestRepository.php index 294015f..3789c45 100644 --- a/src/Services/Database/ChangeRequestRepository.php +++ b/src/Services/Database/ChangeRequestRepository.php @@ -199,12 +199,30 @@ public function transition(ChangeRequest $request, array $from, ChangeStatus $to ]; } - $updated = $this->database->attempt(new StoreName($request->store), fn (): int => $this->database->scoped($this->table()) - ->where('id', $request->id) - ->whereIn('status', array_map(static fn (ChangeStatus $status): string => $status->value, $from)) - ->update($columns)); + $statuses = array_map(static fn (ChangeStatus $status): string => $status->value, $from); - return $updated > 0; + return $this->database->attempt(new StoreName($request->store), function () use ($request, $statuses, $columns): bool { + $updated = $this->database->scoped($this->table()) + ->where('id', $request->id) + ->whereIn('status', $statuses) + ->update($columns); + + if ($updated > 0) { + return true; + } + + // MySQL reports changed rows, not matched rows, so an update writing identical + // values reports 0. That can only happen when the target status is itself one of + // the allowed ones (approved -> approved); any other target means somebody else won. + if (! in_array($columns['status'], $statuses, true)) { + return false; + } + + return $this->database->scoped($this->table()) + ->where('id', $request->id) + ->where('status', $columns['status']) + ->exists(); + }); } /**